$.extend($.modal, {
	close_current: function () {
		// Cancela animações ativas
		$('.modalContainer,.modalOverlay,.modalData').stop();
		// Fecha a janela atual
		$.modal.impl.close(false);
		return false;
	},
	close_on_esc: function (e) {
		// Fecha a janela ao pressionar a tecla ESC
		if (e.keyCode == 27) {
			$.modal.close_current();
			return false;
		}
	},
	template: function (title, id) {
		var wnd =
			$('<div />').addClass('window').append(
				$('<h2 />').append(
					$('<span />').text(title)
				).append(
					$('<a />').attr({href: '#', title: 'Fechar janela'}).addClass('modalClose').text('X')
				)
			)
		;
		if (id) {
			wnd.attr('id', id);
		}
		return wnd.appendTo('body');
	},
	ajaxCache: {},
	ajaxWindow: function (url, template_params, callback) {
		
		if ($.isFunction(template_params)) {
			callback = template_params;
			template_params = ['&nbsp;'];
		}
		
		// There's no cache entry for this URL?
		if ($.modal.ajaxCache[url] == null) {
			
			// Get the URL
			$.get(url, function(data){
				
				// Create a window template, append the loaded data, append the window to the body and save the cache entry
				$.modal.ajaxCache[url] = $.modal.template.apply(null, template_params).append($(data));
				
				// Run the callback if is a valid function
				if ($.isFunction(callback)) {
					callback.apply($.modal.ajaxCache[url], [data]);
				}
				
				// Show the window
				$.modal.ajaxCache[url].modal();
				
			});
			
			// Data loaded
			return true;
			
		}
		// Entry is cached
		else {
			// Show the window from cache
			$.modal.ajaxCache[url].modal();
			
			// Data not loaded, using cache
			return false;
		}
	}
});

// Opções padrão para abertura de janelas
$.extend($.modal.defaults, {
	// Sem botão de fechar
	close: false,
	// Persistir dados e elementos ao fechar/reabrir
	persist: true,
	onOpen: function (dialog) {
		
		// Encontra a janela atual
		$(dialog.data)
			// Re-exibe o formulário e limpa status de "carregando"
			.find('form').show().removeData('loading')
				// Limpa labels marcados com erro
				.find('label.error').removeClass('error')
			// Retorna ao formulário
			.end()
		// Retorna à janela
		.end()
			// Procura caixas de mensagem e limpa status de erro/sucesso
			.find('div.msg').removeClass('ok error').empty()
		;
		
		// Abre com marrência
		dialog.overlay.slideDown(function () {
			dialog.container.show();
			dialog.data.hide().show('normal');
		});
	},
	onShow: function (dialog) {
		// Atribui evento para fechar a janela ao pressionar a tecla ESC
		$(document).keypress($.modal.close_on_esc);
	},
	onClose: function (dialog) {
		
		// Limpa o evento associado no 'onShow'
		$(document).unbind('keypress', $.modal.close_on_esc);
		
		// Fecha com marrência
		dialog.overlay.slideUp();
		dialog.data.hide('normal', function () {
			dialog.container.hide();
			// Fecha janela, container e overlay
			$.modal.close();
		});
		
	}
});

$(function(){
	// Corrige redimensionamento no IE6
	if ($.browser.msie && ($.browser.version <= 6)) {
		$(window).wresize(function(){
			$('#modalOverlay').width($(this).width());
		});
	}
});
