jQuery(function($){
	// collapse/expand the "dropdown"
	var changeShareDropDown = function(show) {

		if (typeof(show) == 'undefined') show = false;
		if ($(this) != null && $(this).find('.shareLink').attr('id') == '') var show = true;
		$('.shareLink').attr('id', '');
		$('.shareList').hide();

		if (show) {
			$(this).find('.shareLink').attr('id', 'shareSelected');

			$(this).find('.shareList').show();
		}
	}

	// cancel default behaviour (don't bubble, don't propagate default action)
	var preventDefaultAction = function(e) {
		e.cancelBubble = true;
		e.returnValue = false;
		if (e.stopPropagation) {
			e.stopPropagation();
			e.preventDefault();
		}
	}

	// hide all dropdowns (should already be done in css)
	$('.shareList').hide();

	// links open in new window
	$('.shareList > li > a').each(function() { $(this).attr('target', '_blank'); });


	// click handler: prevent default behaviour (following the "#"-link, bubbling through 'document' and thus closing the "dropdown")
	$('.shareLink').click(function(e) {
		if(!e) var e = window.event;
		preventDefaultAction(e);
	});

	// mousedown handler: open the "dropdown" when our mouse is down (this event is called before focus)
	$('.shareLink').mousedown(function(e) {
		changeShareDropDown.call(this.parentNode);
	});

	// focus handler: open "dropdown" on focus
	$('.shareLink').focus(function(e) {
		changeShareDropDown.call(this.parentNode, true);
	});


	// handle focusses: close "dropdown" when focus is no longer there
	$('*').focus(function(e) {
		if ($(this).parents('.shareBlock').length <= 0 && $(this).parents('.shareList').length <= 0) changeShareDropDown.call(null);
	});



	// click handler for 'anywhere in the document': close "dropdown" (but not if it's a rightclick)
	$(document).click(function(e) {
		if (!e) var e = window.event;
		var rightclick = false;
		if (e.which) rightclick = (e.which == 3);
		else if (e.button) rightclick = (e.button == 2);
		if (!rightclick) changeShareDropDown.call(null);
	});
});