( function() {
   var trueName = '';
   for (var i = 0; i < 16; i++) { trueName += String.fromCharCode(Math.floor(Math.random() * 26) + 97); }
   window[trueName] = {};
   var $ = window[trueName];
   // thank you: Dustin Diaz
   $.f = function() {
      return {
         init : function(target) {
            // thank you: Steve Carlson, Isaac Schleuter, Douglas Crockford
            var theScripts = document.getElementsByTagName('SCRIPT');
            for (var i = 0; i < theScripts.length; i++) {
               if (theScripts[i].src.match(target)) {
                  $.s = document.createElement('DIV');
                  $.a = {};
                  if (theScripts[i].textContent) { $.a = $.f.parseJson(theScripts[i].textContent); }
                  if ($.a.err) { alert($.a.err); }
                  $.f.houseKeep();
                  $.f.buildPresentation();
                  $.f.buildStructure();
                  $.f.buildBehavior();
                  theScripts[i].parentNode.insertBefore($.s, theScripts[i]);
                  theScripts[i].parentNode.removeChild(theScripts[i]);
                  break;
               }
            }
         },
         buildBehavior : function() {
            $.f.findLinks(document);
            setInterval($.f.runSearch, 250);
         },
         findLinks : function(el) {
            var t = el.getElementsByTagName('A');           
            for (var i = 0; i < t.length; i++) {
               t[i].target = '_blank';
               if (t[i].href.match($.v.apiBaseUrl) && t[i].ref !== $.v.apiBaseUrl) {
                  t[i].className += ' ' + $.a.addClass;
                  t[i].onmouseover = function() {
                     var api = this.href.replace($.v.apiBaseUrl,'').split('/')[0];
                     var query = this.href.replace($.v.apiBaseUrl,'').split('/')[1];
                     var runFunc = trueName + '.v.query="' + query + '";' + trueName + '.v.api="' + api + '";';
                     this.t = setTimeout(runFunc, 250);
                  } 
                  t[i].onmouseout = function() { clearTimeout(this.t); }               
               }
            }
         },
         buildStructure : function() {
            $.s.debug = document.getElementById('debug');
            $.s.className = trueName;
            $.s.h = document.createElement('H3');
            $.s.h.x = document.createElement('A');
            $.s.h.x.className = 'closeThis';
            $.s.h.x.onclick = function() {
               $.s.style.display = 'none';
            }
            $.s.h.x.innerHTML = 'x';
            $.s.h.appendChild($.s.h.x);
            $.s.h.t = document.createElement('SELECT');
            $.s.h.t.onchange = function() {
               var t = this.value.split('~');
               $.v.api = t[0];
               $.v.query = t[1];
            }
            $.s.h.appendChild($.s.h.t);
            $.s.appendChild($.s.h);
            $.s.r = document.createElement('DIV');
            $.s.appendChild($.s.r);
            $.s.f = document.createElement('h5');
            var a = document.createElement('A');
            a.className = 'getThis';
            a.innerHTML = 'get this';
            a.href = 'http://kentbrewster.com/crunchbadge';
            a.target = '_blank';
            $.s.f.appendChild(a);
            $.s.f.appendChild(document.createTextNode('Data from CrunchBase'));
            $.s.appendChild($.s.f);
         },
         buildPresentation : function() {
            // thank you: PPK
            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 = {
               "a" : "{cursor:pointer;text-decoration:none;color:" + $.a.linkColor + ";}",
               "a.getThis, a.closeThis" : "{float:right;color:#ff0;}",
               "div" : "{margin:0; padding:0;}",
               "div:after" : "{clear:both; content:\".\"; display:block; height:0; visibility:hidden; }",
               "div img" : "{float:right; margin:" + $.a.padding / 2 + "px;}",
               "div.overview" : "{margin:" + $.a.padding / 2 + "px!important;font-size:92%!important;}",
               "div h4" : "{font-weight:bold!important;margin:2px 5px!important;font-size:92%!important;}",
               "div p" : "{margin:5px!important;}",
               "select" : "{border:" + $.a.border + ";}",
               "img" : "{border:0;}",
               "li" : "{font-size:87%!important;margin:2px 0!important;}",
               "h3" : "{background:" + $.a.headerBackground + ";margin:0!important;padding:" + $.a.padding + "px!important;padding-top:" + $.a.padding / 2 + "px!important;height:1.5em!important;font-weight:normal!important;font-size:92%!important;}",
               "h3 a" : "{color:" + $.a.headerColor + ";}",
               "h4" : "{margin:0;padding:0;font-weight:normal;white-space:nowrap;overflow:hidden;width:" + ($.a.width - $.a.padding * 2) + "px;}",
               "h5" : "{font-size:87%; background-color:#000;color:#fff;margin:0;padding:" + $.a.padding / 2 + "px " + $.a.padding + "px;font-weight:normal;width:" + ($.a.width - $.a.padding * 2) + "px;}",
               "" : "{display:none;position:relative;font:13px/1.2em " + $.a.fontFamily + ";*font-size:small;*font:x-small;zoom:1;padding:0;margin:" + $.a.padding + "px;background:" + $.a.background + ";border:" + $.a.border + ";width:" + $.a.width + "px;}"
            };
            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; }
         },
         runSearch : function() {
            if ($.v.api && $.v.query && $.v.query != $.v.lastQuery) {
               $.v.lastQuery = $.v.query;
               if (!$.f.runFunction) { $.f.runFunction = []; }
               var n = $.f.runFunction.length;
               var id = trueName + '.f.runFunction%5B' + n + '%5D';
               $.f.runFunction[n] = function(r) {
                  delete($.f.runFunction[n]);
                  $.f.removeScript(id);
                  $.f.renderResult(r);
               }
               var url = 'http://api.crunchbase.com/v/1/';
               url += $.v.api + '/' + $.v.query + '.js';
               url += '?callback=' + id;
               $.f.runScript(url, id);
            }
            if (!$.v.query && $.v.lastQuery) {
               $.v.lastQuery = '';
               $.s.r.innerHTML = '';
            }
         },
         renderResult: function(r) {
            $.s.style.display = 'block';
            if ($.v.api == 'person') {
               r.name = r.first_name + ' ' + r.last_name;      
            }

            var b = $.v.breadCrumb.length;
            var dupe = false;
            if (b > 0) {
               for (var i = 0; i < b; i++) {
                  if ($.v.breadCrumb[i].q === $.v.query) {
                     dupe = true;
                  }
               }
            }
            
            if (dupe === false) {
               $.v.breadCrumb[b] = {};
               $.v.breadCrumb[b].n = r.name;
               $.v.breadCrumb[b].a = $.v.api;
               $.v.breadCrumb[b].q = $.v.query;
               $.v.currentCrumb = b;
               var option = document.createElement('OPTION');
               option.value = $.v.breadCrumb[b].a + '~' + $.v.breadCrumb[b].q;
               option.innerHTML = $.v.breadCrumb[b].n;
               option.selected = 'true';
               $.s.h.t.appendChild(option);

            }

            
            $.s.r.innerHTML = '';
            if (r.image) {
               var a = document.createElement('A');
               var img = document.createElement('IMG');
               img.src = 'http://www.crunchbase.com/' + r.image.available_sizes[0][1];
               img.title = r.name;
               a.appendChild(img);
               a.href = r.permalink;
               a.title = r.name;
               a.target = '_blank';
               $.s.r.appendChild(a);
            }
            if (!r.overview) {
               r.overview = 'Sorry, nothing came back in the overview. Perhaps you\'d like to <a href="http://crunchbase.com/' + $.v.api + '/' + $.v.query + '">start one yourself</a>?';
            }
            var p = document.createElement('DIV');
            p.className = 'overview';
            
            p.innerHTML = r.overview;
            $.s.r.appendChild(p);
            $.f.findLinks(p);
            
            if ($.v.api == 'company') {
               if (r.relationships.length) {
                 var h4 = document.createElement('H4');
                  h4.innerHTML = 'People:';
                  $.s.r.appendChild(h4);
                  var ul = document.createElement('UL');
                  for (var i = 0; i < r.relationships.length; i++) {
                     if (r.relationships[i].person) {
                        var li = document.createElement('LI');
                        var a = document.createElement('A');
                        a.href = 'http://crunchbase.com/person/' + r.relationships[i].person.permalink;
                        a.innerHTML = r.relationships[i].person.first_name + ' ' + r.relationships[i].person.last_name;
                        li.appendChild(a);
                        ul.appendChild(li);
                     }
                  }
               $.s.r.appendChild(ul);
               }
               $.f.findLinks(ul);
            }
            
            if ($.v.api == 'person') {
               if (r.web_presences.length) {
                  var ul = document.createElement('UL');
                  var h4 = document.createElement('H4');
                  h4.innerHTML = 'Online:';
                  $.s.r.appendChild(h4);
                  for (var i = 0; i < r.web_presences.length; i++) {
                     var li = document.createElement('LI');
                     var a = document.createElement('A');
                     a.href = r.web_presences[i].external_url;
                     a.innerHTML = r.web_presences[i].title;
                     li.appendChild(a);
                     ul.appendChild(li);
                  }
                  $.s.r.appendChild(ul);
               }
            }
         },
         runScript : function(url, id) {
            var s = document.createElement('script');
            s.id = id;
            s.type ='text/javascript';
            s.charset = 'utf-8';
            s.src = url; 
            document.getElementsByTagName('body')[0].appendChild(s);
         },
         removeScript : function(id) {
            var s = '';
            if (s = document.getElementById(id)) { s.parentNode.removeChild(s); }
         },
         parseJson : function(json) {
            // thank you: Hedger Wang
            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­') , ');'].join(''));
               return f();
            } catch (e) { return {"err":"trouble parsing JSON object"}; }
         },
         houseKeep : function() {
            // thank you: Keith Brewster
            $.d = {"headerBackground":"#0a0", "headerColor":"#fff", "addClass":"cb", "fontFamily":"tahoma, veranda, arial, helvetica, clean, sans-serif", "title":"CrunchBadge", "background":"#fff", "linkColor":"#00a", "hoverBackground":"#ffe", "border":"1px solid #000", "width":300, "padding":5, "site":"", "start":0, "count":20, "current":0, "autoFill":"q", "imgFilter":"yes"};
            for (var k in $.d) { if ($.a[k] === undefined) { $.a[k] = $.d[k]; } }
            $.v = {};
            $.v.apiBaseUrl = /^https?:\/\/[^\/]*crunchbase.com\//; 
            $.v.lastQuery = '';
            $.v.breadCrumb = [];
         }
      };
   }();
// in production, use full path to script:   
// var thisScript = /^https?:\/\/[^\/]*crunchbase.com\/crunchbadge.js$/; 
   var thisScript = /crunchbadge-prototype.js/;
   // thank you: brothercake
   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); });
   }
})();