/**
 * Wings Plugin
 *
 * Inserts 'wings' around the provided component to provide a visual left/right
 * elements, that don't affect the actual window
 *
 * @author Ben Rowe <ben.rowe@austereo.com.au>
 */
(function($) {
	jQuery.fn.wings = function(options)
	{
		var self = this;

		// compile options
		var options = options || {};
		options = $.extend({
			autoReposition: true,
			className: 'wings'
		}, options);

		return self.each(function() {

			var myself = this;
			// the wing widths
			var lwOrigWidth = false;
			var rwOrigWidth = false;

			injectWings(myself);
			
			positionWings();

			if(options.autoReposition) {
				$(window).resize(function() {
					positionWings();
				})
			}

			/**
			 * Position wings based on the current parent container & window
			 * widths
			 */
			function positionWings()
			{
				// position relative to the current item
				var cWidth = $(myself).width();
				var cOffset	= $(myself).offset();
				// displaywidth
				var wWidth = $(window).width();

				var $lW = $('.'+options.className+' .left');
				var $rW = $('.'+options.className+' .right');

				if(!lwOrigWidth && !rwOrigWidth) {
					// set the original width as set by css!
					lwOrigWidth = $lW.width();
					lwOrigWidth = $rW.width();
				}

				if(wWidth > cWidth) {

					$lW.filter(':hidden').show();
					$rW.filter(':hidden').show();

					var slWidth = Math.min(lwOrigWidth, cOffset.left);
					var srWidth = Math.min(lwOrigWidth, wWidth - (cOffset.left + cWidth));

					// set the width & offset
					$lW
						.css({
							// pull back width of lhs
							left: '-'+slWidth+'px'
						})
						.width(slWidth);
					$rW
						// offset by parent width
						.css({
							'left': cWidth
						})
						.width(srWidth);
				} else {
					// no room, hide wings
					$lW.filter(':visible').hide();
					$rW.filter(':visible').show();
				}
			}
		});

		/**
		 * Inject the wings relative to their parent
		 */
		function injectWings(relTo)
		{
			var css = {position: 'absolute'};

			// create a container that will be positioned relative to the parent
			// (top-left), wing position calculations will be relative from this
			// point
			var wings = $('<div />')
				.addClass(options.className)
				// wing container is positioned within the top-left corner of
				// the parent, calculations will be based from this point
				.css(css);
				
			$('<div class="left" />')
				.css(css)
				.appendTo(wings);
			$('<div class="right" />')
				.css(css)
				.appendTo(wings);

			wings.prependTo(relTo);
		}
	}
})(jQuery);
