// JavaScript Document
// Simulates PHP's date function
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(i-1>=0&&format.charAt(i-1)=="\\"){returnStr+=curChar;}else if(replace[curChar]){returnStr+=replace[curChar].call(this);}else if(curChar!="\\"){returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){var d=new Date(this.getFullYear(),0,1);return Math.ceil((this-d)/86400000);},W:function(){var d=new Date(this.getFullYear(),0,1);return Math.ceil((((this-d)/86400000)+d.getDay()+1)/7);},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){var d=new Date();return new Date(d.getFullYear(),d.getMonth(),0).getDate()},L:function(){var year=this.getFullYear();return(year%400==0||(year%100!=0&&year%4==0));},o:function(){var d=new Date(this.valueOf());d.setDate(d.getDate()-((this.getDay()+6)%7)+3);return d.getFullYear();},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return Math.floor((((this.getUTCHours()+1)%24)+this.getUTCMinutes()/60+this.getUTCSeconds()/3600)*1000/24);},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},u:function(){var m=this.getMilliseconds();return(m<10?'00':(m<100?'0':''))+m;},e:function(){return"Not Yet Supported";},I:function(){return"Not Yet Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':00';},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d\\TH:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","")
		lnk = u.link("http://twitter.com/"+username);
		lnk = lnk.replace('<a ', '<a target="_blank" ');
		return lnk;
	});
};

String.prototype.stripLinks = function() {
	return this.replace(/<a[^>]+>/g, function(url) {
		spl = url.split('href="');
		lnk = spl[1].split('"');
		return lnk[0];
	});
	
}

String.prototype.stripImages = function() {
	return this.replace(/<img[^>]+>/g, '');
}

String.prototype.parseURL = function() {
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
		lnk = url.link(url);
		lnk = lnk.replace('<a ', '<a target="_blank" ');
		return lnk;
	});
};

String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23")
		lnk= t.link("http://search.twitter.com/search?q="+tag);
		lnk = lnk.replace('<a ', '<a target="_blank" ');
		return lnk;
	});
};


