// wrap plugin in a closure
(function($) {
	// stretch plugin definition
	$.fn.stretch =
		function(options) {
			// extend default options with those provided
			var opts = $.extend({}, $.fn.stretch.defaults, options);

			return this.each(function() {
				var $this = $(this);

				// build element specific options
				var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;

				// plugin functionality starts here

				// fade element in on load event
				(
					function() {
						var initial =
							function() {
								$this
									.fadeOut(0)
									.queue(
										function() {
											var width = $this.parent().innerWidth();
											$this
												.data('width', width)
												.css(
													{
														width: width
													}
												);
											$this.dequeue();
										}
									)
									.fadeIn(o.fadeTime);
							};

						var image = new Image();
						image.onLoad = initial();
						image.src = $this.attr('src');
					}
				)()

				var $parent = $this.parent();

				// when window is resized, fade out element,
				// rescale to fit parent, fade in element
				$(window).bind(
					'resize',
					function() {
						var oldWidth = $this.data('width');
						var newWidth = $parent.innerWidth();

						if (oldWidth == newWidth) return true;

						$this
							.stop(true)
							.fadeTo(
								Math.floor(o.fadeTime / 2),
								0
							)
							.queue(
								function() {
									$this
										.css(
											{
												width: newWidth
											}
										)
										.dequeue();
								}
							)
							.fadeTo(
								o.fadeTime,
								1,
								function() {
									$this.data('width', $this.width());
								}
							);
					}
				);
			});
		};

			// stretch plugin default options
	$.fn.stretch.defaults =
		{
			fadeTime: 1000
		};
})(jQuery);
