/* library code */


/*
	from phpjs.org
*/
function urlencode(str) {
	str = (str+'').toString();
	return encodeURIComponent(str)
		.replace(/!/g, '%21')
		.replace(/'/g, '%27')
		.replace(/\(/g, '%28')
		.replace(/\)/g, '%29')
		.replace(/\*/g, '%2A')
		.replace(/%20/g, '+');
}

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

/*
	from roc4life.com createTime()
*/
Date.prototype.setISO8601 = function (string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
}

function createTime( time ) {
	var date = new Date;
	
	if( time ) {
		date.setISO8601( time );
		return date;
	} else {
		return null;
	}
}

/*
	from: tim-barber.com
*/
(function($){
	jQuery.fn.real_height = function(){
		var padding = $(this).padding();
		var margin = $(this).margin();
		return $(this).height() + padding.top + padding.bottom + margin.top + margin.bottom;
	};
})(jQuery);

/*
	from: bramstein.com
*/
/*!
 * JSizes - JQuery plugin v0.32
 *
 * Licensed under the revised BSD License.
 * Copyright 2008, Bram Stein
 * All rights reserved.
 */
/*global jQuery*/
(function ($) {
	var num = function (value) {
		return parseInt(value, 10) || 0;
	};

	/**
	 * Sets or gets the values for min-width, min-height, max-width
	 * and max-height.
	 */
	$.each(['min', 'max'], function (i, name) {
		$.fn[name + 'Size'] = function (value) {
			var width, height;
			if (value) {
				if (value.width) {
					this.css(name + '-width', value.width);
				}
				if (value.height) {
					this.css(name + '-height', value.height);
				}
				return this;
			}
			else {
				width = this.css(name + '-width');
				height = this.css(name + '-height');
				// Apparently:
				//  * Opera returns -1px instead of none
				//  * IE6 returns undefined instead of none
				return {'width': (name === 'max' && (width === undefined || width === 'none' || num(width) === -1) && Number.MAX_VALUE) || num(width), 
						'height': (name === 'max' && (height === undefined || height === 'none' || num(height) === -1) && Number.MAX_VALUE) || num(height)};
			}
		};
	});

	/**
	 * Returns whether or not an element is visible.
	 */
	$.fn.isVisible = function () {
		return this.css('visibility') !== 'hidden' && this.css('display') !== 'none';
	};

	/**
	 * Sets or gets the values for border, margin and padding.
	 */
	$.each(['border', 'margin', 'padding'], function (i, name) {
		$.fn[name] = function (value) {
			if (value) {
				if (value.top) {
					this.css(name + '-top' + (name === 'border' ? '-width' : ''), value.top);
				}
				if (value.bottom) {
					this.css(name + '-bottom' + (name === 'border' ? '-width' : ''), value.bottom);
				}
				if (value.left) {
					this.css(name + '-left' + (name === 'border' ? '-width' : ''), value.left);
				}
				if (value.right) {
					this.css(name + '-right' + (name === 'border' ? '-width' : ''), value.right);
				}
				return this;
			}
			else {
				return {top: num(this.css(name + '-top' + (name === 'border' ? '-width' : ''))),
						bottom: num(this.css(name + '-bottom' + (name === 'border' ? '-width' : ''))),
						left: num(this.css(name + '-left' + (name === 'border' ? '-width' : ''))),
						right: num(this.css(name + '-right' + (name === 'border' ? '-width' : '')))};
			}
		};
	});
})(jQuery);

/*
	from: http://ejohn.org/files/pretty.js
*/
/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	// if( typeof(time == null ) ) { return ''; }
	
	var date = time,
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
			
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		return;
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if ( typeof jQuery != "undefined" )
	jQuery.fn.prettyDate = function(){
		return this.each(function(){
			var date = prettyDate(this.title);
			if ( date )
				jQuery(this).text( date );
		});
	};
/* end library code*/

var time=new Date();time=time.getTime(); // it felt crazy writing it "time=time.getTime();"

var prefix = '';

// roc4life class
var roc4life = {
	
	get_rss: function( url, callback, entries ) {
		add_js( 'http://pipes.yahoo.com/pipes/pipe.run?_id=a6c0d6ace1f126315f8ef015c4bf5a02&_render=json&entries=' + urlencode(entries) + '&rssfeed=' + urlencode(url + '&t=' + time) + '&_callback=' + urlencode(callback) );
	},
	
	get_feed: function( code, callback ) {
		add_js('http://' + prefix + 'roc4life.ginlanemedia.com/parse_feed.php?get=' + urlencode(code + '&t=' + time) + '&callback=' + urlencode(callback));
	},
	
	image_resize: function( url, width, height, crop ) {
		var query_string = '';
		if( width ) { query_string += 'width=' + urlencode(width) + '&'; }
		if( height ) { query_string += 'height=' + urlencode(height) + '&'; }
		if( crop ) { query_string += 'crop=' + urlencode(crop) + '&'; }
		
		if( url.search(/ /g) > 0 ) {
			url = url.substr(0, url.search(/ /g) );
		}
		
		if( url.search(/\/>/g) > 0 ) {
			url= url.substr(0, url.search(/\/>/g) );
		}
		
		if( url.search(/\?/g) > 0 ) {
			url= url.substr(0, url.search(/\?/g) );
		}
		
		return url.replace(/.jpg/g, '.jpg?' + query_string)
			.replace(/.jpeg/g, '.jpeg?' + query_string)
			.replace(/.JPG/g, '.JPG?' + query_string)
			.replace(/.png/g, '.png?' + query_string)
			.replace(/.PNG/g, '.PNG?' + query_string);
	},
	
	parse_feed: function( data, entries ) {		
		var output = new Array();
		
		(function($){
			for( var i = 0; i<entries; i++ ) {
				var item = data.value.items[i];

				var image = item.first_image;
				
				if( !item.first_image ) {
					var src = item.description.match(/<img.*?src="(.*?)".*?\/>/im);
					var srcs = new Array();
					var newHtml = item.description;
					while(src!=null)
					{
						srcs.push(src[1]);
						newHtml = newHtml.substring(src.index+src[1].length,newHtml.length);
						src = newHtml.match(/<img.*?src="(.*?)".*?\/>/im);
					}
					
					if( srcs.length > 0 ) {
						item.first_image = srcs[0];
					} else {
						item.first_image = '';
					}
				}
				
				var image = item.first_image;
				
				while (item.description != (item.description = item.description.replace(/<[^<>]*>/g, "")));
				var description = $('<div>' + item.description + '</div>');
				var description = description.text().replace(/\r\n|\r|\n/g,'');

				var cutoff = 360;
				var description = description.substr(0,cutoff) + ( description.length > cutoff ? '...' : '' );
				
				// var date = dateFormat(createTime(item.pubDate), 'h:MMTT "on" mmm d');
				var date = prettyDate(createTime(item.pubDate));
				var title = item.title;
				var url = item.link;
			
				output.push({
					description: description,
					image: image,
					date: date,
					title: title,
					url: url,
					object: item.first_object,
					views: ( item.views ? item.views : false ),
					comments: ( item.comments ? item.comments : false )
				});
			}
		})(jQuery);
		
		return output;
	},
	
	body_balance: function( elem, max_height, header_selector, body_selector, meta_selector, animate ) {
		var height = elem.find(header_selector).real_height() + elem.find(body_selector).real_height() + elem.find(meta_selector).real_height();
		
		// if( height > max_height ) {
			height = max_height - ( elem.find(header_selector).real_height() + elem.find(meta_selector).real_height() );
			
			elem.find(body_selector)
				.css({
					'overflow': 'hidden'
				});
			
			if( animate ) {
				elem.find(body_selector).animate({'height':height}, 500);
			} else {
				elem.find(body_selector).css({'height':height});
			}
			
		// } else if( height < max_height ) {
		// 	
		// }
	},
	
	retweet: function( element, url ) {
		element.addClass('retweet').attr('href', url).attr('target', '_blank');
		
		add_js('http://api.bit.ly/shorten?version=2.0.1&longUrl=' + url  + '&login=roc4life&apiKey=R_24c66c48b088879c97fef542bc8a5cc7&history=1&callback=bitly');
	}
}

// bit.ly
function bitly(data) {
	for ( var url in data.results ) {
		(function($){
			var element = $('a.retweet[href="' + url + '"]');
			element.attr('href', data.results[url].shortUrl);
			element.removeClass('retweet');
			
			var title = element.parents('.xg_module').eq(0).find('.xg_module_body:visible .article-title').html();
			
			element.attr('href', 'http://www.twitter.com/home?status=' + data.results[url].shortUrl + '+' + urlencode(title) + '+@roc4life' );
		})(jQuery);
	}
}