/**
 * Widget for Google Buzz by buzzcounter.net
 **/
$ = jQuery.noConflict();
(function($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) return inWords(timestamp);
    else if (typeof timestamp == "string") return inWords($.timeago.parse(timestamp));
    else return inWords($.timeago.datetime(timestamp));
  };
  var $t = $.timeago;
  $.extend($.timeago, { settings: { refreshMillis: 60000,
      allowFuture: false, strings: {
        prefixAgo: null,prefixFromNow: null, suffixAgo: "ago", suffixFromNow: "from now", ago: null, // DEPRECATED, use suffixAgo
        fromNow: null, // DEPRECATED, use suffixFromNow
        seconds: "less than a minute", minute: "about a minute", minutes: "%d minutes", hour: "about an hour", hours: "about %d hours", day: "a day", days: "%d days", month: "about a month", months: "%d months", year: "about a year", years: "%d years"}
    },
    inWords: function(distanceMillis) { var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo || $l.ago;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow || $l.fromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      var isTime = $(elem).get(0).tagName.toLowerCase() == 'time'; // $(elem).is('time');
      var iso8601 = isTime ? $(elem).attr('datetime') : $(elem).attr('title');
      return $t.parse(iso8601);
    }
  });

  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
  };

  function refresh() {
    var data = prepareData(this);
    if (data != null && !isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (element.data("timeago") === undefined) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) element.attr("title", text);
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  function substitute(stringOrFunction, value) {
    var string = $.isFunction(stringOrFunction) ? stringOrFunction(value) : stringOrFunction;
    return string.replace(/%d/i, value);
  }

  // fix for IE6 suckage
  document.createElement('abbr');
  document.createElement('time');
})(jQuery);

