var backgroundImage = new Class({
		
	options: {
		theImage: 'background_image',
		method: 'stretch',
		showLog: false
	},
	
	initialize: function (options) {

		var self = this;

		this.setOptions(options);
		this.parseOptions(this.options);		
		this.rendered = false;
		this.resizeInProgress = false;		
		this.render();
		
	},
	
	parseOptions: function(optionsObj) {
	
		for (var optionName in optionsObj) {
			this[optionName] = optionsObj[optionName];
		}
		
	},
	
	render: function() {
	
		var self = this;

		this.useImage = $(this.theImage);
		
		var coords = this.useImage.getCoordinates();
		this.originalImageWidth = coords.width;
		this.originalImageHeight = coords.height;
		delete coords; coords = null;
		
		if (this.originalImageWidth && this.originalImageHeight) {
			this.resizeAction(false);
		}
		
		var resizeAction = function(event){
			if (self.rendered && !self.resizeInProgress) {
				self.resizeAction();
			}
		};

		window.addEvent('resize', resizeAction); 
		
		this.rendered = true;
		
	},
	
	resizeAction: function(unload) {
	
		var self = this;
		
		this.resizeInProgress = true;
		
		var winW, winH, newHeight, newWidth;		
		
		if (document.body && document.body.offsetWidth) {
			winW = document.body.offsetWidth;
		 	winH = document.body.offsetHeight;
		}
		if (document.compatMode=='CSS1Compat' && document.documentElement && document.documentElement.offsetWidth ) {
			winW = document.documentElement.offsetWidth;
		 	winH = document.documentElement.offsetHeight;
		}
		if (window.innerWidth && window.innerHeight) {
		 	winW = window.innerWidth;
		 	winH = window.innerHeight;
		}
		
		if (this.method === 'stretch') {
			
			newWidth = winW;
			newHeight = winH;
			
		} else {
		
			var ratios = [this.originalImageWidth / this.originalImageHeight, this.originalImageHeight / this.originalImageWidth];
			
			if (this.originalImageWidth > this.originalImageHeight) {
			
				if ((winW * ratios[1]) < winH) {
					newWidth = winH * ratios[0];
					newHeight = winH;
				} else {
					newWidth = winW;
					newHeight = winW * ratios[1];
				}
			
			} else if (this.originalImageWidth < this.originalImageHeight) {
				
				if ((winH * ratios[0]) < winW) {
					newWidth = winW;
					newHeight = winW * ratios[1];
				} else {
					newWidth = winH * ratios[0];
					newHeight = winH;
				}
				
			} else {
				newHeight = winH;
				newWidth = winW;
			}			
		
		}
		
		this.useImage.setStyles({'height': newHeight, 'width': newWidth});		
		
		this.resizeInProgress = false;
	}
});

backgroundImage.implement(new Events, new Options);
