YUI.add('social-renderer', function(Y) {
    var getClassName = Y.ClassNameManager.getClassName,
        sub = Y.Lang.sub,
        LINK_RE =/((?:https?|s?ftp|ssh)\:\/\/[^"\s<>]*[^.,;'">\:\s<>\)\]\!])/g,
        classname_social = getClassName('social'),
        classname_social_title = getClassName('social', 'title'),
        classname_social_entry = getClassName('social', 'entry'),
        YQL_QUERY_PATTERN = /^(?:select|set|use)\s+/i,
        SOCIAL_RENDERER = Y.Base.create("SocialRenderer",
            Y.Widget, [Y.WidgetStdMod], {
                // Instance Variables
                TITLE_TEMPLATE: '<h3 class="' + classname_social_title + '">' +  '{title}</h3>',
                ENTRY_TEMPLATE: '<li class="' + classname_social_entry + '">' +  '{text}</li>',
                _socialRenderUI: function() {
                    var cb = this.get('contentBox');
                    if (!cb.one('ul')) {
                        cb.append(sub('<ul><li>{loading}</li></ul>', this.get('strings')));
                    }
                },
                renderUI: function() {
                    this._socialRenderUI();
                },
                syncUI: function() {
                    this._getResults();
                },
                _formatLinks: function(text) {
                    return text.replace(LINK_RE, "<a href='$1'>$1</a>");
                },
                _getResults: function(cb) {
                    var src = this.get('source'), context = this;
                    if (YQL_QUERY_PATTERN.test(src)) {
                        cb = cb || function(r) {
                            var list = this.get('contentBox').one('ul');
                            Y.Array.each(r.results, function(val) {
                                list.append(sub(this.ENTRY_TEMPLATE, val));
                            });
                        };
                        Y.use('yql', function() {
                            if (context._prepareQuery) {
                                src = context._prepareQuery(src);
                            }
                            var yql = Y.YQL(src, {
                                on: {
                                    success: cb,
                                    failure: function() {
                                        this.get('contentBox').one('ul li').setContent("Error retrieving data.");
                                    }
                                },
                                context: context
                            });

                        });
                    } else {
                        Y.error("Unknown query pattern.");
                    }
                }
            }, {
                // Static Varibles
                ATTRS: {
                    source: {},
                    strings: {
                        value: {
                            loading: "Loading..."
                        }
                    }
                }
            });
    Y.SocialRenderer = SOCIAL_RENDERER;
}, "0.0.1", { requires: ['widget', 'widget-stdmod'], optional: ['yql'] });

YUI.add('social-twitter', function(Y) {
    var sub = Y.Lang.sub,
        USERNAME_RE = /@(\w+)/g;
    Y.SocialRenderer.Twitter = Y.Base.create("Twitter",
        Y.SocialRenderer, [], {
            ENTRY_TEMPLATE: "<li><p>{text}</p><p class='time'>{created_at}</p></li>",
            renderUI: function() {
                var cb = this.get('contentBox');
                if (!cb.one('h3')) {
                    cb.append(sub(this.TITLE_TEMPLATE, { title: sub(this.get('strings.title'), { username: this.get('username') }) }));
                }
                this._socialRenderUI();
            },
            syncUI: function() {
                this._getResults(function(response) {
                    var list = this.get('contentBox').one('ul');
                    list.setContent('');
                    Y.Array.each(response.query.results.statuses.status, function(val) {
                        list.append(sub(this.ENTRY_TEMPLATE, {
                            text: this._formatLinks(val.text).replace(USERNAME_RE, "<a href='http://twitter.com/$1'>@$1</a>"),
                            created_at: Y.toRelativeTime(new Date(val.created_at))
                        }));
                    }, this);
                });
            },
            _prepareQuery: function(query) {
                return sub(query, { username: this.get('username') });
            }
        }, {
            ATTRS: {
                source: {
                    value: "select * from twitter.user.timeline where screen_name='{username}';"
                },
                username: {
                    validator: Y.Lang.isString
                },
                strings: {
                    value: {
                        loading: "Loading...",
                        title: "{username}'s Latest Tweets"
                    }
                }
            }
        });

}, "0.0.1", { requires: ["social-renderer", "gallery-torelativetime", 'yql'] });

