$(function() {
	$('body').ClassBySize([
		{minWidth: 0, maxWidth: 951, className: 'without-fixed'}
	]);
	$('input[type=text][data-placeholder], textarea[data-placeholder]').Placeholder();

	// tabs
	var tabs = $('#games .tabs-content li.tab'),
		tabsHeaders = $('#games .tabs-headers li');
	tabsHeaders.click(function() {
		tabsHeaders.removeClass('g-current');
		tabs.removeClass('g-current');
		tabs.filter('#' + this.id + '-content').addClass('g-current');
		$(this).addClass('g-current');
	});

	// раскрытие информации по играм
	$('*[data-rel]').click(function() {
		var gameInfo = $('#' + $(this).data('rel'));
		gameInfo.parents('.games').css('z-index', 300);
		gameInfo.animate({top: 0},{duration: 1100, specialEasing: {top: 'easeOutBounce'}});
		gameInfo.find('.close').click(function handler() {
			var close = $(this);
			gameInfo.animate({top: -410},{duration: 500, complete: function() {
				gameInfo.parents('.games').css('z-index', 'auto');
				close.unbind('click', handler);
			}});
		});
	});

	// при переключении табов открытую игру - убираем
	closeLinks = $('#games .games .game .close');
	$('#games .tabs-headers li').click(function() {
		closeLinks.click();
	});

	function showMessage(message, error, onCloseHandler) {
		var messageWindow = $.Window.message('<p class="' + (error? 'error': 'success') + '-message">' + message + '</p>', {
			tplMain: '<div class="popup"><span class="window-close" title="Закрыть окно">&times;</span>{content}</div>',
			events: {close: onCloseHandler}
		});
		if (onCloseHandler instanceof Function) {
			messageWindow.bind('close', onCloseHandler);
		}
	}

	// Форма поддержки
	$('#support form').submit(function() {
		var $this = $(this);
		var submit = $this.find('button[type=submit]');

		if (submit.attr('disabled')) {
			return false;
		}

		submit.css('opacity', 0.5).attr('disabled', true);

		$.ajax({
			url: '/send-message.php',
			type: 'post',
			data: $this.serialize(),
			success: function(data) {
				var elements = $this.find('textarea,input');
				if (data.status == 'success') {
					elements.val('');
					showMessage(data.message || 'Successfully sent');
				} else if (data.field) {
					showMessage(data.message || 'Error', true, function(){
						elements.filter('*[name=' + data.field + ']').focus();
					});
				} else {
					showMessage(data.message || 'Error', true);
				}
				elements.blur();
			},
			error: function() {
				$this.find('textarea,input').blur();
				showMessage('Error', true);
			},
			complete: function() {
				submit.css('opacity', 1).attr('disabled', false);
			}
		});

		return false;
	});

	// Перетягиване каната
	function Cord(cord, config) {
		var self = this;

		this.config = $.extend({}, this.defaultConfig, config || {});

		this.cord = $(cord);
		if (!this.cord.size()) {
			return;
		}

		this.width = 0;
		this.cord.find(this.config.selectorPart).each(function() {
			self.width += $(this).width();
		});

		this.cordPosition	= this.cord.position().left;
		this._mouseX		= 0;
		this._mouseY		= 0;
		this._buttonFlag	= false;
		this._bodyWidth		= $(window).resize(function () {self._bodyWidth = $(this).width();}).width();

		this.cord.bind('mousedown touchstart', function(e) {
			self.cordPosition = self.cord.position().left;
			self.setButtonFlag(true);
			self.setMouseX(self.calcMouse(e, 'pageX'));
			self.setMouseY(self.calcMouse(e, 'pageY'));
		});

		$(document).bind('mouseup touchend', function(e) {
			if (self.getButtonFlag()) {
				self.setButtonFlag(false);

				if (self.cordPosition < (-self.width + self.config.padding + self.getBodyWidth())) {
					self.cord.animate({left: -self.width + self.config.padding + self.getBodyWidth()}, {duration: 500, specialEasing: {left: 'easeOutBounce'}});
				} else if (self.cordPosition > -self.config.padding) {
					self.cord.animate({left: -self.config.padding}, {duration: 500, specialEasing: {left: 'easeOutBounce'}});
				}
			}
		});
		$(document).bind('mousemove touchmove', function(e) {
			if (self.getButtonFlag()) {
				var pageX = self.calcMouse(e, 'pageX');
				self.cordPosition = Math.max(
					-self.width + self.config.padding - self.config.bounce + self.getBodyWidth(),
					Math.min(
						-self.config.padding + self.config.bounce,
						self.cordPosition + pageX - self.getMouseX()
					)
				);
				self.cord.css('left', self.cordPosition + 'px');

				if (Math.abs(self.calcMouse(e, 'pageY') - self.getMouseY()) <= 50 && pageX != self.getMouseX()) {
					e.preventDefault();
				}

				self.setMouseX(pageX);
			}
		});
	}
	Cord.prototype.defaultConfig = {
		padding: 1500,
		bounce: 750,
		selectorPart: '.part'
	};
	Cord.prototype.setButtonFlag = function(flag) {
		this._buttonFlag = !!flag;
	};
	Cord.prototype.getButtonFlag = function() {
		return this._buttonFlag || false;
	};
	Cord.prototype.setMouseX = function(mouseX) {
		this._mouseX = parseInt(mouseX) || 0;
	};
	Cord.prototype.getMouseX = function() {
		return this._mouseX || 0;
	};
	Cord.prototype.setMouseY = function(mouseY) {
		this._mouseY = parseInt(mouseY) || 0;
	};
	Cord.prototype.getMouseY = function() {
		return this._mouseY || 0;
	};
	Cord.prototype.calcMouse = function(e, property) {
		property = property || 'pageX';
		var value = e[property];
		// touchmove event and 1 finger is
		var touch = e.originalEvent.touches? e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]: false;
		if (touch) {
			value = touch[property];
		}
		return value;
	};
	Cord.prototype.getBodyWidth = function() {
		return this._bodyWidth || $(window).width();
	};

	var cord = new Cord($('#cord .wrapper'));

	// всплывающие окна
	$('#cord .part .content h3').Window({tplMain: '<div class="popup"><span class="window-close" title="Close popup">&times;</span>{content}</div>'});

	// основная навигация
	function moveTo(hash) {
		var linkData = hash.split('|', 2);
		var to = $(linkData[0]);
		if (to.size() > 0) {
			$('html,body').animate({scrollTop: to.position().top - 130}, 1000);
		}
		if (linkData[1]) {
			$('#' + linkData[1]).first().click();
		}
	}
	$('#header .nav-main li a.local, a.local[href^=#]').click(function(e) {
		moveTo($(this).attr('href').replace(/^.*?#/, '#'));
	});
	if (location.hash) {
		moveTo(location.hash);
	}

	// lightbox
	var links = $('.screenshots li a');
	if (links.size()) {
		links.lightBox({fixedNavigation: true});
	}
});