( function( $ ) {
	var element;
	
	var timer;
	
	var settings = {
		'base_url':'',
		'date_format':'m/d/y',
		'include_link':false,
		'include_author':false,
		'include_image':false,
		'include_date':true,
		'refresh_rate':10,
		'limit':10,
		'include_icons':false,
		'facebook_icon':'/budefeed/img/facebook.gif',
		'twitter_icon':'/budefeed/img/twitter.gif',
		'rss_icon':'/budefeed/img/rss.gif',
		'loading_icon':'/budefeed/css/img/ajax-loader.gif',
		'onInit': function() {},
		'onInitComplete': function() {},
		'onBuild': function() {},
		'onBuildComplete': function() {},
		'onRefresh': function() {},
		'onRefreshComplete': function() {}
	}
	
	var methods = {
		init : function(options) {
			return this.each(function() {   
			
				if ($.isFunction(settings.onInit)) {
					settings.onInit.call(this);
				}
			  
				// If options exist, lets merge them
				// with our default settings
				if ( options ) { 
					$.extend( settings, options );
				}
				$(this).html('<div id="feed_loader"><img src="' + settings.loading_icon + '" alt="Loading" /></div>');
				$.getJSON(options.url + '/budefeed/feeds/get_feeds.json', function(response) {
					if(response.meta.status == 'ok') {
						methods.build(response.data);	
					}
				});
				
				if ($.isFunction(settings.onInitComplete)) {
					settings.onInitComplete.call(this);
				}
		
			});
			
			
		},
		build : function(data) {
		
				if ($.isFunction(settings.onBuild)) {
					settings.onBuild.call(this);
				}
				var items = data.results;
				var config = data.configs;
				settings.refresh_rate = config.refresh_rate;
				settings.limit = config.limit;
				if($('#feed_items').length == 0) {
					var divs = '<div id="feed_title">' + config.title + '</div>';
					divs += '<div id="feed_items"></div>';
					$(element).append(divs);
				}
				
				for(i=config.limit-1; i>=0; i--) {
					if($('#feedItem_' + items[i].id).length == 0) {
						$('#feed_items').prepend(buildItem(items[i], i+1)).slideDown('slow', function() {
							if($('#feed_items').children('.feed_item').length > config.limit) {
								$('#feed_items').children('.feed_item:last').remove();
							}
						});
					}
					$('#feed_items').children('.feed_item:last').addClass('feed_item_last');
				}
				$('.feedItem:gt('+config.limit+')').remove();
			
				$('#feed_loader').hide();
				if(settings.include_link) {
					$('.feed_item[rel]').each(function() {
						if($(this).hasClass('link')) return;
						$(this).addClass('link').click(function(e) {
						e.preventDefault();
						window.open($(this).attr('rel'));
						return false;
						});
					});
				}
				
				if ($.isFunction(settings.onBuildComplete)) {
					settings.onBuildComplete.call(this);
				}
				
				timer = setTimeout(refreshItems, (1000 * settings.refresh_rate));
				
		}
		
		
	}
	
	var refreshItems = function() {
		if ($.isFunction(settings.onRefresh)) {
			settings.onRefresh.call(this);
		}
		
		$('#feed_loader').show();
		 $.getJSON(settings.base_url + '/budefeed/feeds/get_feeds.json', function(response) {
			if(response.meta.status == 'ok') {
				methods.build(response.data);	
			}
		});
		
		if ($.isFunction(settings.onRefreshComplete)) {
			settings.onRefreshComplete.call(this);
		}
	}
	
	var buildItem = function(item, index) {
		wrapper = '<div class="feed_item';
		if(index%2) wrapper += ' feed_item_alt';
		wrapper += '" id=feedItem_'+item.id;
		if(settings.include_link && item.link != undefined) {
			wrapper += ' rel="' + item.link + '">';
		} else {
			wrapper += '>';
		}
		inner = '';
		text = '';
		if(settings.include_icons) {
			imagesrc = settings[item.source + '_icon'];
			inner += '<div class="feed-icon"><img src="' + imagesrc + '" alt="" /></div>';
		}
		
		if(settings.include_image) {
			inner += '<img class="feed-image" src="' + item.options.image + '" />';
		} 
		text += '<span class="feed-text">' + item.message + '</span>';
		
		
		//highlight all @ and add links
		text = text.replace(/(^|\s|-)+@(\w+)/g, function(str) {
			return '<span class="highlight">' + str + '</span>';
		});
		//highlight all # and add links
		text = text.replace(/(^|\s|-)+#(\w+)/g, function(str) {
			return '<span class="highlight">' + str + '</span>';
		});
		if(settings.include_link) {
			
			text = text.stripImages().stripLinks().parseURL().parseHashtag().parseUsername();
		}
		inner += text;
		if(settings.include_author) {
			inner += '<span class="feed-author">' + item.from.user + '</span>';
		}
		if(settings.include_date) {
			
			var a = item.date.split(' ');
			a[0] = a[0].split('-').join(' ');
			var mdy = a[0].split(' ');
			var msecs = Date.parse(mdy[1] + '/' + mdy[2] + '/' + mdy[0] + ' ' + a[1]);
			var d = new Date(msecs);
			
			if(settings.date_format == 'timeago') {
				
				inner += '<br /><span class="feed-date">' + jQuery.timeago(d) + '</span>';
				
			} else {
				inner += '<br /><span class="feed-date">' + d.format(settings.date_format) + '</span>';
			}
		}	
		wrapper += inner;		
		wrapper += '</div>';
		
					
			
		return wrapper;
	}
	
	
	$.fn.BUDeFEED = function(method)
	{
		element = $(this); 
		
		
		// Method calling logic
		if ( methods[method] ) {
		  return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
		  return methods.init.apply( this, arguments );
		} else {
		  $.error( 'Method ' +  method + ' does not exist on BUDeFEED' );
		}    
	};


})(jQuery);



/*
 * timeago: a jQuery plugin, version: 0.9.3 (2011-01-21)
 * @requires jQuery v1.2.3 or later
 *
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008-2011, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
 */
(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",
        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",
        numbers: []
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      function substitute(stringOrFunction, number) {
        var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis) : stringOrFunction;
        var value = ($l.numbers && $l.numbers[number]) || number;
        return string.replace(/%d/i, value);
      }

      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(/\.\d\d\d+/,""); // remove milliseconds
      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);
	  var date_string = isTime ? $(elem).attr("datetime") : $(elem).attr("title");

    }
  });

  $.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 (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (!element.data("timeago")) {
      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());
  }

  // fix for IE6 suckage
  document.createElement("abbr");
  document.createElement("time");
}(jQuery));




