$(function() {
	$.ajaxSetup({
		error: function(event, request, options, error) {
			switch (event.status) {
				case 401: window.location.replace('/login?from=' + encodeURIComponent(window.location.href));
				break;
			}
		}
	});

    $('.confirm').click(function() {
        return confirm('Are you sure?'); // TODO: Translation.
    });

	$('.modal').live('click', function() {
		var trigger = $(this);

		if ((id = trigger.data('dialog-id')) === undefined) {
			var dialog = $('<div></div>');
		} else {
			if ((dialog = $('#' + id)).length > 0) {
				var dialog = dialog;
			} else {
				var dialog = $('<div></div>').attr('id', id);
			}
		}

		var title, width, height;

		if ((title = trigger.data('dialog-title')) === undefined) {
			title = '';
		}

		if ((width = trigger.data('dialog-width')) === undefined) {
			width = 400;
		}

		if ((height = trigger.data('dialog-height')) === undefined) {
			height = 300;
		}

		var dialog = dialog.dialog({
			show: 'fade',
			hide: 'fade',
			modal: true,
			width: width,
			height: height,
			title: title,
			open: function() {
				$(this).html('<div class="loading"></div>');

				var href = trigger.attr('href');

				if (href === undefined) {
					href = trigger.data('dialog-href');
				}

				$(this).load(href, function(responseText, textStatus) {
					if (false) {
						window.location.href = responseText.redirect;
					} else {
						$(this).find('textarea, input').first().focus();
					}
				});
			},
			close: function(event, ui) {
				if (trigger.data('dialog-reuse') === false) {
					$(this).dialog('destroy');
					$(this).remove();
				}
			}
		});

		$.ui.dialog.overlay.resize(); // See http://bugs.jqueryui.com/ticket/5637.

		return false;
	});
});
