(function(){
  if (!window.SHAREIN) window.SHAREIN = {};
  if (window.SHAREIN.renderBadge) return;
  
  // embed stylesheet
  var stylesheetID = 'sharein-badge-stylesheet';
  if (!document.getElementById(stylesheetID)){
    var l = document.createElement('link');
    l.setAttribute('rel', 'stylesheet');
    l.setAttribute('href', 'http://sharein.com/stylesheets/badge.css');
    l.setAttribute('id', 'sharein-badge-stylesheet');
    document.getElementsByTagName('head')[0].appendChild(l);
  }
  
  var i = 0;
  var badges = [];
  
  // render badge
  window.SHAREIN.renderBadge = function(opts){
    if (!opts) opts = {};
    badges.push(opts);
    document.write('<div class="sharein-badge" id="sharein-badge-' + i + '"></div>');
    i++;
  };

  // execute bookmarklet
  var reset = null;
  window.SHAREIN.execBookmarklet = function(mode, title, url, description){
    if (reset != null) clearTimeout(reset);
    if (title && url){
      window.SHAREIN.title = title;
      window.SHAREIN.url = url;
      window.SHAREIN.description = description || '';
    }
    window.SHAREIN.mode = (mode) ? mode.replace(/\b[a-z]/g, function(match){
      return match.toUpperCase();
    }) + 'Share' : '';
    
    // launch!
    var s = document.createElement('script');
    s.setAttribute('src', 'http://sharein.com/javascripts/bookmarklet.js?noCache='+ +new Date());
    document.body.appendChild(s);
    
    // reset it back to prevent conflict with the actual bookmarklet from browser
    reset = setTimeout(function(){
      window.SHAREIN.title = '';
      window.SHAREIN.url = '';
      window.SHAREIN.description = '';
      window.SHAREIN.mode = '';
    }, 5000);
  };
  
  var addEvent = function(obj, type, fn){
    if (obj.addEventListener){
      obj.addEventListener(type, fn, false);
    } else if (obj.attachEvent){
      obj['e'+type+fn] = fn;
      obj[type+fn] = function(){ obj['e'+type+fn](window.event); }
      obj.attachEvent('on'+type, obj[type+fn]);
    }
  };
  
  addEvent(window, 'load', function(){
    for (var i in badges){
      var opt = badges[i];
      var str = '\'' + (opt.title || '') + '\', \'' + (opt.url || '') + '\', \'' + (opt.description || '') + '\'';
      var tmpl = '<ul>\
        <li><a class="sharein-sharein" href="http://sharein.com/" title="Sharein">Sharein</a></li>\
        <li><a class="sharein-email" href="#" onclick="SHAREIN.execBookmarklet(\'email\', ' + str + '); return false;">Email</a></li>\
        <li><a class="sharein-facebook" href="#" onclick="SHAREIN.execBookmarklet(\'facebook\', ' + str + '); return false;">Facebook</a></li>\
        <li><a class="sharein-twitter" href="#" onclick="SHAREIN.execBookmarklet(\'twitter\', ' + str + '); return false;">Twitter</a></li>\
      </ul>';
      document.getElementById('sharein-badge-' + i).innerHTML = tmpl;
    }
  });
})();