YUI.add('social-atom', function(Y) {
    var sub = Y.Lang.sub;
    Y.SocialRenderer.ATOM = Y.Base.create("ATOM",
        Y.SocialRenderer, [], {
            ENTRY_TEMPLATE: "<li><a href='{href}'>{title}</a><span class='time'>{time}</span></li>",
            renderUI: function() {
                var cb = this.get('contentBox');
                if (!cb.one('h3')) {
                    cb.append(sub(this.TITLE_TEMPLATE, { title: sub(this.get('strings.title'), { name: this.get('name') }) }));
                }
                this._socialRenderUI();
            },
            syncUI: function() {
                this._getResults(function(response) {
                    var list = this.get('contentBox').one('ul');
                    list.setContent('');
                    Y.Array.each(response.query.results.entry, function(val) {
                        list.append(sub(this.ENTRY_TEMPLATE, {
                            href: val.link.href,
                            title: val.title,
                            time: Y.toRelativeTime(new Date(val.published))
                        }));
                    }, this);
                });
            },
            _prepareQuery: function(query) {
                return sub(query, { feed: this.get('feed') });
            }
        }, {
            ATTRS: {
                source: {
                    value: "select * from atom where url='{feed}';"
                },
                feed: {
                    validator: Y.Lang.isString
                },
                name: {
                    validator: Y.Lang.isString,
                    value: "Blog Posts"
                },
                strings: {
                    value: {
                        loading: "Loading...",
                        title: "{name}"
                    }
                }
            }
        });
}, "0.0.1", { requires: ["social-renderer", "gallery-torelativetime", 'yql'] });
YUI.add('social-github', function(Y) {
    var sub = Y.Lang.sub,
        USERNAME_RE = /@(\w+)/g;
    Y.SocialRenderer.GitHub = Y.Base.create("Github",
        Y.SocialRenderer, [], {
            ENTRY_TEMPLATE: '<li><h4>{title}</h4>{content}</a></li>',
            renderUI: function() {
                var cb = this.get('contentBox');
                if (!cb.one('h3')) {
                    cb.append(sub(this.TITLE_TEMPLATE, { title: this.get('strings.title')}));
                }
                this._socialRenderUI();
            },
            syncUI: function() {
                this._getResults(function(response) {
                    var list = this.get('contentBox').one('ul'),
                        filters = this.get('filter'), //.split(','),
                        data = response.query.results.entry,
                        index;
                    list.setContent('');
                    Y.Array.each(data, function(val) {
                        list.append(sub(this.ENTRY_TEMPLATE, {
                            content: val.content.content,
                            title: val.title
                        }));
                    }, this);
                });
            },
            _prepareQuery: function(query) {
                return sub(query, { username: this.get('username') });
            }
        }, {
            ATTRS: {
                source: {
                    value: "select * from atom where url='https://github.com/{username}.atom';"
                },
                username: {
                    validator: Y.Lang.isString
                },
                strings: {
                    value: {
                        loading: "Loading...",
                        title: "Githhub Activity"
                    }
                }
            }
        });
}, "0.0.1", { requires: ["social-renderer", 'yql'] });

YUI.add('social-tiptheweb', function(Y) {
    var sub = Y.Lang.sub,
        USERNAME_RE = /@(\w+)/g;
    Y.SocialRenderer.TipTheWeb = Y.Base.create("TipTheWeb",
        Y.SocialRenderer, [], {
            ENTRY_TEMPLATE: '<li>{amount} tip for <a href="{uri}">{title}</a></li>',
            TITLE_DATA_TEMPLATE: "<a href='{tipstream}'>{name}'s {title}</a>",
            renderUI: function() {
                var cb = this.get('contentBox');
                if (!cb.one('h3')) {
                    cb.append(sub(this.TITLE_TEMPLATE, { title: this.get('strings.title')}));
                }
                this._socialRenderUI();
            },
            syncUI: function() {
                this._getResults(function(response) {
                    var cb = this.get('contentBox'),
                        list = cb.one('ul'),
                        header = cb.one('h3'),
                        filters = this.get('filter'), //.split(','),
                        data = response.query.results.json,
                        index;
                    list.setContent('');
                    if (data.account.publishesName) {
                        header.setContent(sub(this.TITLE_DATA_TEMPLATE, {
                            tipstream: data.account.tipstreamURL,
                            name: data.account.name,
                            title: this.get('strings.title')
                        }));
                    }
                    Y.Array.each(data.tips, function(val) {
                        list.append(sub(this.ENTRY_TEMPLATE, {
                            uri: val.link,
                            title: val.title,
                            amount: this._formatTipAmount(val.amountCents)
                        }));
                    }, this);
                });
            },
            _formatTipAmount: function(amountCents) {
                if (amountCents >= 100) {
                    return "$" + Math.Floor(amountCents / 100) + "." + (amountCents % 100);
                } else {
                    return "$0." + amountCents;
                }
            },
            _prepareQuery: function(query) {
                return sub(query, { tipstream: this.get('tipstream') });
            }
        }, {
            ATTRS: {
                source: {
                    value: "select * from json where url='http://tiptheweb.org/tipstream/{tipstream}/?format=json'"
                },
                tipstream: {
                    validator: Y.Lang.isString
                },
                strings: {
                    value: {
                        loading: "Loading...",
                        title: "TipStream"
                    }
                }
            }
        });
}, "0.0.1", { requires: ["social-renderer", 'yql'] });

YUI().use('node', 'social-tiptheweb', 'social-github', 'social-atom', 'social-twitter', 'yql', function(Y) {
    var lists = Y.one('#socials'), element,
        twitter = new Y.SocialRenderer.Twitter({username: 'foxxtrot'}),
        atom = new Y.SocialRenderer.ATOM({feed: 'http://feeds.feedburner.com/MadBeautifulIdeas', name: "Mad, Beautiful, Ideas"}),
        github = new Y.SocialRenderer.GitHub({username: "foxxtrot"}),
        ttw = new Y.SocialRenderer.TipTheWeb({tipstream: "zyy6w73h4mp20"});
    lists.replace('<div id="socials" class="yui3-g"><div class="yui3-u-1-2"></div><div class="yui3-u-1-2"></div></div>');
    lists = Y.all('#socials div');
    lists.addClass('js-socials');

    element = Y.Node.create('<div></div>');
    lists.item(0).append(element);
    atom.render(element);

    lists.item(0).append("<a href='http://stackexchange.com'><img src='http://stackexchange.com/users/flair/fe78f769da0b4c30b7f1c2481ebac33b.png' width='208' height='58' alt='combined Stack Exchange profiles for foxxtrot' title='combined Stack Exchange profiles for foxxtrot'></a>");

    element = Y.Node.create('<div></div>');
    lists.item(0).append(element);
    ttw.render(element);

    lists.item(0).append("<a class='linkedin-profileinsider-inline' href='http://www.linkedin.com/pub/jeff-craig/10/447/546'>On LinkedIn</a>");
    Y.Get.script("http://www.linkedin.com/js/public-profile/widget-os.js");

    element = Y.Node.create('<div></div>');
    lists.item(1).append(element);
    github.render(element);
    element = Y.Node.create('<div></div>');
    lists.item(1).append(element);
    twitter.render(element);
});

