var ajaxLoadTab = function() {}

$(function() {
	var ajax_handler;

	ajaxLoadTab = function(url, divId) {
		if (ajax_handler) try {ajax_handler.abort()} catch(err) {};
		var hash = '#tab_' + divId;
		if (window.location.hash.length <= 1 || divId == window.location.hash.substr(5, 4)) {
			var re = /p=([0-9]+)$/;
			var result = re.exec(url);
			if (result && result[1]) {
				if (result[1] != window.location.hash.substr(10)) {
					var offset_top = $('#tabs').offset().top - 20;
					if (offset_top < 0) offset_top = 0;
					$(window).scrollTop(offset_top);
				}
				hash += '_' + result[1];
			}
		}
		window.location.hash = hash;
		$('#' + divId).empty();
		var timer = window.setTimeout(function() {$('#' + divId).html('<img src="/images/ajax-loader.gif" alt="Загрузка…" width="16" height="16" style="display: block; margin: 0px auto 15px auto" \/>')}, 100);
		ajax_handler = $.ajax({
			url: url,
			dataType: 'html',
			success: function(html){
				window.clearTimeout(timer);
				$('#' + divId).html(html);
			}
		});
	};

	$('#tabs a').live('click', function() {
		$obj = $(this);
		$rel = $obj.attr('rel');
		$li = $obj.parents('li');
		$act = $obj.parents('ul').find('li.act');
		$cont = $('#tabs-cont .act');
		var id = $cont.attr('id'); //tab id
		var url = $obj.attr('href'); //url for ajax query
		if ($rel == window.location.hash.substr(5, 4)) {
			var re = /^#tab_id_[0-9]+_([0-9]+)$/;
			var result = re.exec(window.location.hash);
			if (result && result[1]) {
				url += '&p=' + result[1];
			}
		}
		$act.removeClass('act').html('<span><a href="' + $('a', $act).attr('href') + '" rel="' + $cont.attr('id') + '">' + $act.text() + '</a></span>');
		$cont.removeClass('act').addClass('hide');
		$li.addClass('act').html('<span><span><b>' + $obj.text() + '</b></span></span><q class="l"></q><q class="r"></q><a href="' + url + '"></a>');
		$('#' + $rel).removeClass('hide').addClass('act');
		ajaxLoadTab(url, $rel);
		return false;
	});

	if (window.location.hash.indexOf('tab_id_') == 1) {
		var count = 0;
		$('#tabs a[rel=\'' + window.location.hash.substr(5, 4) + '\']').each(function() {
			$(this).click();
			count++;
		});
		if (count == 0) {
			var url = $('#tabs li:first a').attr('href');
			if (url.length) {
				var re = /^#tab_id_[0-9]+_([0-9]+)$/;
				var result = re.exec(window.location.hash);
				if (result && result[1]) {
					url += '&p=' + result[1];
				}
				ajaxLoadTab(url, 'id_1');
			}
		}
	}

	/* *** */
	/* Для любимого шестого Осла */
	$('input[type=radio]').addClass('radio');
	$('input[type=checkbox]').addClass('checkbox');
	/* *** */
	/*Блок с ответами для голосования*/
	$('#ans').click(function(){
		$('#res').toggleClass('hide');
		return false;
	});
	/* *** */
	/* Карусель */
	var $boxs = $('div.box');
	var $inbox = $('#in-box');
	$('#in-box').css({width:($boxs.length*530)+'px'});
	$boxs.each(function(n){
		$(this).attr('index',n);
	});
	$('#left').click(function(){
		var $this = $(this);
		var $obj = $('div.box.act-box').removeClass('act-box');
		var $n = parseInt($obj.attr('index'));
		$prev = $n - 1;
		if($prev < 0) $prev = $boxs.length - 1;
		$prev = $('div.box.hide-box[index='+$prev+']');
		$prev.css('marginLeft', '0');
		// $inbox.prepend($prev.css({opacity: 'hide', left: -530, marginRight: -530}).clone().animate({left: 0, opacity: 'show'}, 400, 'easeOutQuad', function() {$(this).css({marginRight: '', left: ''}).removeClass('hide-box').addClass('act-box')}));
		$inbox.prepend($prev.css({left: -530, marginRight: -530}).clone().animate({left: 0}, 400, 'easeOutQuad', function() {$(this).css({marginRight: '', left: ''}).removeClass('hide-box').addClass('act-box')}));
		$prev.remove();
		$obj.css({right: 0}).animate({right: -530}, 400, 'easeOutQuad', function() {$(this).addClass('hide-box').css({right: ''});});
		return false;
	});
	$('#right').click(function(){
		var $obj = $('div.box.act-box').removeClass('act-box');
		var $n = parseInt($obj.attr('index'));
		$next = $n + 1;
		if($next == $boxs.length)$next = 0;
		$next = $('div.box.hide-box[index='+$next+']');
		$next.css('marginLeft', 0)
		$obj.animate({marginLeft: -530}, 400, 'easeOutQuad', function() {var $elem = $(this); $('#in-box').append($elem.prev('.box')).append($elem.addClass('hide-box').css({marginLeft: ''}).clone()); $elem.remove()});
		$next.animate({marginLeft: 0}, 400, 'easeOutQuad', function() {$(this).removeClass('hide-box').addClass('act-box')});
		return false;
	});

	$('#lefttour').click(function(){
		var $this = $(this);
		var $obj = $('div.box.act-box').removeClass('act-box');
		var $n = parseInt($obj.attr('index'));
		$prev = $n - 1;
		if($prev < 0) $prev = $boxs.length - 1;
		$prev = $('div.box.hide-box[index='+$prev+']');
		$prev.css('marginLeft', '0');
		// $inbox.prepend($prev.css({opacity: 'hide', left: -530, marginRight: -530}).clone().animate({left: 0, opacity: 'show'}, 400, 'easeOutQuad', function() {$(this).css({marginRight: '', left: ''}).removeClass('hide-box').addClass('act-box')}));
		$inbox.prepend($prev.css({left: -687, marginRight: -687}).clone().animate({left: 0}, 400, 'easeOutQuad', function() {$(this).css({marginRight: '', left: ''}).removeClass('hide-box').addClass('act-box')}));
		$prev.remove();
		$obj.css({right: 0}).animate({right: -687}, 400, 'easeOutQuad', function() {$(this).addClass('hide-box').css({right: ''});});
		return false;
	});
	$('#righttour').click(function(){
		var $obj = $('div.box.act-box').removeClass('act-box');
		var $n = parseInt($obj.attr('index'));
		$next = $n + 1;
		if($next == $boxs.length)$next = 0;
		$next = $('div.box.hide-box[index='+$next+']');
		$next.css('marginLeft', 0)
		$obj.animate({marginLeft: -687}, 400, 'easeOutQuad', function() {var $elem = $(this); $('#in-box').append($elem.prev('.box')).append($elem.addClass('hide-box').css({marginLeft: ''}).clone()); $elem.remove()});
		$next.animate({marginLeft: 0}, 400, 'easeOutQuad', function() {$(this).removeClass('hide-box').addClass('act-box')});
		return false;
	});

	//Login popup
	$('#enter').click(function(){
		$('#popupLogin').toggleClass('act-popup');
		if ($('#popupLogin').is(':visible')) {
			$('#loginInput').each(function() {
				if (!this.value.length || this.value == this.defaultValue) {
					this.focus();
					this.select();
				} else {
					$('#passwordFake').each(function() {
						this.style.display = 'none';
					});
					$('#passwordInput').each(function() {
						this.style.display = '';
						this.focus();
						this.select();
					});
				}
			});
		}
		return false;
	});
	//Logout query
	$('#exit').click(function(){
		$.ajax({
			type: "POST",
			url: "/user/logout",
			success: function( data ){
				var _str = window.location.href;
				var url = '';
				if( _str.substr(-8, 8) == '#comment' ){
					url = _str.substr(0, _str.length - 8);
				} else {
					url = window.location.href;
				}
				window.location.href = url;
			},
			error: function(){
				alert( 'Ошибка во время обработки данных!' );
			}
		});
		return false;
	});
	//Login query
	$('#loginForm').submit(function(){
		$.ajax({
			type: "POST",
			url: "/user/login",
			dataType: 'json',
			data: {login: $('#loginInput').val(), password: $('#passwordInput').val()},
			success: function( data ){
				if( data.result ){
					$('#popup').toggleClass('act-popup');
					window.location.reload();
				} else {
					if( data.error ){
						alert( data.error );
					} else {
						alert( 'Ошибка во время обработки данных!' );
						$('#popup').toggleClass('act-popup');
					}
				}
			},
			error: function(){
				alert( 'Ошибка во время обработки данных!' );
				$('#popup').toggleClass('act-popup');
			}
		});
		return false;
	});
});
