var myTimeLine = {	

	GPlusUser: '101670405747033705660',
	GPlusApiKey: 'AIzaSyAsIIuCRHioNXmc7vQjXJce91keA8T4_cI',

	FBUser: 'oliver.michalak',
	FBApiKey: '210461172358613',
	FBAccessToken: 'AAACZCac9q3dUBAISg02hZBzFwXvIK47jwWs3NOu3itvKQ1bZBWBUe2a2ufk3wrB3nObjcjsdR2BoIpyIWFvEF1Ni0gQb2CFZAPLo0cAjUgZDZD',

/*
https://graph.facebook.com/oauth/authorize?type=user_agent&client_id=210461172358613&redirect_uri=http://oliver.werk01.de/global/&scope=user_about_me,user_activities,user_notes,user_photos,user_status,user_videos,user_website,user_work_history,read_stream,offline_access&response_token=token
*/

	TwitterUser: 'omichde',

	slideDelayTimer: 500,
	entryList: [],

	insertEntry: function (entry) {
		if (!entry.type || !entry.date || !entry.text)
			return;
		var index = 0;
		if (this.entryList.length) {
			for (index = this.entryList.length - 1; index >=0; index--) {
				if (this.entryList[index].date > entry.date)
					break;
				$('#mtl_entry_'+index).attr('id', 'mtl_entry_'+(index+1));
			}
			if (index < 0) {
				this.entryList.unshift (entry);
				$('#mtl_entry_1').before(this.renderEntry(entry, 0));
				$('#mtl_entry_0').hide();
				$('#mtl_entry_0').slideDown(this.slideDelayTimer);
			}
			else {
				this.entryList.splice (index+1, 0, entry);
				$('#mtl_entry_'+index).after(this.renderEntry(entry, index+1));
				$('#mtl_entry_'+(index+1)).hide();
				$('#mtl_entry_'+(index+1)).slideDown(this.slideDelayTimer);
			}
		}
		else {
			this.entryList.push (entry);
			$('#mtl').append(this.renderEntry(entry, 0));
			$('#mtl_entry_0').hide();
			$('#mtl_entry_0').slideDown(this.slideDelayTimer);
		}
		/*
	                                j.append("<li>" + (e.show_image && d.src ? '<span class="thumb" style="width:' + (e.image_width + 2) + "px; height:" + (e.image_height + 2) + 'px; overflow:hidden">' + (d.useLink ? '<a href="' + d.useLink + '">' : "") + '<img src="' + d.src + '" />' + (d.useLink ? "</a>" : "") + "</span>" : "") + '<span class="title">' + (d.useLink ? '<a href="' + d.useLink + '">' : "") + (c.title ? c.title : d.useTitle) + (d.useLink ? "</a>" : "") + '</span><span class="meta">' + (e.show_plusones ? '<span class="plusones">+' + q(m) + "</span>" : "") + (e.show_shares ? '<span class="shares">' + q(p) + " shares</span>" : "") + (e.show_replies ? '<span class="replies">' + q(g) + " comments</span>" : "") + (e.show_date ? '<a class="date" href="' + c.url + '">' + v(c.published) + "</a>" : "") + "</span></li>")
	  */

	},

	renderEntry: function (entry, index) {
		var text = '<div id="mtl_entry_'+index+'" class="mtl_entry mtl_type_'+entry.type.toLowerCase()+'">\n<p class="mtl_header">'+entry.date.toGMTString().substring(5, 25);
		if (entry.loveCounter)
			text += ' <span class="mtl_heart">'+entry.loveCounter+'</span>';
		text += ':</p><p class="mtl_content">';
		if (entry.image)
			text += '<img src="'+entry.image+'" align="left">\n';
		text += entry.text+'</p>\n<ul class="mtl_comment">\n';
		if (entry.commentList) {
			for (index=0; index < entry.commentList.length; index++) {
				var comment = entry.commentList[index];
				text += '<li>'+(comment.from ? comment.from+': ' : '')+comment.date.toLocaleString()+'<br>'+comment.text+'</li>\n';
			}
		}
		text += '</ul></div>\n';
		return text;
	},

	appendComments: function (commentList, destinationID, type) {
		for (index=0; index < this.entryList.length; index++) {
			var entry = this.entryList[index];
			if (entry.type == type && entry.referenceID == destinationID) {
				var text = '';
				for (commentIndex=0; commentIndex < commentList.length; commentIndex++) {
					var comment = commentList[commentIndex];
					text += '<li>'+(comment.from ? comment.from+': ' : '')+comment.date.toLocaleString()+'<br>'+comment.text+'</li>\n';
				}
				$('#mtl_entry_'+index+' .mtl_comment').html(text);
				break;
			}
		}
	},

	toggle: function (type) {
		if ($('#mtl_status_'+type).hasClass('loading'))
			return;
		if ($('#mtl_status_'+type).hasClass('hidden')) {
			$('.mtl_type_'+type).slideDown(this.slideDelayTimer);
			$('#mtl_status_'+type).removeClass('hidden');
		}
		else {
			$('.mtl_type_'+type).slideUp(this.slideDelayTimer);
			$('#mtl_status_'+type).addClass('hidden');
		}
	},

	update: function () {
		this.TwitterUpdate();
		this.GPlusUpdate();
		this.FBUpdate();
	},

	TwitterUpdate: function () {
		$('#mtl_status_twitter').addClass('loading');
		jQuery.ajax({
      url: "http://twitter.com/status/user_timeline/"+this.TwitterUser+".json",
      data: {
      	count: 100
      },
      cache: true,
      dataType: "jsonp",
      error: function (header) {
				$('#mtl_status_twitter').removeClass('loading').addClass('error');
      },
      success: myTimeLine.TwitterCallback
	  });
	},

	TwitterCallback: function (data) {
		$('#mtl_status_twitter').removeClass('loading').addClass('ok');
		for (index = 0; index < data.length; index++) {
			var entry = data[index];
			var newEntry = new Object;
			newEntry.type = 'Twitter';
			if (jQuery.browser.msie)
				newEntry.date = new Date(entry.created_at.replace(/( \+)/, ' UTC$1'));
			else
				newEntry.date = new Date(entry.created_at);
			newEntry.text = entry.text.replace (/(https?:\/\/[^\s]+)/g, '<a href="$1">$1</a>');
			newEntry.loveCounter = 0;
			if (entry.retweet_count)
				newEntry.loveCounter += entry.retweet_count;
			myTimeLine.insertEntry (newEntry);
		}
	},

	TwitterToggle: function () { this.toggle('twitter'); },

	FBUpdate: function () {
		$('#mtl_status_fb').addClass('loading');
		FB.init({	appId: this.FBApiKey, status: true, cookie: true, oauth: true, xfbml: true});

		jQuery.ajax({
      url: 'https://graph.facebook.com/'+this.FBUser+'/feed',
      data: {
          key: this.FBApiKey,
          access_token: this.FBAccessToken
      },
      cache: true,
      dataType: "jsonp",
      error: function (header) {
				$('#mtl_status_fb').removeClass('loading').addClass('error');
      },
      success: myTimeLine.FBCallback 
	  });
	},

	FBCallback: function (data) {
  	if (data.error)
			$('#mtl_status_fb').removeClass('loading').addClass('error');
		else if (data.data && data.data.length) {
			$('#mtl_status_fb').removeClass('loading').addClass('ok');
			for (index = 0; index < data.data.length; index++) {
				var entry = data.data[index];
				var newEntry = new Object;
				newEntry.type = 'FB';
				if (entry.updated_time)
					newEntry.date = (new Date()).setISO8601(entry.updated_time);
				else
					newEntry.date = (new Date()).setISO8601(entry.created_time);
				if (entry.message)
					newEntry.text = entry.message.replace (/(https?:\/\/[^\s]+)/g, '<a href="$1">$1</a>');
				if (entry.picture)
					newEntry.image = entry.picture;

				newEntry.loveCounter = 0;
				if (entry.likes && entry.likes.count)
					newEntry.loveCounter += entry.likes.count;

				if (entry.comments && entry.comments.data && entry.comments.data.length) {
					newEntry.loveCounter += entry.comments.data.length;
					var list = new Array();
					for (commentIndex = 0; commentIndex < entry.comments.data.length; commentIndex++) {
						var comment = entry.comments.data[commentIndex];
						var newComment = new Object;
						newComment.date = (new Date()).setISO8601(comment.created_time);
						newComment.text = comment.message;
						if (comment.from && comment.from.name)
							newComment.from = comment.from.name;
						list.push (newComment);
					}
					newEntry.commentList = list;
				}
				myTimeLine.insertEntry (newEntry);
			}
		}
		/*
		if (data.paging && data.paging.next) {
			jQuery.ajax({
	      url: data.paging.next,
	      cache: true,
	      dataType: "jsonp",
	      success: myTimeLine.FBCallback 
		  });
	  }
	  */
  },

	FBToggle: function () { this.toggle('fb'); },

	GPlusUpdate: function () {
		$('#mtl_status_gplus').addClass('loading');
		jQuery.ajax({
      url: "https://www.googleapis.com/plus/v1/people/" + this.GPlusUser + "/activities/public",
      data: {
          key: this.GPlusApiKey,
          maxResults: 20,
          prettyprint: false,
          fields: "items(id,kind,published,url,object(objectType,content,replies,plusoners,resharers,attachments(image)))"
      },
      cache: true,
      dataType: "jsonp",
      error: function (header) {
				$('#mtl_status_gplus').removeClass('loading').addClass('error');
      },
      success: myTimeLine.GPlusCallback
	  });
	},

	GPlusCallback: function (data) {
  	if (data.error)
			$('#mtl_status_gplus').removeClass('loading').addClass('error');
		else if (data.items && data.items.length) {
			$('#mtl_status_gplus').removeClass('loading').addClass('ok');
			for (index = 0; index < data.items.length; index++) {
				var entry = data.items[index];
				var newEntry = new Object;
				newEntry.type = 'GPlus';
				newEntry.date = (new Date()).setISO8601(entry.published);
				newEntry.text = entry.object.content;

				newEntry.loveCounter = 0;
				if (entry.object.replies && entry.object.replies.totalItems)
					newEntry.loveCounter += entry.object.replies.totalItems;
				if (entry.object.plusoners && entry.object.plusoners.totalItems)
					newEntry.loveCounter += entry.object.plusoners.totalItems;
				if (entry.object.resharers && entry.object.resharers.totalItems)
					newEntry.loveCounter += entry.object.resharers.totalItems;
				
				if (entry.object && entry.object.attachments) {
					for (attachmentIndex = 0; attachmentIndex < entry.object.attachments.length; attachmentIndex++) {
						var attachment = entry.object.attachments[attachmentIndex];
						if (attachment.image)
							newEntry.image = attachment.image.url;
					}
				}
				if (entry.url)
					newEntry.link = entry.url;

				// load comments async
				if (entry.id && entry.object.replies && entry.object.replies.totalItems && entry.object.replies.selfLink) {
					newEntry.referenceID = entry.id;
					jQuery.ajax ({
						url: entry.object.replies.selfLink,
			      data: {
		          key: myTimeLine.GPlusApiKey,
		          fields: "items(id,published,actor,object(objectType,content),inReplyTo(id))"
						},
			      cache: true,
			      dataType: "jsonp",
						success: function (commentData) {
							if (commentData.items && commentData.items.length) {
								var list = new Array();
								for (commentIndex = 0; commentIndex < commentData.items.length; commentIndex++) {
									var comment = commentData.items[commentIndex];
									var newComment = new Object;
									newComment.date = (new Date()).setISO8601(comment.published);
									newComment.text = comment.object.content;
									if (comment.actor && comment.actor.displayName)
										newComment.from = comment.actor.displayName;
									list.push (newComment);
								}
								myTimeLine.appendComments (list, commentData.items[0].inReplyTo[0].id, 'GPlus');
							}
						}
					});
				}

				myTimeLine.insertEntry (newEntry);
				/*
                  g = c.object.replies ? c.object.replies.totalItems : 0,
                  m = c.object.plusoners ? c.object.plusoners.totalItems : 0,
                  p = c.object.resharers ? c.object.resharers.totalItems : 0,
                  if (d.src.indexOf("resize_h") >= 0) d.src = d.w >= d.h ? d.src.replace(/resize_h=\d+/i, "resize_h=" + e.image_height) : d.src.replace(/resize_h=\d+/i, "resize_w=" + e.image_width)
				*/
			}
		}
  },

	GPlusToggle: function () { this.toggle('gplus'); }
};

