(function($) {
	$.jAlert = function(message, tipo_mensagem, titulo, options){
		if(tipo_mensagem != null){
			tipo_mensagem = $.trim(tipo_mensagem.toLowerCase());
		}
		if(tipo_mensagem == 'auto'){
			messages = message.split('|}]');
			for(p=0; p<messages.length-1; p++){
				dados = $.trim(messages[p]).split('[{|');
				message = dados[0];
				tipo_mensagem = dados[1];
				$.jAlert(message, tipo_mensagem);
			}
		}else{
			if(titulo == null && tipo_mensagem == 'erro'){
				titulo = 'Erro';
			}else
			if(titulo == null && tipo_mensagem == 'atencao'){
				titulo = 'Atenção';
			}else
			if(titulo == null && tipo_mensagem == 'info'){
				titulo = 'Informação';
			}else
			if(titulo == null && tipo_mensagem == 'certo'){
				titulo = 'Sucesso';
			}
			if(titulo == null){
				titulo = document.URL.split('/')[2];
			}
			options = $.extend({},$.jAlert.defaults,options);
			$.jAlert.currentPrefix = options.prefix;
	
			var ie6		= ($.browser.msie && $.browser.version < 7);
			var $body	= $(document.body);
			var $window	= $(window);
	
			//build the box and fade
			var msgbox = '<div class="'+ options.prefix +'box" id="'+ options.prefix +'box">';
			if(options.useiframe && (($('object, applet').length > 0) || ie6)) {
				msgbox += '<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></iframe>';
			} else {
				if(ie6) {
					$('select').css('visibility','hidden');
				}
				msgbox +='<div class="'+ options.prefix +'fade" id="'+ options.prefix +'fade"></div>';
			}
			msgbox += '<div rel="impromptu" class="'+ options.prefix +' jqi_'+tipo_mensagem+'" id="'+ options.prefix +'"><div class="'+ options.prefix +'container">';
			msgbox += '<div class="'+ options.prefix +'barratitulo" id="'+ options.prefix +'barratitulo"><h4 class="'+ options.prefix +'titulo">'+titulo+'</h4>';
			msgbox += '<a class="'+options.prefix +'close" title="Fechar esta Mensagem">X</a></div><div id="'+ options.prefix +'states"></div>';
			msgbox += '</div></div></div>';
	
			var $jqib	= $(msgbox).appendTo($body);
			var $jqi	= $jqib.children('#'+ options.prefix);
			var $jqif	= $jqib.children('#'+ options.prefix +'fade');
	
			//if a string was passed, convert to a single state
			if(message.constructor == String){
				message = {
					state0: {
						html: message,
						buttons: options.buttons,
						focus: options.focus,
						submit: options.submit
					}
				};
			}
	
			//build the states
			var states = "";
	
			$.each(message,function(statename,stateobj){
				stateobj = $.extend({},$.jAlert.defaults.state,stateobj);
				message[statename] = stateobj;
	
				states += '<div id="'+ options.prefix +'_state_'+ statename +'" class="'+ options.prefix + '_state" style="display:none;"><div class="'+ options.prefix +'message">' + stateobj.html +'</div><div class="'+ options.prefix +'buttons">';
				$.each(stateobj.buttons, function(k, v){
					states += '<button name="' + options.prefix + '_' + statename + '_button' + k + '" id="' + options.prefix +	'_' + statename + '_button' + k + '" value="' + v + '">' + k + '</button>';
				});
				states += '</div></div>';
			});
	
			//insert the states...
			$jqi.find('#'+ options.prefix +'states').html(states).children('.'+ options.prefix +'_state:first').css('display','block');
			$jqi.find('.'+ options.prefix +'buttons:empty').css('display','none');
			
			//Events
			$.each(message,function(statename,stateobj){
				var $state = $jqi.find('#'+ options.prefix +'_state_'+ statename);
	
				$state.children('.'+ options.prefix +'buttons').children('button').click(function(){
					var msg = $state.children('.'+ options.prefix +'message');
					var clicked = stateobj.buttons[$(this).text()];
					var forminputs = {};
	
					//collect all form element values from all states
					$.each($jqi.find('#'+ options.prefix +'states :input').serializeArray(),function(i,obj){
						if (forminputs[obj.name] === undefined) {
							forminputs[obj.name] = obj.value;
						} else if (typeof forminputs[obj.name] == Array) {
							forminputs[obj.name].push(obj.value);
						} else {
							forminputs[obj.name] = [forminputs[obj.name],obj.value];	
						} 
					});
	
					var close = stateobj.submit(clicked,msg,forminputs);
					if(close === undefined || close) {
						removePrompt(true,clicked,msg,forminputs);
					}
				});
				$state.find('.'+ options.prefix +'buttons button:eq('+ stateobj.focus +')').addClass(options.prefix +'defaultbutton');
	
			});
	
			var ie6scroll = function(){
				$jqib.css({ top: $window.scrollTop() });
			};
	
			var fadeClicked = function(){
				if(options.persistent){
					var i = 0;
					$jqib.addClass(options.prefix +'warning');
					var intervalid = setInterval(function(){
						$jqib.toggleClass(options.prefix +'warning');
						if(i++ > 1){
							clearInterval(intervalid);
							$jqib.removeClass(options.prefix +'warning');
						}
					}, 100);
				}
				else {
					removePrompt();
				}
			};
			
			var keyPressEventHandler = function(e){
				var key = (window.event) ? event.keyCode : e.keyCode; // MSIE or Firefox?
				
				//escape key closes
				if(key==27) {
					removePrompt();	
				}
				
				//constrain tabs
				if (key == 9){
					var $inputels = $(':input:enabled:visible',$jqib);
					var fwd = !e.shiftKey && e.target == $inputels[$inputels.length-1];
					var back = e.shiftKey && e.target == $inputels[0];
					if (fwd || back) {
					setTimeout(function(){ 
						if (!$inputels)
							return;
						var el = $inputels[back===true ? $inputels.length-1 : 0];
	
						if (el)
							el.focus();						
					},10);
					return false;
					}
				}
			};
			
			var positionPrompt = function(){
				$jqib.css({
					position: (ie6) ? "absolute" : "fixed",
					height: $window.height(),
					width: "100%",
					top: (ie6)? $window.scrollTop() : 0,
					left: 0,
					right: 0,
					bottom: 0
				});
				$jqif.css({
					position: "absolute",
					height: $window.height(),
					width: "100%",
					top: 0,
					left: 0,
					right: 0,
					bottom: 0
				});
				$jqi.css({
					position: "absolute",
					top: options.top,
					left: "50%",
					marginLeft: (($jqi.outerWidth()/2)*-1)
				});
			};
	
			var stylePrompt = function(){
				$jqif.css({
					zIndex: options.zIndex,
					display: "none",
					opacity: options.opacity
				});
				$jqi.css({
					zIndex: options.zIndex+1,
					display: "none"
				});
				$jqib.css({
					zIndex: options.zIndex
				});
			};
	
			var removePrompt = function(callCallback, clicked, msg, formvals){
				$jqi.remove();
				//ie6, remove the scroll event
				if(ie6) {
					$body.unbind('scroll',ie6scroll);
				}
				$window.unbind('resize',positionPrompt);
				$jqif.fadeOut(options.overlayspeed,function(){
					$jqif.unbind('click',fadeClicked);
					$jqif.remove();
					if(callCallback) {
						options.callback(clicked,msg,formvals);
					}
					$jqib.unbind('keypress',keyPressEventHandler);
					$jqib.remove();
					if(ie6 && !options.useiframe) {
						$('select').css('visibility','visible');
					}
				});
			};
	
			positionPrompt();
			stylePrompt();
			
			//ie6, add a scroll event to fix position:fixed
			if(ie6) {
				$window.scroll(ie6scroll);
			}
			$jqif.click(fadeClicked);
			$window.resize(positionPrompt);
			$jqib.bind("keydown keypress",keyPressEventHandler);
			$jqi.find('.'+ options.prefix +'close').click(removePrompt);
	
			//Show it
			$jqif.fadeIn(options.overlayspeed);
			$jqi[options.show](options.promptspeed,options.loaded);
			$jqi.find('#'+ options.prefix +'states .'+ options.prefix +'_state:first .'+ options.prefix +'defaultbutton').focus();
			
			//CENTRALIZA 
			var box_width = $('div[rel=impromptu]').width();
			var box_heigth = $('div[rel=impromptu]').height();
			var margin = '-' + box_heigth/2 - 30 + 'px 0 0 -' + box_width/2 + 'px';
			$('div[rel=impromptu]').css({'margin' : margin, 'position' : 'absolute', 'top' : '50%', 'left' : '50%'});	
				
			if($.jAlert.defaults.draggable){
				try {
					$("div[rel=impromptu]").draggable({ opacity: 0.7, handle: 'div#jqibarratitulo' });
					$("div[rel=impromptu] div#jqibarratitulo").css({ cursor: 'move' });	
				} catch(e) { /* requires jQuery UI draggables */ }
			}
	
			if(options.timeout > 0)
				setTimeout($.jAlert.close,options.timeout);
			
			return $jqib;
		}
	};
	
	$.jAlert.defaults = {
		prefix:'jqi',
		buttons: {
			Ok: false
		},
	 	loaded: function(){

	 	},
	  	submit: function(){
	  		return true;
		},
	 	callback: function(){

	 	},
		opacity: 0.6,
	 	zIndex: 999,
	  	overlayspeed: 'slow',
	   	promptspeed: 'fast',
   		show: 'fadeIn',
	   	focus: 0,
	   	useiframe: false,
	 	top: "0",
	  	persistent: true,
	  	timeout: 0,
		draggable: true,
	  	state: {
			html: '',
		 	buttons: {
		 		Ok: true
		 	},
		  	focus: 0,
		   	submit: function(){
		   		return true;
		   }
	  	}
	};
	
	$.jAlert.currentPrefix = $.jAlert.defaults.prefix;

	$.jAlert.setDefaults = function(o) {
		$.jAlert.defaults = $.extend({}, $.jAlert.defaults, o);
	};
	
	$.jAlert.setStateDefaults = function(o) {
		$.jAlert.defaults.state = $.extend({}, $.jAlert.defaults.state, o);
	};
	
	$.jAlert.getStateContent = function(state) {
		return $('#'+ $.jAlert.currentPrefix +'_state_'+ state);
	};
	
	$.jAlert.getCurrentState = function() {
		return $('.'+ $.jAlert.currentPrefix +'_state:visible');
	};
	
	$.jAlert.getCurrentStateName = function() {
		var stateid = $.jAlert.getCurrentState().attr('id');
		
		return stateid.replace($.jAlert.currentPrefix +'_state_','');
	};
	
	$.jAlert.goToState = function(state) {
		$('.'+ $.jAlert.currentPrefix +'_state').slideUp('slow');
		$('#'+ $.jAlert.currentPrefix +'_state_'+ state).slideDown('slow',function(){
			$(this).find('.'+ $.jAlert.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.jAlert.nextState = function() {
		var $next = $('.'+ $.jAlert.currentPrefix +'_state:visible').next();

		$('.'+ $.jAlert.currentPrefix +'_state').slideUp('slow');
		
		$next.slideDown('slow',function(){
			$next.find('.'+ $.jAlert.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.jAlert.prevState = function() {
		var $next = $('.'+ $.jAlert.currentPrefix +'_state:visible').prev();

		$('.'+ $.jAlert.currentPrefix +'_state').slideUp('slow');
		
		$next.slideDown('slow',function(){
			$next.find('.'+ $.jAlert.currentPrefix +'defaultbutton').focus();
		});
	};
	
	$.jAlert.close = function() {
		$('#'+ $.jAlert.currentPrefix +'box').fadeOut('fast',function(){
        		$(this).remove();
		});
	};
	
	//ALIAS PARA AS FUNCOES CURTAS
	jAlert = function(message, tipo_mensagem, titulo, options){
		$.jAlert(message, tipo_mensagem, titulo, options);
	}
	
})(jQuery);
