var evonModalLastId = 0;

(function($) {
	
	$.fn.modal2 = function (options)
	{
		var close = function(e)
		{
			$("#overlay").remove();
			$(".evonModal-close").remove();
			$(".evonModal-title").remove();
			
			$(e.data.object).removeClass("modal"+e.data.id);
			$(e.data.object).removeClass("evonModal-content");
			$(e.data.object).hide();
		};
	
		// opções padrão
		 var defaults = {
			 title: null,
			 minWidth: 350,
			 maxWidth: 600,
			 actions:""
		 };

		 if(typeof options == "string")
		 {
			 defaults.title = options;
			 options = defaults;
		 }
		 else
		 {
			 //options = $.extend(defaults, options);
			 options = $.extend({}, defaults, options||{});
		 }
		 if(options.action == "close")
		 {
			 $(".evonModal-close").click();
			 return $(this);
		 }
		 
		evonModalLastId++;
		var closeSize = 32;
		$(this).modalid = evonModalLastId; 
		$(this).addClass("evonModal-content");
		$(this).addClass("modal"+evonModalLastId);
		
		$("#overlay").remove();
		$("body").append("<div id='overlay'></div>");
		$("body").append("<img id='evonModal-close' class='evonModal-close close" + evonModalLastId + "' src='/imgs/button_cancel.png'/>");
		if(options.title!=null)
		{			
			$(this).prepend("<h3 class='evonModal-title'>" + options.title + "</h3>");
		}
		var margin = $("#overlay").width();
		var width = $(".evonModal-content").width();
		if(width<options.minWidth)
		{
			$(".evonModal-content").width(options.minWidth);
			width=options.minWidth;
		}
		else if (width>options.maxWidth)
		{
			$(".evonModal-content").width(defaults.maxWidth);
			width=options.maxWidth;
		}
		var contentLeftMargin = (margin/2)-(width/2);
		$(".evonModal-content").css("margin-left",contentLeftMargin);
		$(".evonModal-content").css("margin-left","-="+$(".evonModal-content").css("paddingLeft"));
		$(".evonModal-close").css("left",contentLeftMargin+width+(closeSize/2)-5);
		$(".evonModal-close").bind("click",{object:this,id:evonModalLastId},close);
		
		$(this).show();
		
		return $(this);
	};
})(jQuery);