/*
 Internet Timestamp Parser
 Copyright (c) 2009 Sebastiaan Deckers
 License: GNU General Public License version 3 or later
*/
Date.prototype.setISO8601 = function (timestamp) {
 var match = timestamp.match(
  "^([-+]?)(\\d{4,})(?:-?(\\d{2})(?:-?(\\d{2})" +
  "(?:[Tt ](\\d{2})(?::?(\\d{2})(?::?(\\d{2})(?:\\.(\\d{1,3})(?:\\d+)?)?)?)?" +
  "(?:[Zz]|(?:([-+])(\\d{2})(?::?(\\d{2}))?)?)?)?)?)?$");
 if (match) {
  for (var ints = [2, 3, 4, 5, 6, 7, 8, 10, 11], i = ints.length - 1; i >= 0; --i)
   match[ints[i]] = (typeof match[ints[i]] != "undefined"
    && match[ints[i]].length > 0) ? parseInt(match[ints[i]], 10) : 0;
  if (match[1] == '-') // BC/AD
   match[2] *= -1;
  var ms = Date.UTC(
   match[2], // Y
   match[3] - 1, // M
   match[4], // D
   match[5], // h
   match[6], // m
   match[7], // s
   match[8] // ms
  );
  if (typeof match[9] != "undefined" && match[9].length > 0) // offset
   ms += (match[9] == '+' ? -1 : 1) *
    (match[10]*3600*1000 + match[11]*60*1000); // oh om
  if (match[2] >= 0 && match[2] <= 99) // 1-99 AD
   ms -= 59958144000000;
  this.setTime(ms);
  return this;
 }
 else
  return null;
}

