

var homeImage = function(images, elems, maxOpacity) {

	if (!$.isArray(images)) {
		images = [images];
	}

	var self 			= this,
		prev			= null,
		current			= Math.round( Math.random() * (images.length+1) ),
		loaded			= [],
		preloading		= [],
		useBackground	= true,
		loading			= null,
		wsize			= {
			width:		0,
			height:		0
		},
		wrapper			= $('<div></div>'),
		fadeSpeed		= 400,
		rotateSpeed		= 60000,
		maxOpacity		= maxOpacity || 1,
		rotateItv,
		dbody			= $('body'),
		ie				= '\v'=='v';


	if (!images[current])
		current = 0;

	$.extend(self, {

		detectFeature: function() {

			return false;

			// the technique is taken from Modernizr

			var prop		= 'backgroundSize',
				uc			= 'BackgroundSize',
				domPrefixes 	= ['Webkit', 'Moz', 'O', 'ms', 'Khtml'],
				props   	= (prop + ' ' + domPrefixes.join(uc + ' ') + uc).split(' '),
				style		= elems.body.get(0).style;

			if (ie) {
				return false;
			}

			for ( var i in props ) {
				if ( style[ props[i] ] !== undefined) {
					return true;
				}
			}

			return false;
		},


		init: function() {

			var w = $(window);

			loading = loadingIndicator.get();

			self.setLoading(true);

			w.bind('resize', self.resize);

			wrapper.css({
				position:					'absolute',
				left:						0,
				top:						0,
				width:						'100%',
				height:						'100%',
				backgroundPosition:			'50% 50%',
				backgroundRepeat:			'no-repeat',
				'-webkit-background-size': 	'auto 100%',
				'-moz-background-size':		'auto 100%',
				'-o-background-size': 		'auto 100%',
				'background-size': 			'auto 100%'
			});

			self.set();
		},


		setLoading: function(state) {

			if (!loading.canvas)
				return;

			if (state == true) {

				var w = $(window);

				loading.canvas.addClass('page-loading');
				/*loading.canvas.css({
					top: w.height() / 2 - 8,
					left: w.width() / 2 - 8
				});*/
				loading.moveTo(document.body);
			}
			else {
				loading.canvas.removeClass('page-loading');
				loading.stop();
			}
		},


		resize: function() {

			if (!loaded[current]) return;

			if (useBackground) {

				bsize = self.calculate(current);

				elems.body.css({
					'-webkit-background-size': bsize,
					'-moz-background-size': bsize,
					'-o-background-size': bsize,
					'background-size': bsize
				});
			}
			else {
				loaded[current].img.css(self.calculate(current));
			}
		},

		calculate: function(inx) {

			var i		= loaded[inx],
				win		= $(window),
				wsize	= {
					width:	win.width(),
					height:	win.height()
				},
				wratio	= wsize.width / wsize.height;

			if (useBackground) {

				if (wratio < i.ratio) {

					var perc	= (wsize[i.auto] * i.ratio * 100) / wsize[i.change],
						bsize 	= i.auto == 'height' ? perc + '% auto' : 'auto ' + perc + '%';
				}
				else {
					bsize 		= i.auto == 'height' ? '100% auto' : 'auto 100%';
				}

				return bsize;
			}
			else {

				var img 	= i.img,
					hr		= wsize.width / i.ratio,
					wr		= wsize.height * i.ratio,
					props	= {};

				if (wratio < i.ratio) {
					props.width		= wr;
					props.height	= '100%';
				} else {
					props.width		= '100%';
					props.height	= hr;
				}

				// unfortunately, we have to apply
				// width and height immediately.
				// otherwise we can't calculate position properly.
				// Hello mr. Heisenberg! :)
				img.css(props);

				props.left	= (wsize.width - img.width())/2;
				props.top	= (wsize.height - img.height())/2;

				return props;
			}
		},

		getNextIndex: function(direction) {
			var c 	= current;
			c += direction;
			if (!images[c]) {
				c	= direction == 1 ? 0 : images.length - 1;
			}
			return c;
		},

		next: function() {
			prev 	= current;
			while (prev == current) {
				current = Math.round( Math.random() * (images.length+1) );
			}
			self.set();
		},

		prev: function() {
			prev 	= current;
			current = self.getNextIndex(-1);
			self.set();
		},


		set: function() {

			if (!loaded[current]) {
				self.setLoading(true);
				self.preload(current, self.set);
				return;
			}

			self.setLoading(false);

			if (fadeSpeed) {
				dbody.css('background-color', '#666');

				//elems.mask.animate({opacity: .8}, fadeSpeed/2, 'linear', function(){
					dbody.css('background-color', '#000');
					self.actuallySet();
				//	elems.mask.animate({opacity: maxOpacity}, fadeSpeed/2);
				//});
			}
			else {
				dbody.css('background-color', '#000');
				self.actuallySet();
			}
		},

		actuallySet: function() {

			var url = images[current];


			if (useBackground) {

				var bsize = self.calculate(current);

				elems.body.css({
					'background-image': 'url('+url+')',
					'-webkit-background-size': bsize,
					'-moz-background-size': bsize,
					'-o-background-size': bsize,
					'background-size': bsize
				});
			}
			else {

				var i 	= loaded[current];

				elems.body.html('');

				i.img.css({
					visibility: 'hidden',
					left: 0,
					top: 0
				});

				if (ie) {


					// ie hell!!

					setTimeout(function(){
						i.img.appendTo(elems.body);
						i.img.css(self.calculate(current));
						i.img.css('visibility', '');
					}, 200);

				}
				else {
					i.img.appendTo(elems.body);
					i.img.css(self.calculate(current));
					i.img.css('visibility', '');
				}

			}

			self.resize();

			if (rotateSpeed && images.length > 1) {
				window.setTimeout(self.next, rotateSpeed);
			}

		},

		preload: function(inx, cb) {

			if (preloading[inx] || loaded[inx]) {
				if (cb) cb();
				return;
			}

			preloading[inx] = true;

			var img 	= $('<img>'),
				url		= images[inx];

			img.css({
				position: 	'absolute',
				left: 		'-10000px',
				top:		'-10000px',
				visibility:	'hidden'
			});

			img.bind('load', function(){

				var w	= img.width(),
					h	= img.height();

				loaded[inx] = {
					width: 		w,
					height: 	h,
					change:		w > h ? 'width' : 'height',
					auto:		w > h ? 'height' : 'width',
					ratio:		w > h ? w / h : h / w,
					img:		img
				};

				if (cb) cb();

				delete preloading[inx];

				//img.remove();
			});

			img.attr('src', url);
			img.appendTo('body');
		}

	});

	useBackground = self.detectFeature();
	self.init();

	return {
		// no public api here :)
	};
};
