/*
 * @copyright		© Copyright 2006-2010, epages GmbH, All Rights Reserved.
 *
 * @module			ep.fn.busy
 */

define("ep/fn/busy", [
	"jquery",
	"ep"
], function ($, ep) {

	var stack = [];

	// remove all busy layers on page leave
	$(window)
		.on("unload", function(){
			$(stack)
				.remove();
			stack = [];
		});

	ep.fn.extend({
		/**
		 * Add or remove a busy layer to each of the set of matched elements.
		 * 
		 * The `.busy()` method adds/removes a busy layer to/from each of the set of matched elements.
		 * 
		 * On page unload every busy layer will be removed. This prevents showing busy layer after
		 * come back via browsers back button.
		 * 
		 * ### Examples
		 * Show a busy layer on body.
		 * 
		 * JavaScript:
		 * 
		 *     ep('div').busy('show');
		 * 
		 * HTML:
		 * 
		 *     <body>
		 *       <h1>Example</h1>
		 *       <div>My test case ...</div>
		 *       <div>A footer.</div>
		 *     </body>
		 * 
		 * Results:
		 * 
		 *     <body>
		 *       <h1>Example</h1>
		 *       <div>My test case ...</div>
		 *       <div>A footer.</div>
		 *       <div class="ep-busy"></div>
		 *     </body>
		 * 
		 * Hide a busy layer on body.
		 * 
		 * JavaScript:
		 * 
		 *     ep('div').busy('hide');
		 * 
		 * HTML:
		 * 
		 *     <body>
		 *       <h1>Example</h1>
		 *       <div>My test case ...</div>
		 *       <div>A footer.</div>
		 *       <div class="ep-busy"></div>
		 *     </body>
		 * 
		 * Results:
		 * 
		 *     <body>
		 *       <h1>Example</h1>
		 *       <div>My test case ...</div>
		 *       <div>A footer.</div>
		 *     </body>
		 * 
		 * 
		 * @param {String} action An action for busy layer, 'show' or 'hide'.
		 * 
		 * @method busy
		 * @member jQuery
		 * 
		 * @since 6.11.0
		 */
		busy: function( action ){
			return this.each(function(){
				var elem = $(this),
					layer = elem.find('> .ep-busy');

				if( action==='hide' ){
					var pos = $.data( this, 'epBusyOldposition');

					if( pos === 'static' ){
						$.removeData( this, 'epBusyOldposition' );
						elem.css('position','relative');
					}

					layer.remove();
				}
				else if( !layer.length ){
					var pos = elem.css('position');

					if( pos === 'static' ){
						$.data( this, 'ep-busy-oldposition', pos );
						elem.css('position','relative');
					}

					stack.push( $('<div>')
						.attr('class','ep-busy')
						.css( 'border-radius', elem.css('border-radius') )
						.appendTo( elem )[0] );
				}
			});
		}
	});

	return ep;

});