$(function() {
	$('div.context_help_button').each(function() {
		var node = $(this);
		var matches = node.attr('id').match(/context_help_box_(\d+)_([^_]+)_(\d+)/);

        var button_id = matches[1]+'_'+matches[2]+'_'+matches[3];
		var spot = matches[2];
		var id = matches[1];

		node.click(function(event) {
			var closedOld;

			$('div#context_help_node_' + spot + ' a.context_help_close').each(function(){
				$(this).click();
				closedOld = true;
			});

			if (closedOld) return;

			var contextBox = $('<div class="context_help_box">').attr('id', 'context_help_node_' + spot);
			var helpContent = $('<div class="context_help_content">').html($('div#context_help_box_content_' + button_id).text());
			var closeButton = $('<a class="context_help_close" href="#" alt="Piilota ohje">Piilota ohje</a>').click(function(){
				closeButton.parent().fadeOut(200, function(){$(this).remove();});
				return false;
			});
			var editButton = $('<a class="context_help_edit" href="#" alt="Muokkaa">Muokkaa</a>').click(function(){
				openWindow('admin.phtml?w=contexthelp&id=' + spot, 'context_help_' + spot)
				return false;
			});
			var deleteButton = $('<a class="context_help_delete" href="#" alt="Poista">Poista</a>').click(function(){
				openWindow('admin.phtml?w=contexthelp&id=' + spot + '&remove=1', 'context_help_' + spot)
				return false;
			});

			contextBox.append(helpContent);
			contextBox.append(closeButton);

			if (matches[3] == 1) {
				contextBox.append(editButton);

				if (id > 0) {
					contextBox.append(deleteButton);
				}
			}

			contextBox.css({
				position: 'absolute',
				display: 'none',
				zIndex: '50000',
				top: (node.offset().top - contextBox.outerHeight()) + 'px',
				left: (node.offset().left + node.outerWidth() + 10) + 'px'
			}).fadeIn(400);

			$('body').append(contextBox);
			event.preventDefault();
		});
	});
});
