$(document).ready(function() {
	$("a[rel='permalink']").mouseenter(LikeBox.handle_show)
	$("a[rel='permalink']").mouseleave(LikeBox.handle_leave);
	$(LikeBox.SELECTOR).mouseenter(LikeBox.handle_enterBox);
	$(LikeBox.SELECTOR).mouseleave(LikeBox.handle_leaveBox);
});

var LikeBox = {
	WIDTH : 110,
	FB_HEIGHT : 21,
	TWEET_HEIGHT : 20,
	FB_APP_ID : 118210643380,
	TWITTER_ACCOUNT : 'chavesn',
	SELECTOR : "#like-hoverbox",
	_contentCache : {},
	_timeoutId : null,

	tryHide : function(hidingElement) {
		this._timeoutId = setTimeout(function(){ $(LikeBox.SELECTOR).fadeOut(125); }, 200);
	},

	showContent : function(anchor) {
		clearTimeout(this._timeoutId);

		$(this.SELECTOR + " .content div").hide();
		var href = anchor.href;
		var title = $(anchor).data("title");
		if (!this._contentCache[href]) {
			var container = document.createElement("DIV");

			container.innerHTML += this.getFBLike(href);
			container.innerHTML += this.getTweetButton(href, title);

			$(container).appendTo(this.SELECTOR + " .content");
			this._contentCache[href] = container;
		} else {
			this._contentCache[href].style.display = "block";
		}
	},

	getFBLike : function(href) {
		return '<iframe src="//www.facebook.com/plugins/like.php?href=' +
				encodeURIComponent(href) +
				'&amp;send=false&amp;layout=button_count&amp;action=like&amp;colorscheme=light&amp;font=segoe+ui&amp;' +
				'width=' + this.WIDTH + '&amp;height=' + this.FB_HEIGHT +
				'&amp;appId=' + this.FB_APP_ID + '"' +
				' scrolling="no" frameborder="0" style="border:none; overflow:hidden;' +
				'width:' + this.WIDTH + 'px; height:' + this.FB_HEIGHT + 'px;"' +
				'allowTransparency="true"></iframe>';
	},

	getTweetButton : function(href, title) {
		var qstring = decodeURIComponent($.param({
			url : href,
			count : "horizontal",
			via : this.TWITTER_ACCOUNT,
			text : encodeURIComponent(title)
			// use counturl for the full url if href is a short url
		})); // TODO: Fix weird encoding/decoding.
		return '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="//platform.twitter.com/widgets/tweet_button.html?'+qstring+'" style="width:' +
				this.WIDTH + 'px; height:' + this.TWEET_HEIGHT + 'px;' +
				'"></iframe>';
	},

	handle_show : function() {
		LikeBox.showContent(this);

		var $offset = $(this).offset();
		$(LikeBox.SELECTOR).css({
		      'top': $offset.top + $(this).height()/2 - 30, // TODO: Unmagic this number.
		      'left': $offset.left + $(this).width() + 15  // TODO: Unmagic this number.
		  });
		$(LikeBox.SELECTOR).fadeIn(125);
	},
	handle_leave : function() {
		LikeBox.tryHide(this);
	},

	handle_enterBox : function() {
		clearTimeout(LikeBox._timeoutId);
	},

	handle_leaveBox : function() {
		$(LikeBox.SELECTOR).fadeOut(125);
	}

};
