var IfElse = IfElse || {};

IfElse.Config = {
    debug:  true,
    feeds:  [
                {   src:  "/archives/index.xml",    callback: "ifelse",      destination: "li.ifelse div.item"  },
                {   src:  "/data/ffffound.xml",     callback: "ffffound",    destination: "li.ffffound div.item"  },
                {   src:  "/data/timespeople.xml",  callback: "timespeople", destination: "li.timespeople div.item"  }
            ]
};

IfElse.App = {
    init: function() {
        if (window['console'] === undefined || !IfElse.Config.debug) {
            window.console = { log: function(){} };
        }
        $$('div.more').each(function(item){
            Event.observe(item, 'click', IfElse.App.toggleView.bindAsEventListener(0, item));
        });
        IfElse.Feeds.init();
    },
    toggleView: function (e, item) {
        if (Event.element(e).tagName.toLowerCase()!="a") {
            var li     = item.up('li');
            var isWide = li.hasClassName('wide') || li.hasClassName('wider');

            if (!item.hasClassName('open')) {
                item.parentNode.style.zIndex = 10;
                item.style.zIndex            = 10;
                new Effect.Scale (item, 200, {
                    scaleX: !isWide, duration: 0.5, scaleContent: false, scaleMode: { originalWidth: 152.5, originalHeight: 152.5 }
                });
                
            //  Close other open items, if any
                var openItem = $$('div.open')[0];
                if (openItem) {
                    var liOpen     = openItem.up('li');
                    var isWideOpen = liOpen.hasClassName('wide') || liOpen.hasClassName('wider');
                    new Effect.Scale(openItem, 50, {
                        scaleX: !isWideOpen, duration: 0.3, scaleContent: false, scaleMode: { originalWidth: 280, originalHeight: 280 },
                        afterFinish: function() {
                            openItem.removeClassName('open');
                            openItem.parentNode.style.zIndex = 1;
                            openItem.style.zIndex            = 1;
                        } 
                    });
                }
            } else {
                item.parentNode.style.zIndex = 1;
                item.style.zIndex            = 1;
                new Effect.Scale(item, 50, {
                    scaleX: !isWide, duration: 0.5, scaleContent: false, scaleMode: { originalWidth: 280, originalHeight: 280 }
                });
            }
            item.toggleClassName('open');
        }
    }
};

