$(function() {
	// Коррдинаты центра изображения
	var fonCenterCoord = { x:970, y: 622};

	// Позиция мыши от центра экрана
	var mousePosition = {
		x: { px: null, percents: null },
		y: { px: null, percents: null }
	}

	var lockX = false;

	var container = $('#container');
	var fon = container.children('.fon');
	var center = fon.children('.center');

	var continerWidth = container.width();
	var continerHeight = container.height();

	var fonWidth = fon.width();
	var fonHeight = fon.height();

	var centerClassLast = null;
	var centerClassPrefix = 'logo-';

	var height, width, shiftCenterY, shiftCenterX;


	fon.css('left',  -1 *  fonCenterCoord.x + container.width() / 2);
	fon.css('top',  -1 * fonCenterCoord.y  + container.height() / 2);

	if (fon.width() + (fon.width() / 2 - Math.abs(fonCenterCoord.x)) < container.width()) {
		lockX = true;
	}

	center.mouseover(function(){
		var rand = 0;
		
		if(this.last === undefined){
			rand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
		}else{
			rand = this.last;
			
			while(this.last == rand){
				rand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
			}
		}
		this.last = rand;
		
		centerClassLast = centerClassPrefix + rand;
		
		$(this).addClass(centerClassLast);
	}).mouseout(function() {
		if (centerClassLast) {
			$(this).removeClass(centerClassLast);
		}
	});

	var i = 0;
	container.mousemove(function(e) {
		if (i != 2) {
			i++;
			return;
		} else {
			i = 0;
		}

		if (!lockX) {
			mousePosition.x.px = e.pageX - continerWidth / 2;
			mousePosition.x.percents = 2 * (mousePosition.x.px * 100) / continerWidth;

			if (mousePosition.x.px > 0) {
				width = fonWidth - fonCenterCoord.x;
			} else {
				width = fonCenterCoord.x;
			}

			shiftCenterX = (width * mousePosition.x.percents) / 100;
			var shiftX = -(fonCenterCoord.x + shiftCenterX) + e.pageX;

		}

		mousePosition.y.px = e.pageY - continerHeight / 2;
		mousePosition.y.percents = 2 * (mousePosition.y.px * 100) / continerHeight;


		if (mousePosition.y.px > 0) {
			height = fonHeight - fonCenterCoord.y;
		} else {
			height = fonCenterCoord.y;
		}

		shiftCenterY = (height * mousePosition.y.percents) / 100;
		var shiftY = -(fonCenterCoord.y + shiftCenterY) + e.pageY;

		var coords = {};

		if(shiftY) {
			coords.top = shiftY;
		}

		if(shiftX && !lockX) {
			coords.left = shiftX;
		}

		//fon.css(coords);
		fon.stop().animate(coords, { duration: 5000, easing: 'easeOutCirc' });

	});


	$(window).resize(function() {
		continerWidth = container.width();
		continerHeight = container.height();

		fonWidth = fon.width();
		fonHeight = fon.height();

		if (fon.width() - (Math.abs(fon.width() / 2 - fonCenterCoord.x) * 2) < container.width()) {
			lockX = true;
		} else {
			lockX = false;
		}

		fon.css('left',  -1 *  fonCenterCoord.x + container.width() / 2);
		fon.css('top',  -1 * fonCenterCoord.y  + container.height() / 2);
	});
});
