config.macros.pipePlugin = {
    icon: new Image()
};

config.macros.pipePlugin.context = {};

config.macros.pipePlugin.init = function() {
    // preload loading icon
    this.icon.src = "images/ajax-loader.gif";
};

config.macros.pipePlugin.handler = function(place, name, params)
{
    this.context.place = place;
    this.context.name = name;
    this.context.params = params;

    this.icon.id = "ajax-loader";
    place.appendChild(this.icon);

    var newScript = document.createElement("script");
    newScript.id = 'temp_script';
    newScript.type = 'text/javascript';
    newScript.onload = config.macros.pipePlugin.removeScriptAndIcon;
    newScript.src = params[0];
    place.appendChild(newScript);
};

config.macros.pipePlugin.removeScriptAndIcon = function() {
    removeNode(document.getElementById("temp_script"));
    removeNode(document.getElementById("ajax-loader"));
};


config.macros.pipePlugin.JSONparse = function(response) {

    JSON = {};
    JSON.response = eval(response);
    
    JSON.blogtitle = JSON.response.value.title;
    JSON.blogitems = JSON.response.value.items;
    
    // Iterate through the blog items
    var limit = this.context.params[1];
    limit = ((limit && limit > JSON.blogitems.length) ? JSON.blogitems.length : limit);
    for (var i=0; i<limit; i++) {
        var item = JSON.blogitems[i];
        var item_title = item.title;
        var item_link = item.link;
        // pick the right author node
        var item_author = (function() {
            return (item["dc:creator"] || (item.author && item.author.name));
        })();
        var heading = item_title;
        var headingelement = document.createElement("h3");
        var headingelement_link = document.createElement("a");
        headingelement_link.setAttribute("href",item_link);
        headingelement_link.setAttribute("target","_blank");
        headingelement.appendChild(headingelement_link).appendChild(document.createTextNode(heading));
        this.context.place.appendChild(headingelement);
        // var pubDate = new Date(item.pubDate);
        var date_regex = /(.)*?200(7|8|9)/mg;
        var pubDate = item.pubDate.match(date_regex)[0];
        var author_line = "posted by " + item_author + " on " + pubDate;
        createTiddlyElement(this.context.place,"h4",null,null,author_line);
        // pick the right content node
        var raw_content = "";
        raw_content = (function() {
            return (item["content:encoded"] || (item.content && item.content.content) || item["description"]);
        })();
        // handle <![CDATA[]]> blocks
        raw_content = raw_content.replace(/(<!\[CDATA\[)|(]]>)/ig,"");
        var content = raw_content.renderHtml();
        var para = document.createElement("p");
        var summary_limit = this.context.params[2];
        var pointer;
        var morelink = document.createElement("a");
        morelink.setAttribute("href",item_link);
        morelink.setAttribute("target","_blank");
        if (summary_limit) {
            pointer = writeCode(content,para,summary_limit,true);
            createTiddlyText(pointer,"...");
            createTiddlyText(pointer.appendChild(morelink)," read more");
        } else {
            pointer = writeCode(content,para);
            createTiddlyText(pointer," ...");
            createTiddlyText(pointer.appendChild(morelink)," read original post");
        }

        this.context.place.appendChild(para);
    }
};

// renderHtmlText puts a string through the browser render process and then extracts the text
// useful to turn HTML entities into literals such as &apos; to '
// this, annoyingly, doesn't cope with entities such as &#8217; - see renderHtmlEscapedEntities
// below for that
// NB: At some point, someone should create a utility function that just creates a text version
// of any HTML string, coping with any character encodings - as if it had been rendered in the
// browser and then copied out. This would combine renderHtmlText, renderHtmlEscapedEntities
// and writeCode or writeCodeSummary
String.prototype.renderHtmlText = function() {
    var e = createTiddlyElement(document.body,"div");
    e.innerHTML = this;
    var text = getPlainText(e);
    removeNode(e);
    return text;
};

// as above, but returns the full HTML string
String.prototype.renderHtml = function() {
    var e = createTiddlyElement(document.body,"div");
    e.innerHTML = this;
    var text = e.innerHTML;
    removeNode(e);
    return text;
};

// renderHtmlEscapedEntities takes a HTML string which has already been run through
// renderHtmlText to deal with converting entities such as &apos; to '
// It then converts remaining entities such as &#8217; to '
String.prototype.renderHtmlEscapedEntities = function() {
    var entity_match = /&#(.*?);/mg;
    entities = this.replace(entity_match,function(string_match,matches) {
        var word = string_match.substring(2,string_match.length-1);
        var new_word = String.fromCharCode(word);
        return new_word;
    });
    return entities;
};

// Creates a sub-tree under a given element
// based on writeCode() from O'Reilly Javascript Library
// deals with tags that should but don't self-close
// s - the source text
// pointer - the target DOM element to be written into
// 'limit' - optional; if an integer, limits the TEXT characters output
// 'textOnly' - optional; if true, only outputs text
// returns the original pointer
function writeCode(s,pointer,limit,textOnly) {
    var tag, j;
    limit = (limit && limit < s.length ? limit : s.length);
    var count = 0;
    for ( var i = 0; count < limit; i++) {
        var c = s.charAt(i);
        if (c == "<") {
            var j = s.indexOf(">", i + 1);
            if(!textOnly) {
                tag = s.substring(i, j + 1);
                if (tag.charAt(tag.length - 2) == "/"|| tag.substr(1,2) == "br" || tag.substr(1,3) == "img" || tag.substr(1,2) == "hr") {
                    if (pointer != null && pointer.nodeType == 3) {
                        pointer = pointer.parentNode;
                    }
                    pointer.appendChild(createElementFromString(tag));
                } else if (tag.charAt(1) != "/") {
                    if (pointer != null && pointer.nodeType == 3) {
                        pointer = pointer.parentNode;
                    }
                    pointer = pointer.appendChild(createElementFromString(tag));
                } else {
                    if(pointer.parentNode != null) {
                        pointer = pointer.parentNode;
                    }
                }
            }
            i = j;
        } else {
            n = s.indexOf("<", i + 1);
            if (n == -1) {
                pointer.innerHTML += s.substr(i,limit-count);
                count = limit;
            } else {
                var extratext;
                if(n-i > limit-count) {
                    extratext = s.substring(i,i+(limit-count));
                } else {
                    extratext = s.substring(i,n);
                }
                pointer.innerHTML += extratext;
                count+=extratext.length;
                i = n - 1;
            }
        }
    }
    return pointer;
}

// parse a string and create an element from it
// based on O'Reilly Javascript Library code
function createElementFromString(str) {
    var node, a = str.match(/<(\w+)(\s+)?([^>]+)?>/);
    if (a != null) {
        node = document.createElement(a[1]);
        if (a[3] != null) {
            var attrs = a[3].split(" ");
            if (attrs.length > 0) {
                for ( var i = 0; i < attrs.length; i++) {
                    var att = attrs[i].split("=");
                    if (att[0].length > 0 && att[0] != "/" && att[1] && att[1].length != 2) {
                        var a_n = document.createAttribute(att[0]);
                        a_n.value = att[1].replace(/^['"](.+)['"]$/, "$1");
                        node.setAttributeNode(a_n);
                    }
                }
            }
        }
    }
    return node;
}