// JavaScript Document

(function($) {
	$.fn.gnCover = function (options) {
		var defaults = {
			testing: false,
			isCentered: false,
			fullscreen: true,
			folder: 'images/index',
			top: 0,
			bottom: 0,
			left: 0,
			right: 0
		};
		var o = $.extend(defaults, options);
		
		
		var divContainer = this;
		if(o.fullscreen) {
			var realHeight = $(window).height() - o.top - o.bottom;
			var realWidth = $(window).width() - o.left - o.right;
			divContainer.css("width", realWidth + 'px');
			divContainer.css("height", realHeight + 'px');
		}
		var wMainPhotoDiv = divContainer.css("width");
		var hMainPhotoDiv = divContainer.css("height");
		var screenRatio = hMainPhotoDiv.replace(/px/,'')/wMainPhotoDiv.replace(/px/,'');
		
		$("#coverPhoto").remove();
		divContainer.addClass('loading');
		
		var img = new Image();
		$(img).load(function () {
			var imgRatio = $(this).attr("height")/$(this).attr("width");
			$(this).hide();
			divContainer.removeClass('loading').append(this);
			if(imgRatio >= screenRatio || o.testing==true) {
				$(this).css("width",wMainPhotoDiv);
				$(this).css("height",wMainPhotoDiv.replace(/px/,'')*imgRatio);
				if(o.isCentered) $(this).css("marginTop", ( hMainPhotoDiv.replace(/px/,'') - $(this).height() ) /2 );
				else {
					$(this).css("marginTop", 0);
					$(this).css("marginLeft", 0);
				}
			}
			else {
				$(this).css("height",hMainPhotoDiv);
				if(o.isCentered) $(this).css("marginLeft", ( wMainPhotoDiv.replace(/px/,'') - $(this).width() ) /2 );
				else {
					$(this).css("marginTop", 0);
					$(this).css("marginLeft", 0);
				}
			}
			$(this).fadeIn("fast");
		})
		.error(function () {
		})
		.attr('src', o.folder+'/cover.jpg').attr('id', 'coverPhoto');
		
		return divContainer;
	}
})(jQuery);