/**
 * Convert linebreaks to html breaks
 * http://stackoverflow.com/questions/2919337/jquery-convert-line-breaks-to-br-nl2br-equivalent
 */
$.nl2br = function(str, is_xhtml) {
	var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
	return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
};

/**
 * http://delete.me.uk/2005/03/iso8601.html
 */
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));
}

/**
 * Object for dealing with d3mls_facebook functionality
 */
var facebook_wall =
{
	/**
	 * With the the facebook user's profile id and a suitable div to serve
	 * as the user's wall, get the facebook feed and write wall comments
	 * @param Integer profile_id The user's profile id on Facebook
	 * @param Integer app_id Programmar app id
	 * @param jQuery $wall A div to append wall postings to
	 * @param Integer num_wall_posts Number of posts to display
	 * @param String template String containing the html from wall.tpl.php
	 */
	writeWall : function(profile_id, app_id, $wall, num_wall_posts, template){

		profile_id = parseInt(profile_id);
		if (profile_id)
		{
			$.ajax({
				url: "/app/modules/facebook_wall/xml/feed.php",
				dataType: 'json',
				data: {"profile_id" : profile_id},
				success: function (data){
					var dataObj = eval(data);
					var feed = dataObj.data;

					if ($.isArray(feed))
					{
						for (var i=0, fromAllcleanCounter=0;
							fromAllcleanCounter < ((num_wall_posts < feed.length) ? num_wall_posts : feed.length);
							i++)
						{
							var item = feed[i];
							var fromAllclean = item.from.name.match(/clean/i);
							if ($.isArray(fromAllclean) && typeof item.message != "undefined")
							{
								fromAllcleanCounter++;
								var post = decodeURI(template);
								post = post.replace(/\{\$name\}/gi, item.from.name);
								post = post.replace(/\{\$sef_name\}/gi, item.from.name.replace(/\s/ig,"-"));
								post = post.replace(/\{\$id\}/gi, item.from.id);
								post = post.replace(/\{\$message\}/gi, $.nl2br(item.message));
								if (typeof item.picture != "undefined" && item.picture != null)
								{
									if (item.picture.match(/&url=/i))
									{
										var urlPos = item.picture.indexOf("&url=") +5 ;
										var itemImage = decodeURIComponent(item.picture.substr(urlPos));
									}
									else
										var itemImage = decodeURIComponent(item.picture);

									if (typeof itemImage!= "undefined" && itemImage!= null)
									{
										post = post.replace(/\{\$image\}/gi,itemImage);
									}
									if (typeof item.link != "undefined" && item.link != null)
										post = post.replace(/\{\$imagelink\}/gi,item.link);
								}
								var date = new Date();
								date.setISO8601(item.updated_time);
								var eastTime = date.getTime() - 14400000;
								var eastUTC = new Date(eastTime);
								var utcMonth = (eastUTC.getUTCMonth()<11)? eastUTC.getUTCMonth()+1 : 12;//stupid
								var updated = eastUTC.getUTCFullYear()+"-"+utcMonth+"-"+eastUTC.getUTCDate()+"T"+
									eastUTC.getUTCHours()+":"+eastUTC.getMinutes()+":"+eastUTC.getSeconds()+"Z";
								post = post.replace(/\{\$utcdate\}/gi, updated);//DONT F*&KING TOUCH
								var hour = date.getHours();
								var pm = false;
								if(hour > 12){
									hour = hour-12;
									pm = true;
								}
								var updated = utcMonth+'/'+eastUTC.getUTCDate()+'/'+eastUTC.getUTCFullYear()+' @'+hour+':'+eastUTC.getMinutes()+((pm) ? 'PM' : 'AM');
								post = post.replace(/\{\$datetime\}/gi, updated);
								$wall.append(post);
							}
						}
						//hide empty images and css resize
						$wall.find("img").each(function(){
							if ($(this).attr("src").match(/\$image/ig) || $(this).attr("src").length==0)
								$(this).hide().parent().hide();//also hide of anchor
							else
								$(this).css({'width':'75px','height':'75px'});
						});
						//prettify dates
						$wall.find("a").each(function(){
							$(this).prettyDate();
						});
					}
				}
			});
		}
	}
};

/*
 * jQuery pretty date plug-in 1.0.0
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-prettydate/
 *
 * Based on John Resig's prettyDate http://ejohn.org/blog/javascript-pretty-date
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * $Id: jquery.validate.js 6096 2009-01-12 14:12:04Z joern.zaefferer $
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function() {

$.prettyDate = {

	template: function(source, params) {
		if ( arguments.length == 1 )
			return function() {
				var args = $.makeArray(arguments);
				args.unshift(source);
				return $.prettyDate.template.apply( this, args );
			};
		if ( arguments.length > 2 && params.constructor != Array  ) {
			params = $.makeArray(arguments).slice(1);
		}
		if ( params.constructor != Array ) {
			params = [ params ];
		}
		$.each(params, function(i, n) {
			source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
		});
		return source;
	},

	now: function() {
		return new Date();
	},

	// Takes an ISO time and returns a string representing how
	// long ago the date represents.
	format: function(time) {
		var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
			diff = ($.prettyDate.now().getTime() - date.getTime()) / 1000,
			day_diff = Math.floor(diff / 86400);

		if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
			return;

		var messages = $.prettyDate.messages;
		return day_diff == 0 && (
				diff < 60 && messages.now ||
				diff < 120 && messages.minute ||
				diff < 3600 && messages.minutes(Math.floor( diff / 60 )) ||
				diff < 7200 && messages.hour ||
				diff < 86400 && messages.hours(Math.floor( diff / 3600 ))) ||
			day_diff == 1 && messages.yesterday ||
			day_diff < 7 && messages.days(day_diff) ||
			day_diff < 31 && messages.weeks(Math.ceil( day_diff / 7 ));
	}

};

$.prettyDate.messages = {
	now: "just now",
	minute: "1 minute ago",
	minutes: $.prettyDate.template("{0} minutes ago"),
	hour: "1 hour ago",
	hours: $.prettyDate.template("{0} hours ago"),
	yesterday: "Yesterday",
	days: $.prettyDate.template("{0} days ago"),
	weeks: $.prettyDate.template("{0} weeks ago")
};

$.fn.prettyDate = function(options) {
	options = $.extend({
		value: function() {
			return $(this).attr("title");
		},
		interval: 10000
	}, options);
	var elements = this;
	function format() {
		elements.each(function() {
			var date = $.prettyDate.format(options.value.apply(this));
			if ( date && $(this).text() != date )
				$(this).text( date );
		});
	}
	format();
	if (options.interval)
		setInterval(format, options.interval);
	return this;
};

})();
