$(function () {
	// remove layerX and layerY
	var all = $.event.props,
	len = all.length,
	res = [];
	while (len--) {
		var el = all[len];
		if (el != 'layerX' && el != 'layerY') res.push(el);
	}
	$.event.props = res;


	var jSnowContainer = $('#snow'),
		jSnow = $('.snow__layer'),
		jjSnow = $('.snow__left,.snow__right'),
	//Global
		aFriction = [0.15, 0.05, 0.55],
		aXOffset = [0.75, -0.25, 0.25],
		aYOffset = [0.75, 0.25, 0.25],
		aMXOffset = [0.015, 0.125, 0.575],
		aMYOffset = [0.015, 0.125, 0.575],
		aLayers = [],
		st = 0;
		
	jSnow.each(function (index) {
		aLayers[index] = new snowLayer({
			layer : this,
			left : '.snow__left',
			right : '.snow__right',
			friction : aFriction[index],
			xOffset : aXOffset[index],
			yOffset : aYOffset[index],
			xMouseOffset : aMXOffset[index],
			yMouseOffset : aMYOffset[index]
		});
	});
	
	var aLen = aLayers.length;
	
	function doScroll (isMM) {
		var bMM = isMM || false;
		
		if (!bMM){
			st = $(window).scrollTop();
		}

		for (var i = 0; i < aLen; i++) {
			aLayers[i].scroll(st);
		}
		
	};
	
	function snowHeight () {
		window.xSnowOffset = 0;
		window.ySnowOffset = 0;
		window.hh = $(window).height() / 2;
		window.wh = $(window).width() / 2;
		
		jSnowContainer.css({
			height : $('#layout').height() - 300}
		);
	};
	
	$measurer.bind(snowHeight);
	
	$(document).mousemove($.throttle(20, function(e){
		window.xSnowOffset = -e.pageX/2 || 0;
		window.ySnowOffset = -e.pageY/2 || 0;
		doScroll(true);
	}));
	
	$(document).bind('scroll', $.throttle(60, function (e) {
		doScroll(false);
	}));
	
	$(window).load(snowHeight);
});

var snowLayer = function (options) {
	
	this.jLayer = $(options.layer);
	this.jViews = this.jLayer.find(options.left).add(this.jLayer.find(options.right));
	
	this.friction = options.friction || 0;
	this.xOffset = options.xOffset || 0;
	this.yOffset = options.yOffset || 0;
	this.xMOffset = options.xMouseOffset || 0;
	this.yMOffset = options.yMouseOffset || 0;
	
	this.duration = ($.browser.msie && $.browser.version < 9) ? 0 : 50;
}

snowLayer.prototype = {
	scroll : function (offset) {
			var xOff = Math.ceil((offset/this.friction  + window.xSnowOffset * this.xMOffset) * this.xOffset) - 300,
				yOff = Math.ceil((-offset/this.friction + window.ySnowOffset * this.yMOffset) * this.yOffset) - 350;
			this.jViews.stop(true,true).animate({
				'backgroundPosition' : xOff + 'px ' + yOff + 'px'
				},{duration: this.duration, queue: false, easing : 'linear'});
	}
}
