var decoLineHeight = 20;
var randThres = 1;
var upSpeed = 1000;
var downSpeed = -1500;
var gapPauseCounter = 100;
var workHeight;
var collection;
var backgroundMotion = true;
var currentDensity = 64;
var minDensity = 128;

function createLine() {
	if (Math.random() < randThres && backgroundMotion) {
		if (collection.length < workHeight / currentDensity && gapPauseCounter > 32) {
			gapPauseCounter = 0;
			randThres = 0.2;
			var line = $('<div class="decoline ' + ((Math.random() > 0.5)
				? 'browndeco' : 'whitedeco') + '"></div>');
			var pos = workHeight;
			line.css('top', pos + 'px');
			line.each(function() {
				this.speed = upSpeed + Math.round(Math.random() * 2 - 1) * 333;
				this.curTop = pos;
			});
			collection = collection.add(line);
//			line.fadeTo(1, 0);
			line.appendTo('body');
//			line.fadeTo(1000, 0.4);
		}
	}
	else
		randThres += 0.1;
	
	setTimeout('createLine()', 2000);
	if (currentDensity < minDensity)
		currentDensity += 0.5;
}

function linesMove() {
	if (backgroundMotion) {
		gapPauseCounter += upSpeed / 500;
		collection.each(function(index) {
			this.curTop -= this.speed / 500;
			if (this.curTop < 0) {
				var prSpeed = this.speed;
				collection.each(function() {
					if (this.speed == 0 && this.curTop == 0) {
						this.speed = - prSpeed * 1.5;
					}
				});
				this.curTop = 0;
				this.speed = 0;
			}
			if (this.curTop > workHeight) {
				this.curTop = workHeight;
				this.speed = 0;
//				$(this).fadeTo(500, 0, function() {
					$(this).remove();
//				});
				collection.splice(index, 1);
			}

			$(this).css('top', Math.round(this.curTop) + 'px');
		});
	}
	setTimeout('linesMove()', 100);
}

$(document).ready(function() {

	var fixedSupported = !($.browser.msie && $.browser.version < 7);
//	$('body').append('<div id="checkfixedsupport" style="position: fixed; display: none;"></div>');
//	if ($('#checkfixedsupport').css('position') != 'fixed')
//		fixedSupported = false;
//	$('#checkfixedsupport').remove();

	if ($(window).width() > 1024 + 64 && fixedSupported) {

		workHeight = Math.min($(window).height(), $(document).height() - decoLineHeight);

		$(window).resize(function() {
			workHeight = Math.min($(window).height(), $(document).height() - decoLineHeight);
		});

		collection = $('body .decoline');

		// start creating
		createLine();

		// start motion
		linesMove();
	}
});

