function twits(obj) {
  var twitter = null;
  var root = null;
  var config = null;
  var noSVGBackgrounds = !window.opera;

  for(var i = 0; i < twitters.length; i++)
  {
    config = twitters[i].getConfig();
    if(config.query == obj.query)
    {
      twitter = twitters[i];
      root = twitter.getElement();
      break;
    }
  }

  if(!root)
    return;

  while(obj.results.length > config.num_twits - root.childNodes.length) {
    root.removeChild(root.lastElementChild);
  }

  for(var i=obj.results.length-1; i >= 0; i--) {
    var item = obj.results[i];
    twitter.setLastId(item.id);

    var box = document.createElement("div");
    box.className = "twresult" + (noSVGBackgrounds? " nosvg" : "");

    var a = null;
    if(config.image)
    {
      var img = new Image();
      img.src = item.profile_image_url;
      img.height=32;
      img.width=32;
      img.className = "twim" + (noSVGBackgrounds? " nosvg" : "");

      a = document.createElement("a");
      a.href = "http://twitter.com/"+item.from_user;
      a.appendChild(img);
      a.className = "twimlink" + (noSVGBackgrounds? " nosvg" : "");
    }

    var a2 = null;
    if(config.fromuser)
    {
      a2 = a.cloneNode(false);
      a2.textContent = item.from_user;
      a2.className = "twfromuserlink" + (noSVGBackgrounds? " nosvg" : "");
    }

    var twtx = null;
    if(config.text)
    {
      item.text = twitter.linkify(item.text);

      twtx = document.createElement("div");
      twtx.className="twtx" + (noSVGBackgrounds? " nosvg" : "");

      if(config.fromuser)
      {
        twtx.appendChild(a2);
        item.text = ": " + item.text;
      }

      twtx.innerHTML += item.text;
    }

    var twat = null;
    if(config.date)
    {
      twat = document.createElement("div");
      twat.className="twat" + (noSVGBackgrounds? " nosvg" : "");
      twat.textContent = new Date(item.created_at).toLocaleString();
    }

    if(config.image)
      box.appendChild(a);

    if(config.text)
      box.appendChild(twtx);

    if(config.date)
      box.appendChild(twat);

    root.insertBefore(box, root.childNodes.length > 0 ? root.childNodes[0] : null);
  }

  var s = twitter.getScriptElement();
  s.parentNode.removeChild(s);
  twitter.update();
};

/** only do this if the site has expanded twitter miff or cookie is set */
function doSearch()
{
  var elms = document.getElementsByClassName("twitter");
  for(var i=0; i < elms.length; i++)
  {
    twitters.push(new Twitter(elms[i]));
  }

  for(var i = 0; i < twitters.length; i++)
  {
    twitters[i].search();
  }
}

function Twitter(inelm)
{
  var elm = inelm;
  var last_id = null;
  var last_seed = Math.floor(Math.random() * 1234567890);
  var script_element = null;
  var config = {  "num_twits" : elm.getAttribute("data-num"),
          "query" : /*encodeURIComponent*/(elm.getAttribute("data-search")),
          "interval" : elm.getAttribute("data-interval"),
          "image" : !elm.hasAttribute("data-noimage"),
          "fromuser" : !elm.hasAttribute("data-nofromuser"),
          "text" : !elm.hasAttribute("data-notext"),
          "date" : !elm.hasAttribute("data-nodate")
        };

  function fetch_impl(url) {
    var script = document.createElement("script");
    script.src = url + "&callback=twits&rpp=" + (config.num_twits ? config.num_twits : 10);
    if(last_id)
      script.src += "&since_id=" + last_id;
    last_seed = Math.floor(Math.random(last_seed) * 1234567890);
    script.src += "&rand=" + last_seed;
    script.type = "text/javascript";
    script_element = script;
    document.getElementsByTagName("head")[0].appendChild(script);
  }

  return {
    search: function(str) {
      if(str)
        config.query = str;
      fetch_impl("http://search.twitter.com/search.json?q=" + config.query);
    },
    update: function() {
      if(config.interval >= 0)
        window.setTimeout(this.search, config.interval*1000);
    },
    getConfig: function() {
      return config;
    },
    getElement: function() {
      return elm;
    },
    getScriptElement: function() {
      return script_element;
    },
    setLastId : function(id) {
      last_id = id;
    },
    linkify : function(str) {
      var re = new RegExp("(([a-zA-Z]+:\/\/)([a-zA-Z][a-zA-Z0-9_\.-]*[a-zA-Z]{2,6})([a-zA-Z0-9~\#\/\._\?\&%-=]*[a-zA-Z0-9~\#\/_\?\&%-=]))", "g");
      str = str.replace(re, '<a href="$1">$1</a>');
      re = new RegExp("@([a-zA-Z0-9_]+)", "g");
      str = str.replace(re, '@<a href="http://twitter.com/$1">$1</a>');
      re = new RegExp("[ \n\t](www\.([a-zA-Z][a-zA-Z0-9_\.-]*[a-zA-Z]{2,6})([a-zA-Z0-9~\#\/\._\?\&%-=]*[a-zA-Z0-9~\#\/_\?\&%-=]))", "g");
      str = str.replace(re, '<a href="http://$1">$1</a>');
      return str;
    }
  };
}

var twitters = new Array();
doSearch();

