/* JS
* Copyright 2009 noponies.
* Version 0.1 Beta - Intial Release to the wild - comments, yes please!
*/
(function($){

	var img_prop;
	var imageArray = [];
	var opts = {};
	
	$.fn.extend({ 
		npFullBgImg: function(imgPath, options) {
			var defaults = {
				 fadeInSpeed: 1000,
   				 center: true,
				 height: 0
			};
			
			opts = $.extend(defaults, options);
			var targetContainer = $(this); 
			//create image
			var img  = new Image();
			//add to array
 	 		imageArray.unshift(img);
			
	        $(img).load(function () {
	         	$(img).css({left:0, top: 0, position: 'absolute', 'z-index': -100});
	            //add image to container
	            $(targetContainer).append(img);
	            //resize image
				resizeImg(img);
					            
	            $(img).fadeIn(opts.fadeInSpeed, function () {
		            if(imageArray.length > 1) {
		            	imageArray.pop();
		            	$(targetContainer).children().eq(0).remove();   	
		            }
		            
		          	if( typeof opts.callback == 'function' ){
						opts.callback.call(this, targetContainer, options);
					}

	            });
			
				$(window).bind("resize", function(){
						resizeImg(imageArray[0]);		  			
				});
	        }).error(function () {
	            // got an error
	            //alert('image not loaded');
	        }).attr('src', imgPath);
	    }
	});

  	function resizeImg(img){
			var sw = $(window).width();
			if(typeof containerResize !== 'undefined'){
				containerResize();	
			}
			if($(window).height() < $("#container-margin").height()){
				var sh = $("#container-margin").height();
			}else{
				var sh = $(window).height();
			}
			var imgw = $(img).width();
			var imgh = $(img).height();
			if ((sh / sw) > (imgh / imgw)) {
				img_prop = imgw/imgh;
				destHeight = sh;
				destWidth = sh * img_prop;
			} else {
				img_prop = imgh/imgw;
				destWidth = sw;
				destHeight = sw * img_prop;
			}

			$(img).attr({
				width: destWidth,
				height: destHeight
			});
			
			if(opts.center) {
				var xVal = sw * .5 - $(img).width() * .5;
				var yVal = sh * .5 - $(img).height() * .5;
				$(img).css({left:xVal, top: yVal});
			}
			if(typeof bgOffset !== 'undefined'){
				bgOffset();	
			}
	}

	
})(jQuery);

