// twitterati badge --  updated 10Jun2008

// as always, use at your own risk

// copyright Kent Brewster 2008

// see http://kentbrewster.com/twitterati for info




( function() { 

   var trueName = '';

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

      trueName += String.fromCharCode(Math.floor(Math.random() * 26) + 97); 

   }

   window[trueName] = {};

   var $ = window[trueName];

   $.f = function() {

      return { 

         runFunction : [],

         init : function(target) {

            var theScripts = document.getElementsByTagName('SCRIPT');

            for (var i = 0; i < theScripts.length; i++) {

               if (theScripts[i].src.match(target)) {

                  $.a = {};

                  if (theScripts[i].innerHTML) {

                     $.a = $.f.parseJson(theScripts[i].innerHTML);

                  }

                  if ($.a.err) {

                     alert('bad json!');

                  }

                  $.f.loadDefaults();

                  $.f.buildStructure();

                  $.f.buildPresentation();

                  theScripts[i].parentNode.insertBefore($.w, theScripts[i]);

                  theScripts[i].parentNode.removeChild(theScripts[i]);

                  break;

               }

            }         

         },

         parseJson : function(json) {

            this.parseJson.data = json;

            if ( typeof json !== 'string') {

               return {"err":"trying to parse a non-string JSON object"};

            }

            try {

               var f = Function(['var document,top,self,window,parent,Number,Date,Object,Function,',

                  'Array,String,Math,RegExp,Image,ActiveXObject;',

                  'return (' , json.replace(/<\!--.+-->/gim,'').replace(/\bfunction\b/g,'function&shy;') , ');'].join(''));

               return f();

            } catch (e) {

               return {"err":"trouble parsing JSON object"};

            }

         },

         loadDefaults : function() {

            $.d = { 

               "user":"kentbrew",

               "headerText" : " and friends",

               "height" : 350,

               "width" : 250,

               "background" : "white",

               "border" : "0px solid black",

               "userFontSize" : "inherit",

               "userColor" : "inherit",

               "headerBackground" : "transparent", 

               "headerColor" : "white",

               "evenBackground" : "inherit",

               "oddBackground" : "#eee",

               "thumbnailBorder" : "1px solid black",

               "thumbnailSize" : 24,

               "padding" : 3

            };

            for (var k in $.d) { if ($.a[k] === undefined) { $.a[k] = $.d[k]; } }

         },

          buildPresentation : function () {

            var ns = document.createElement('style');

            document.getElementsByTagName('head')[0].appendChild(ns);

            if (!window.createPopup) {

               ns.appendChild(document.createTextNode(''));

               ns.setAttribute("type", "text/css");

            }

            var s = document.styleSheets[document.styleSheets.length - 1];

            var rules = {

               "" : "{zoom:1;margin:0;padding:0;width:" + ($.a.width) + "px;background:" + $.a.background + ";border:" + $.a.border + ";font:13px/1.2em tahoma, veranda, arial, helvetica, clean, sans-serif;*font-size:small;*font:x-small;}",

               "a" : "{cursor:pointer;text-decoration:none;}",

               "a:hover" : "{text-decoration:underline;}",

               "img":"{float:left; height:" + $.a.thumbnailSize + "px;width:" + $.a.thumbnailSize + "px;border:" + $.a.thumbnailBorder + ";margin-right:" + $.a.padding + ";}",

               "cite, date":"{margin:0 0 0 4px;padding:0;display:block;font-style:normal;font-size:" + $.a.userFontSize + ";line-height:" + ($.a.thumbnailSize/2) + "px;}",

               "date:after" : "{clear:both; content:\".\"; display:block; height:0; visibility:hidden; }",

               "h3 a, h4 a" : "{font-size:92%; color:" + $.a.headerColor + ";}",

               "h3" : "{margin:0!important;padding:" + $.a.padding + ";font-weight:bold;background:" + $.a.headerBackground + " url('http://twitter.com/favicon.ico') " + $.a.padding + "px 50% no-repeat;text-indent:" + ($.a.padding + 16) + "px;}",

               "h3.loading" : "{background-image:url('http://l.yimg.com/us.yimg.com/i/us/my/mw/anim_loading_sm.gif')}",

               "h4" : "{font-weight:normal; background:" + $.a.headerBackground + ";text-align:right;margin:0;padding:" + $.a.padding + "px;}",

               "ul":"{margin:0!important; padding:0!important; height:" + $.a.height + "px;width:" + $.a.width + "px;overflow:auto;}",

               "p" : "{margin:0!important; padding:0!important; }",

               "ul li":"{margin:0!important;padding:" + $.a.padding + "px!important;list-style:none}",

               "ul li.odd" : "{background:" + $.a.oddBackground + ";}"

            };

            var ieRules = "";

            for (r in rules) {

               var selector = '.' + trueName + ' ' + r;

               if (!window.createPopup) {

                  var theRule = document.createTextNode(selector + rules[r]);

                  ns.appendChild(theRule);

               } else {

                  ieRules += selector + rules[r];

               }

            } 

            if (window.createPopup) { s.cssText = ieRules; }

         },

         buildStructure : function() {

            $.w = document.createElement('DIV');

            $.w.className = trueName;         

            $.w.h = document.createElement('H3');

            $.w.h.a = document.createElement('A');

            $.w.h.a.innerHTML = $.a.user + $.a.headerText;

            $.w.h.a.href = 'http://twitter.com/' + $.a.user;

            $.w.h.a.target = '_twitter';

            $.w.h.appendChild($.w.h.a);

            $.w.appendChild($.w.h);

            $.w.r = document.createElement('UL');

            $.w.appendChild($.w.r);

            $.w.f = document.createElement('H4');

            var a = document.createElement('A');

            a.innerHTML = 'get this';

            a.target = '_blank';

            a.href = 'http://kentbrewster.com/twitterati';

            $.w.f.appendChild(a);

            $.w.appendChild($.w.f);

            $.f.runSearch();

         },

         runSearch : function() {

            $.w.h.className = 'loading';

            $.w.r.innerHTML = '';

            if (!$.f.runFunction) { $.f.runFunction = []; }

            var n = $.f.runFunction.length;

            var id = trueName + '.f.runFunction[' + n + ']';

            $.f.runFunction[n] = function(r) {

               delete($.f.runFunction[n]);

               $.f.removeScript(id);

               $.f.renderResult(r.value.items); 

            };

            var url = 'http://pipes.yahoo.com/pipes/pipe.run?_id=kIRJZQM33RGr9Zkb9YS63A&_render=json&n=20';

            url += '&_callback=' + id;

            url += '&u=' + $.a.user;

            $.f.runScript(url, id);

         },

         changeUserTo : function(el) {

            $.a.user = el.rel;

            if (!el.rev) {

               el.rev = $.a.user;

            }

            $.w.h.a.innerHTML = el.rev + $.a.headerText;

            $.w.h.a.href = 'http://twitter.com/' + el.rel;

            $.f.runSearch(); 

         },

         renderResult: function(r) { 

            $.w.h.className = '';

            for (var i = 0; i < r.length; i++) {

               var li = document.createElement('LI');

               if (i % 2) { li.className = 'odd'; }

               var icon = document.createElement('A');

               if (r[i].u) {

                  icon.href = r[i].u;

                  icon.target = '_blank'; 

               }

               var img = document.createElement('IMG');

               img.src = r[i].n;

               img.title = r[i].t + $.a.headerText;

               icon.appendChild(img);

               li.appendChild(icon); 

               

               var user = document.createElement('CITE');

               var a = document.createElement('A');

               a.rel = r[i].k;

               a.rev = r[i].t;

               a.innerHTML = r[i].t; 

               a.href = 'http://twitter.com/' + r[i].k;

               a.onclick = function() {

                  $.f.changeUserTo(this);

                  return false;

               };

               user.appendChild(a);

               li.appendChild(user);

               var updated = document.createElement('DATE');

               updated.innerHTML = r[i].d.split(/\+/)[0];

               li.appendChild(updated);

               var p = document.createElement('P');

               var raw = r[i].p;

               var cooked = raw.replace(/\/u([^ ]+)/gi, "&#$1;");

               cooked = cooked.replace(/http:\/\/([^ ]+)/g, "<a href=\"http://$1\" target=\"_blank\">http://$1</a>");

               var woo = "@<a class=\"changeUserTo\">$1</a>";

               cooked = cooked.replace(/@([\w*]+)/g, woo);

               cooked = cooked.replace(/#([\w*]+)/g, "#<a target=\"_summize\" href=\"http://summize.com/search?tag=$1\">$1</a>");

               p.innerHTML = cooked;

               li.appendChild(p);

               var a = p.getElementsByTagName('A');

               for (var j = 0; j < a.length; j++) {

                  if (a[j].className == 'changeUserTo') {

                     a[j].className = '';

                     a[j].href = 'http://twitter.com/' + a[j].innerHTML;

                     a[j].rel = a[j].innerHTML;

                     a[j].onclick = function() { 

                        $.f.changeUserTo(this); 

                        return false;

                     } 

                  }

               }

               $.w.r.appendChild(li);

            }         

         },

         runScript : function(url, id) {

            var s = document.createElement('script');

            s.id = id;

            s.type ='text/javascript';

            s.src = url;

            document.getElementsByTagName('body')[0].appendChild(s);

         },

         removeScript : function(id) {

            if (document.getElementById(id)) {

               var s = document.getElementById(id);

               s.parentNode.removeChild(s);

            }

         }         

      };

   }();

//   var thisScript = /^https?:\/\/[^\/]*r8ar.com\/twitterati.js$/;

   var thisScript = /twitterati.js$/;

   if(typeof window.addEventListener !== 'undefined') {

      window.addEventListener('load', function() { $.f.init(thisScript); }, false);

   } else if(typeof window.attachEvent !== 'undefined') {

      window.attachEvent('onload', function() { $.f.init(thisScript); });

   }

} )();