/**
 * @author Benjamin Falk / Euroweb
 * Published under GPLv3
 * see http://www.gnu.org/licenses/gpl.html
 */

(function( $ ){
	var settings = {
		'autoset':				true,			// if true, loads the first image into background, when loaded
		'backgroundselector':	'#background',	// background element
		'linkselector':			'a',			// link selector for link-elements
		'fxDuration':			'slow',			// duration of fading
		'reposition':			true,			// reposition image to always be centered
		'nogallery':			false
	}
	
	var initDone = false;
	
	var methods = {
		/**
		 * inits plugin for a set of images
		 */
		init : function( options ) {
			if ( options ) {
				$.extend( settings, options );
			}
			
			// check if image object is available in backgroundselector
			if ($(settings.backgroundselector).children('img').length == 0) {
				$(settings.backgroundselector).append('<img src="" alt="" />');
				$(settings.backgroundselector).children('img').hide();
			}
			
			$(window).resize(function() {
				methods.dim();
			});
			
			if ($.browser.msie) {
				$(window).scroll(function() {
					methods.dim();
				});
			}
			
			var firstHref = false;
			// set click event of links
			if (!settings.nogallery) {
				return this.each(function() {
					// get first background-picture
					if (settings.autoset === true && firstHref === false) {
						firstHref = $(this).children(settings.linkselector).attr("href");
						methods.view(firstHref);
					}
					$(this).children(settings.linkselector).click(function(evt) {
						evt.preventDefault();
						methods.view($(this).attr("href"));
					});
				});
			}
			
			initDone = true;
		},
		
		/**
		 * loads background-image and views it
		 */
		view : function( href, options ) {
			if (!initDone) {
				if (typeof options == 'undefined') {
					options = {};
				}
				methods.init($.extend({ 'nogallery': true }, options));
			}
			
			var preload = new Image();
			preload.onload = function() {
				// hide image
				var objImg = settings.backgroundselector+' img';
				$(objImg).stop();
				viewImg = function() {
					$(objImg).attr("src", href);
					$(settings.backgroundselector).data('curDim', {
						'width': preload.width,
						'height': preload.height
					});
					// give the browser time to load picture
					setTimeout(function() {
						methods.dim();
						if (settings.fxDuration == false) {
							$(objImg).show();
						}
						else {
							$(objImg).fadeIn(settings.fxDuration);
						}
					}, 50);
				}
				if ($(objImg).is(':visible')) {
					$(objImg).fadeOut(settings.fxDuration, function() { viewImg() });
				}
				else {
					viewImg();
				}
			}
			preload.src = href;
		},
		
		/**
		 * Calculates new dimension and position for background image
		 */
		dim : function() {
			if (!initDone) {
				methods.init({ 'nogallery': true });
			}
			
			var winWidth	= $(window).width();
			var winHeight	= $(window).height();
			
			var _dim		= $(settings.backgroundselector).data('curDim');
			
			var newWidth	= winWidth;
			var newHeight	= Math.round( (_dim.height / _dim.width) * winWidth);
			
			// check if calculated height is enough to fit
			if (winHeight > newHeight) {
				var newHeight	= winHeight;
				var newWidth	= Math.round( (_dim.width / _dim.height) * winHeight);
			}
			
			// set dimensions
			$(settings.backgroundselector).children('img').attr('width', newWidth);
			$(settings.backgroundselector).children('img').attr('height', newHeight);
			
			var marginLeft	= Math.round(newWidth / 2);
			var marginTop	= Math.round(newHeight / 2);
			
			// set position
			if (settings.reposition) {
				if ($.browser.msie && $.browser.version <= 7) {
					var winHeight = $(window).innerHeight();
					$("#background").show();
					$("#background").css({
						top: $(document).scrollTop()+'px',
						overflow: 'hidden',
						height: winHeight+'px'
					});
					$("#background").fadeTo(1);
				}
				$(settings.backgroundselector).children('img').css({
					'left': '50%',
					'top': '50%',
					'marginLeft': '-'+marginLeft+'px',
					'marginTop': '-'+marginTop+'px'
				});

			}
		}
	};
	
	/**
	 * Plugin-Constructor
	 */
	$.fn.backgroundgallery = function( method ) {
		// Method calling logic
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.backgroundgallery' );
		}
	};

})( jQuery );
