(function($){
    var template;
    var counter = 0;
	
    $.notifications = function(msg, options) {
        counter++;
        
        var settings = $.extend({}, $.notifications.defaults, options);
        
		if (!template) {
        	//template = $('<div id="jquery-notifications"></div>').appendTo(document.body);
		}

		var n = settings.selector.prepend( '<span class="msg_' + settings.type + '" id="jquery-notifications-' + counter + '" style="display: none;">' + msg + '</span>');
		if( settings.effect == "fade" ) {
			$('#jquery-notifications-' + counter).fadeIn( settings.fadeSpeed );
		} else {
			$('#jquery-notifications-' + counter).slideDown( settings.fadeSpeed );
		}

		if (settings.stick) {
			var close = $('<a href="javascript:void(0);">' + settings.close + '</a>').click(function() {
				if (settings.effect == "fade") {
					$(this.parentNode).fadeOut( settings.fadeSpeed, function() {
						$(this).remove();
					});
				}
				else {					
					$(this.parentNode).slideUp( settings.fadeSpeed, function() {
						$(this).remove();
					});					
				}
			});
			close.appendTo(n);
		}		
    	
		if (!settings.stick) {
			var notificationsDelayer = delayTimer(settings.timeout);
			notificationsDelayer(update, { done: settings.done, counter: counter, effect: settings.effect, fadeSpeed : settings.fadeSpeed } );
		}
	};
	
	$.notifications.success = function( msg, options ){		
        return $.notifications( msg, $.extend( {}, options, { type : "success"}) );
    };
	
    $.notifications.error = function( msg, options ){
        return $.notifications( msg, $.extend( {}, options, { type : "error" }) );
    };
	
    $.notifications.warning = function( msg, options ){
        return $.notifications( msg, $.extend( {}, options, { type : "warning" }) );
    };
    
    $.notifications.info = function( msg, options ){
        return $.notifications( msg, $.extend( {}, options, { type : "info" }) );
    };	
    
    $.notifications.greybox = function( msg, options ){
        return $.notifications( msg, $.extend( {}, options, { type : "greybox" }) );
    };
    
    
    
	function update(params) {				
		if (params.effect == "fade") {
			$("#jquery-notifications-" + params.counter).fadeOut( params.fadeSpeed, function(){
				$(this).remove();
                params.done();
			});
		} else {
			$("#jquery-notifications-" + params.counter).slideUp( params.fadeSpeed, function(){
				$(this).remove();
                params.done();
			});			
		}
	}
	
	function delayTimer(delay) {
	    var timer;
	    return function(fn, params) {
	        timer = clearTimeout(timer);
	        if (fn)
	            timer = setTimeout(function() {
	                fn(params);
	            }, delay);
	        return timer;
	    };
	}	

	$.notifications.defaults = {
            type: "notice",
			timeout: 10000,
			stick: false,
			fadeSpeed : 800,
			close : "x",
			effect : "fade",
            done : function(){}
        };
    
	$.n = $.notifications;	 
	
})(jQuery);
