/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};$.fn.sponsor = function(programFile, callback) {
  var self = this;
  $.getJSON(programFile, function(program) {
    var sponsor = program.slots[rand(program.slots.length)];
    var id = sponsor.id;
    var anchor = self.find("a");
    anchor.attr("href", sponsor.url);
    anchor.find("img").attr("src", sponsor.image);
    anchor.find("p").html(sponsor.message);
    if (pageTracker) {
      pageTracker._trackPageview("/sponsor/" + id);
      anchor.unbind("click");
      anchor.click(function() { pageTracker._trackPageview("/outgoing/sponsor/" + id); });
    }
    if (callback) callback.call(self);
  });
  return self;
};

function rand(max) {
  return Math.floor(Math.random() * max);
}

$.log = $.fn.log = function (msg) {
  if (console && console.log){
    console.log("%s: %o", msg, this);
  }
  return this;
};

function gentlyEncode(string) {
  return ( encodeURIComponent
           ? encodeURIComponent(string).replace(/%20(\D)?/g, "+$1").replace(/'/g, escape("'"))
           : escape(string).replace(/\+/g, "%2B").replace(/%20/g, "+") );
}
$(function(){
  var streamData  = [];
  var streamIndex = getStreamIndex();
  var streamNode  = $("#stream");

  updateData();
  runBanners();

  function updateData() {
    $.getJSON("/recent.json", null, beginStreamRoll);
  }

  function beginStreamRoll(data) {
    streamData = data;
    rollStream();
  }

  function rollStream() {
    if(streamIndex > streamData.length - 1) {
      setStreamIndex(0);
      updateData();
    }
    else {
      var nextMessage    = streamData[streamIndex];
      var nextMessageUrl = "http://lmgtfy.com/?q=" + gentlyEncode(nextMessage);
      var newNode        = $("<li style=\"display:none\"><a></a></li>");
      newNode.find("a")
        .attr("href", nextMessageUrl)
        .text(nextMessage)
        .click(function() {
          var self = $(this);
          self.attr("href", "http://vanillaresults.com/?q=" + gentlyEncode(nextMessage));
          setTimeout(function() { self.attr("href", nextMessageUrl); }, 10);
        });
      streamNode.append(newNode);
      newNode.slideDown();
      setStreamIndex(streamIndex + 1);
      popOffTheTop();
      setTimeout(rollStream, rand(3000));
    }
  }

  function popOffTheTop() {
    if(streamNode.children().length > 100)
      popOffTheTop = function() { streamNode.find("li:first").remove(); };
  }

  function setStreamIndex(x) {
    $.cookie("streamIndex", x);
    streamIndex = x;
  }

  function getStreamIndex() {
    return streamIndex || parseInt($.cookie("streamIndex")) || 0;
  }

  function runBanners() {
    $("#sponsor").fadeOut(1000, function() {
      $(this).sponsor("/s/program.json", function() {
        this.fadeIn(1000);
      });
    });
    setTimeout(runBanners, 30000);
  }
});