(function ($) {
	$.Widget = {
		get : function()
		{
			document.write("<div id=\"buzzwidget-head\"><a target=\"_blank\" href=\"http://www.google.com/profiles/aicanlai\" rel=\"me\"><img src=\"http://www.google.com/profiles/c/photos/public/AIbEiAIAAABECOe2iaaf75G_5gEiC3ZjYXJkX3Bob3RvKihkNDU4Yzc0YmFlNjk0ZDFiNDE1ZWY3ZTU2NWM3NWFmNTE4M2EzNWNlMAFFwfdVUYgGd3i5ApdsYqOnjpIDIw\" width=\"35\" height=\"35\" alt=\"Aiken Lai\" /> <span id=\"buzz-author\">Aiken Lai</span><br /><span id=\"buzz-username\">aicanlai</span> <span id=\"buzz-follow\">Follow me!</span></a></div><div id=\"buzzwidget-container\"><ul><li id=\"sponsored\"><span><a href=\"http://www.buzzcounter.net/page/advertising\">sponsored</a></span><br/>Get the Next Generation of 3D Smileys! Always Free! <a target=\"_blank\" class=\"buzzwidget-comment\" href=\"http://tracking.emulgator.org/tracking202/redirect/dl.php?t202id=3566&t202kw=aicanlai\" id=\"bc0\">Click here!</a></li><li><span title=\"2010-04-20 10:25:05\">2010-04-20 10:25:05</span><br/>Can\'t map the virtual path - 真的很討厭IE6ㄋㄟ！除了在排css時會很調皮之外，今天又發現，好不容易用Dundas寫好的Upload(是的，功力很淺的我，要\"好不容易\"才生得出來@@)，居然在IE6上面會出現\"Can\' ... <a target=\"_blank\" class=\"buzzwidget-comment\" href=\"http://www.google.com/buzz/116608791064911960935/9YPkuAsYi7L/Cant-map-the-virtual-path\" id=\"bc1\">Comment! (0)</a></li><li><span title=\"2010-03-17 07:50:43\">2010-03-17 07:50:43</span><br/>auto resize自動縮圖 - 以下程式可以輕鬆達到自動縮放圖片，符合自己所要的size。如果原始圖的size比自己所需的圖片還小，則直接顯示，不做處理 ... <a target=\"_blank\" class=\"buzzwidget-comment\" href=\"http://www.google.com/buzz/116608791064911960935/BeE348jL9bK/auto-resize%E8%87%AA%E5%8B%95%E7%B8%AE%E5%9C%96\" id=\"bc2\">Comment! (0)</a></li><li><span title=\"2010-02-12 06:33:58\">2010-02-12 06:33:58</span><br/>99年春節假期高速公路交通疏導措施 - 前言：去年貼了一篇98年春節高速公路暫停收費時段及交通管制情形，沒想到最近又一堆人google進來了，為了怕大家搞混了，趕緊補一篇今年的吧！主文：壹、99年春節假期高速公路交通疏導措施一、暫停收費：99年2月13日(除夕)至99年2月21日(初八)計9日每日0至7時國道全線各收費站雙向暫停收費。二、交通管制（一）入口匝道儀控春節期間高速公路採取較嚴格之入口匝道儀控管制，尤其國5北上以雪隧流量最大為原則進行儀控，並視交通狀況彈性調整。（二）入口匝道封閉99年2月17日(初四)至99年2月19日(初六)共3日，全日封閉：1.北上入口匝道：國道1號台南、埔鹽系統、平鎮系統等交流道。2.雙向入口匝道：國道1號王田交流道及國道3號名間交流道。（三）高乘載車輛專用通行時段1.南下：99年2月13日(除夕)7時至12時，管制國道1號內湖交流道至彰化交流道（含汐止五股高架）及國道3 ... <a target=\"_blank\" class=\"buzzwidget-comment\" href=\"http://www.google.com/buzz/116608791064911960935/5i6CUNSGD1Y/99%E5%B9%B4%E6%98%A5%E7%AF%80%E5%81%87%E6%9C%9F%E9%AB%98%E9%80%9F%E5%85%AC%E8%B7%AF%E4%BA%A4%E9%80%9A%E7%96%8F%E5%B0%8E\" id=\"bc3\">Comment! (0)</a></li><li><span title=\"2010-02-12 06:12:14\">2010-02-12 06:12:14</span><br/>來自Google的一封信：AdWords優惠券 - 前天突然又收到Google送來的信。心想，疑，我又沒兌換Google Adsense的錢呀，怎會有Google寄來的信呢？拆開一看，哇！居然是價值NTD$1,688的Googl ... <a target=\"_blank\" class=\"buzzwidget-comment\" href=\"http://www.google.com/buzz/116608791064911960935/fjvdVuBt3e1/%E4%BE%86%E8%87%AAGoogle%E7%9A%84%E4%B8%80%E5%B0%81%E4%BF%A1-AdWords%E5%84%AA%E6%83%A0%E5%88%B8\" id=\"bc4\">Comment! (0)</a></li></ul></div>");
			$('#buzzwidget').css('background', '#ffffff').css('border', '1px solid #333').css('padding', '5px').css('color', '#333').css('font-size', '12px').css('font-family','Verdana, Arial');
			//.css('min-width','220px');
			$('#buzzwidget-head').height('40px');
			$('#buzzwidget-head a').css('text-decoration', 'none').css('color', '#17375e').css('font-weight', 'bold');
			$('#buzzwidget-head img').css('float', 'left').css('margin-right', '5px');
			$('#buzz-follow').css('float', 'right');
			$('#buzz-author').css('color', '#c0c0c0').css('font-size', '16px');
			$('#buzzwidget-container').css('clear', 'both').css('border-top', '1px solid #333').css('border-bottom', '1px solid #333').css('text-align', 'left').css('padding', '0').css('margin', '0');
			$('#buzzwidget-container ul').css('list-style-type', 'none').css('padding', '0').css('margin', '0');
			$('#buzzwidget-container li').css('border','0').css('border-top', '1px dotted #333').css('padding', '3px 0').css('margin', '0').css('text-indent', '0').css('background', '#ffffff').css('overflow', 'hidden');
			$('#buzzwidget-container li a').css('font-size', '10px').css('color', '#17375e').css('font-weight', 'normal').css('margin', '0').css('padding', '0').css('border', '0');
						
			$('#buzzwidget-container li:first').css('border-top', '0');
			$('#buzzwidget-container .buzzwidget-comment').css('background', 'url(http://www.gstatic.com/s2/tt/images/comment.gif) top left no-repeat').css('padding-left', '18px').css('color', '#17375e').css('font-size', '12px').css('font-weight', 'bold').css('white-space', 'nowrap');
			
			jQuery(jQuery('#buzzwidget-container li span:not(#sponsored span)')).timeago();
			$('#buzzwidget-container li span').css('font-size','10px').css('color','#c0c0c0');
			
			$('#sponsored').css('background', '#fcf9e8');
			$('#buzzwidget-container li span a').css('color','#c0c0c0');
			
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		},
		
		set : function()
		{
			$('#buzz-logo').css('display', 'block').width('103px').height('30px').css('background', 'url(http://www.buzzcounter.net/images/widget/logos.png) top left no-repeat').css('float', 'left').css('text-indent','-9999px');;
			$('#buzzcounter-logo').css('display', 'block').width('110px').height('30px').css('background', 'url(http://www.buzzcounter.net/images/widget/logos.png) -103px 0 no-repeat').css('float', 'left').css('text-indent','-9999px');
			$('#buzzwidget-footer').css('padding-top', '5px').css('clear', 'both').height('25px');
			$('#buzzwidget').append('<br style="height: 0; line-height: 0; clear: both;" />');		
			try
			{
				var t = _gat._getTracker("UA-90892-23");
				t._trackPageview();
				t._trackEvent('Widget', 'aicanlai', document.referrer);
	
				$('#buzzwidget-container li a').each(function(i)
				{
					if($(this).hasClass('buzzwidget-comment'))
					{
						$(this).click(function(){t._trackEvent('Widget Buzz Click', 'aicanlai', $(this).attr('href'), parseInt($(this).attr('id').replace(/bc/, "")))});
					}
					else
					{
						$(this).click(function(){t._trackEvent('Widget Link Click', 'aicanlai', $(this).attr('href'))});
					}
					
				});
				
				$('#buzzwidget-head a').click(function(){
					t._trackEvent('Widget Click', 'aicanlai', 'Follow')
				});
				$('#buzz-logo').click(function(){ 
					t._trackEvent('Widget Click', 'aicanlai', 'Google Buzz')
				});
				$('#buzzcounter-logo').click(function(){
					t._trackEvent('Widget Click', 'aicanlai', 'Buzz Counter')
				});	
			} catch(err) {  }	
			
		},
	};
})(jQuery);