IfElse.Feeds = {
    init:    function() {
        feeds = IfElse.Config.feeds;
        for (var f=0; f<feeds.length; f++) {
            this.getFeed(feeds[f].src, feeds[f].callback, feeds[f].destination);
        }
        setTimeout(this.cleanup, 9000);
    },

    getFeed: function(src, callback, destination) {
        var feedFile = src + '?' + Math.floor(Math.random()*111);
        new Ajax.Request(feedFile,
        {
            method:    'get',
            onSuccess: function(transport){
                if(src.indexOf(".js")>0) {
                    var x = eval(transport.responseText) || false;
                } else {
                    var x = transport.responseText       || false;
                }
                eval( "IfElse.Feeds.drawFeed_" + callback + "(x, destination)"); // eval isn't always evil, just usually...
            },
            onFailure: function(){ 
            //  do nothing...
                console.log('major fail. you know what you must do.');
            }
        });
    },

    drawFeed_ffffound: function(x, destination) {

        var html      = [];
        var column1   = [];
        var column2   = [];
        var fragment  = [];

    //  Convert to XML object
        var xmlObj    = (new DOMParser()).parseFromString(x, "text/xml");
        var root      = xmlObj.getElementsByTagName('rss')[0];
        var channels  = root.getElementsByTagName("channel");
        var items     = channels[0].getElementsByTagName("item");
        var itemCount = 0;

        for (var i=0; i<8; i++) {
            var title, url, pubdate, thumb, source, savedby;
            for (var b=0; b<items[i].childNodes.length; b++) {
                var n     = items[i].childNodes.item(b);
                var nn    = n.nodeName.split(":");
                var base  = nn[nn.length-1];

                switch(base) {
                    case "title":
                        title       = n.firstChild.nodeValue;
                        break;
                    case "link":
                        url         = n.firstChild.nodeValue;
                        break;
                    case "pubDate":
                        pubdate     = n.firstChild.nodeValue;
                        break;
                    case "thumbnail":
                        thumb       = n.getAttribute("url");
                        break;
                    case "source":
                        source      = n.getAttribute("referer");
                        break;
                    case "savedby":
                        savedby     = n.getAttribute("count");
                        break;
                    case "description":
                        description = n.firstChild.nodeValue;
                        break;
                    default:
                    //  default
                }
            }

            if (itemCount < 6) {
                html.push("<a href='" + url +"' title='" + title + "' target='_blank'><img src='" + thumb + "' width='155' class='ffffound'/></a>"  );
                itemCount++;
            }
        }
        $$(destination)[0].innerHTML = html.join('');
    },

    drawFeed_ifelse: function(x,destination) {

        var html     = [];
        var column1  = [];
        var column2  = [];
        var fragment = [];

    //  Convert to XML object
        var xmlObj   = (new DOMParser()).parseFromString(x, "text/xml");
        var root     = xmlObj.getElementsByTagName('rss')[0];
        var channels = root.getElementsByTagName("channel");
        var items    = channels[0].getElementsByTagName("item");

        html.push("<table>\n<tr>\n");

        for (var i=0; i<items.length; i++) {
            var title, url, thumb, desc;
            var isLast = '';
            for (var b=0; b<items[i].childNodes.length; b++) {

                var n    = items[i].childNodes.item(b);
                var nn   = n.nodeName.split(":");
                var base = nn[nn.length-1];

                switch(base) {
                    case "title":
                        title       = n.firstChild.nodeValue;
                        break;
                    case "description":
                        desc        = n.firstChild.nodeValue;
                        break;
                    case "link":
                        url         = n.firstChild.nodeValue;
                        break;
                    case "thumbnail":
                        thumb       = n.getAttribute("url");
                        break;
                    default:
                    //  default
                }
            }
            if (i==items.length-1) {    isLast = " class='last'"; }
            var htmlImg  = (thumb.length>1) ? "<a href='" + url +"' title='" + title + "'><img src='" + thumb + "' alt='" + title + "' /></a>" : "";
            html.push("<td" + isLast + ">" + htmlImg + "<p>" + desc + "</p></td>\n" );
        }
        html.push("</tr>\n</table>\n");
    },

    drawFeed_timespeople: function(r,destination) {

        var html     = [];
        var list     = [];

    //  Convert to XML object
        var xmlObj   = (new DOMParser()).parseFromString(r, "text/xml");
        var root     = xmlObj.getElementsByTagName('rss')[0];
        var channels = root.getElementsByTagName("channel");
        var items    = channels[0].getElementsByTagName("item");

        var swapThis = [ "Michael Donohoe", "commented on", "blog post", " feature", "interactive graphic", " an ", " a " ];
        var withThis = [ "",                "commented",    "blog",      "",         "graphic",             " / ",    " / "   ];

        for(var i=0; i<8; i++){

            var title, url, thumb, desc, pubdate, headline, info, action, type;

            for (var b=0; b<items[i].childNodes.length; b++) {

                var n      = items[i].childNodes.item(b);
                var nn     = n.nodeName.split(":");
                var base   = nn[nn.length-1];
                var nValue = (n.firstChild) ? n.firstChild.nodeValue : '';

                switch(base) {
                    case "title":
                        title   = nValue;
                        break;
                    case "description":
                        desc    = nValue;
                        break;
                    case "link":
                        url     = nValue;
                        break;
                    case "pubDate":
                        pubdate = nValue;
                        break;
                    default:
                    //  default
                }

            }

        //  Custom edits
            title    = title.split(" : ");
            info     = title[0];
            headline = title[1];
            
            console.log(info);

            for (var z=0; z<swapThis.length; z++) {
                info = info.replace(swapThis[z], withThis[z]);
            }


            info     = info.split(" / ");
            console.log(info);
            info     = info[0] + " / <b>" + info[1] + "</b>";


        //  Limit description
            if (desc.length>85) {
                descWords = desc.split(" ");
                descWords.length = 16;
                desc = descWords.join(" ") + "&hellip;";
            }

            list.push("<li><span>" +info+ "</span><br/><a href='" +url+ "' target='_blank'>" +headline+ "</a><p>" +desc+ "</p></li>\n");
        }

        html.push("<ul class='inline'>"+list.join('')+"</ul>\n");
        $$(destination)[0].innerHTML = html.join('');
    },

    cleanup: function() {
    //  Clear loading animation if feed not processed
        IfElse.Config.feeds.each(function(feed){
            var destination = $$(feed.destination)[0];
            if (destination) {
                console.log(destination);
                if (destination.innerHTML.indexOf('loading.gif')>0) {
                    destination.innerHTML = '<h3>Error loading data, bye-bye...</h3>';
                    new Effect.Fade (destination.up('li'), { duration: 2 });
                }
            }
        });
    }
};

IfElse.App.init();