/**
 * Background gallery plugin 4 jQuery
 * 
 * @author Bartlomiej Marciniuk (redliquid)
 * @copyright Bartlomiej Marciniuk
 * @version 0.3
 */

(function($)
{
	var opts;
	var gallery;
	var imageClock = null;
	var scroll = null;
	var widthSub;
	var heightSub;
	var width;
	var height;
	var imageIndex = 0;
	var thisObj;
	var onChangeCallback = null;

	$.fn.backgroundGallery = function( method )
	{
		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' );
		}
	};


	$.fn.backgroundGallery.defaults =
	{
		fadeSpeed:		'slow',							// fade speed
		interval:		10000,							// interval between next image [ms]
		loadingImage:	'/public/images/ajax-loader.gif',	// set loading image
		noResize:		false
	};

	var methods = {
		init : function( options )
		{
			// extend given options
			$.extend(true, $.fn.backgroundGallery.defaults, options);

			// apply 'image loader' to all matched elements by plugin start
			thisObj = this;
			
			return this.each(function()
			{
				// create loading image and center it
				var loadingImage = $('<img/>');
				loadingImage.css({
					position: 'absolute',
					left: ( parseInt($(this).width() / 2) - 17 - 54),
					top: ( parseInt($(this).height() / 2) - 17 - 54)
				});
				loadingImage.attr('src', $.fn.backgroundGallery.defaults.loadingImage);
				loadingImage.addClass('loading');
				$(this).append(loadingImage);
			})
		},
		onChange : function( data )
		{
			onChangeCallback = data;
		},
		setData : function( data )
		{
			// set data of current gallery
			galleryData = data;
		},
		show : function( index )
		{
			
			if (index != undefined) imageIndex = index;
			if (galleryData[imageIndex] == undefined) imageIndex = 0;

			// apply show method to every matched element from jQuery selector
			return this.each(function()
			{
				$this = $(this);
				// get 'this' width and height
				width = $this.width();
				height = $this.height();

				var galleryImage = $('<img/>');

				// check, what dimension is closer to full
				if ( $.fn.backgroundGallery.defaults.noResize == false)
				{
					widthSub = galleryData[imageIndex].width - width;
					heightSub = galleryData[imageIndex].height - height;

					// image width is closer to container width, scale to full width
					var targetWidth = width;
					var ratio = galleryData[imageIndex].width / width;

					heightSub = parseInt(galleryData[imageIndex].height / ratio);

					$(galleryImage).hide();
					$(galleryImage).width(targetWidth);

					$(galleryImage).css('position', 'absolute');
					$(galleryImage).css('left', '0');
					
					// calculate top position
					// 1. resize width and height proporionally (width first)
					var destinationWidth = width;
					var widthRatio = (galleryData[imageIndex].width / destinationWidth);
					var destinationHeight = galleryData[imageIndex].height / widthRatio;
					
					var top = (destinationHeight - height) / 2;
					if (top < 0) top = 0;
					
					$(galleryImage).css('top', '-'+top+'px');
				}
				else
				{
					// center image ONLY
					// make black background
					$('#bigPicture').css('background-color', '#000');
					
					var imageWidth = galleryData[imageIndex].width;
					var imageHeight = galleryData[imageIndex].height;

					$(galleryImage).hide();
					$(galleryImage).css('position', 'absolute');


					if ( (imageWidth <= width) && (imageHeight <= height) )
					{
						// center only
						$(galleryImage).css('top', ((height - galleryData[imageIndex].height) / 2)+'px');
						$(galleryImage).css('left', ((width - galleryData[imageIndex].width) / 2)+'px');
					}
					else
					{
						// resize
						var targetHeight = height;
						var targetWidth = width;
						
						
						// thx for http://thingsilearned.com/2008/12/27/proportional-image-resize-in-javascript/
						function scaleSize(img, maxh, maxw) {
						  var ratio = maxh/maxw;
						  if (img.height/img.width > ratio){
							 // height is the problem
							if (img.height > maxh){
							  img.width = Math.round(img.width*(maxh/img.height));
							  img.height = maxh;
							}
						  } else {
							// width is the problem
							if (img.width > maxh){
							  img.height = Math.round(img.height*(maxw/img.width));
							  img.width = maxw;
							}
						  }
						  return img;
						}
						
						var newSize = scaleSize({width: imageWidth, height: imageHeight}, height, width);
						
						$(galleryImage).width(newSize.width);
						$(galleryImage).height(newSize.height);
						
						$(galleryImage).css('top', ((height - newSize.height) / 2)+'px');
						$(galleryImage).css('left', ((width - newSize.width) / 2)+'px');
						
					}
					
				}
				
				$(galleryImage).one("load",function(){
					
					if ( onChangeCallback )
					{
						onChangeCallback(galleryData[imageIndex]);
					}
					if ($.fn.backgroundGallery.defaults.noResize == true)
					{
						var cImage = $this.find('img');
						if (cImage)
						{
							$this.find('img').fadeOut(2000);
						}
					}
					$(this).fadeIn(2000, function(){
						imageIndex++;
						$(this).parent().find('img').eq(0).remove();
					});
					$this.append(this);
				})
				.each(function(){
					if(this.complete || (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6))
					$(this).trigger("load");
				});
				$(galleryImage).attr('src', galleryData[imageIndex].image);

				//
			});
		},
		cycle : function ( index )
		{
			if (galleryData && galleryData.length > 0)
			{
				if (imageClock != null) clearInterval(imageClock);
				
				if (index != undefined)
				{
					thisObj.backgroundGallery('show', index);
					imageClock = setInterval(function() {thisObj.backgroundGallery('show');} , $.fn.backgroundGallery.defaults.interval);
				}
				else
				{
					thisObj.backgroundGallery('show', index);
					imageClock = setInterval(function() {thisObj.backgroundGallery('show');} , $.fn.backgroundGallery.defaults.interval);
				}
			}
		}

	};

})(jQuery);
