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

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

	// collapse/expand the "dropdown"
	var changeShareDropDown = function(show) {
		var itemId = $(this).attr('rel');
		if(typeof(show) == 'undefined') show = false;
		else if($(this) != null && $(this).attr('id') == '') var show = true;
		$('.toggleShareList').attr('id', '');
		$('.shareList').hide();

		if(show) {

			$(this).attr('id', 'shareSelected');
			if(itemId) $('#share' + itemId + ' .shareList').show();
			else $('.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();
		}
	}

	// 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(this);
	});

	$('.share a').click(function(e){
		e.preventDefault();

		if($('.shareList').is(':visible')) { changeShareDropDown.call(this); }
		else { 	changeShareDropDown.call(this, true); }

		// return false so the document click doesn't get triggered
		return false;
	});
});
