// показываем/скрываем контент
function showHiddenContent( id )
{
	if ( $('#' + id).is(':hidden') )
	{
		$('#' + id).slideDown('slow');
	}
	else
	{
		$('#' + id).slideUp('slow');
	}
	return 0;
}

// показываем/скрываем кнопку [ ответить ] на комментарий
function showHideButtons( id, show )
{
	if ( show === 'true' )
	{
		$('#HiddenLink' + id).css('visibility', 'visible');
	}
	else
	{
		$('#HiddenLink' + id).css('visibility', 'hidden');
	}
}

// перенаправление на index после того, как показали сообщение
function newLocation( Page )
{
	window.location.href = '/' + Page;
	return 0;
}

// таймер с обратным отчётом перенаправления
function refreshTime(sec)
{
	if ( sec > 0 )
	{
		sec--;
	}
	$('#Seconds').html(sec);
	setTimeout('refreshTime(' + sec + ')', 1000);
	return 0;
}

// показываем все новости
function showAllNews()
{
	$('#NewsSpinner').css('display', 'inline');
	$.ajax({
		url: '/ajax/news.php',
		success: function( Message )
		{
			$('#News').html(Message);
			$('#NewsSpinner').css('display', 'none');
		},
		error: function()
		{
			$('#News').html('Произошла ошибка отправки данных');
			$('#NewsSpinner').css('display', 'none');
		}
	});
	return 0;
}

// показываем человечка
function showPerson( Person )
{
	$('#PersonSpinner').css('display', 'inline');
	$.ajax({
		type: 'POST',
		url: '/ajax/band.php',
		data: { name: Person },
		success: function( Message )
		{
			$('#PersonSpinner').css('display', 'none');
			$('#Person').html(Message);
			$('.NameListActiveItem').removeClass('NameListActiveItem');
			$('#' + Person).addClass('NameListActiveItem');
		},
		error: function()
		{
			$('#PersonSpinner').css('display', 'none');
			$('#Person').html('Произошла ошибка отправки данных');
		}
	});
	return 0;
}



// показываем капчу
function showCaptcha( id )
{
	// показываем затемнённую подложку
	TransparentDIV = document.createElement('DIV');
	TransparentDIV.className = 'BlackBack';
	$('body').append(TransparentDIV);
	$('.BlackBack').fadeTo(0, 0.4);
	$('#CaptchaWindow').fadeIn('slow');

	$('#CaptchaToNote').val(id);
	$('#CaptchaValue').val('').focus();
	return 0;
}

// обработка кнопки [ Отмена ] на окне капчи
function cancelCaptcha()
{
	$('#CaptchaValue').val('');
	$('#CaptchaWindow').fadeOut('fast');
	$('.BlackBack').remove();
	return 0;
}

// обновляем картинку на captcha
function reloadCaptcha( SetFocus )
{
	var img = document.getElementById('CaptchaIMG');
	img.src = img.src + '&' + Math.random();
	if ( SetFocus )
	{
		document.getElementById('CaptchaValue').focus();
	}
	return 0;
}

// при нажатии на кнопку при вводе текста капчи
function captchaKeyPress( event )
{
	if ( event.keyCode === 13 ) // enter
	{
		addComment( $('#CaptchaToNote').val() );
	}
	if ( event.keyCode === 27 ) // escape
	{
		cancelCaptcha();
	}
	return 0;
}



// ответить на комментарий
function replyComment( NoteId, ReplyId, ReplyName )
{
	var form = document.getElementById('AddComment' + NoteId );
	form.ToId.value = ReplyId;
	form.Name.focus();
	$('#TitleAnswer' + NoteId).html('Ответить ' + ReplyName);
	$('#CancelAnswer' + NoteId).css('display', 'inline');
	return 0;
}

// отменить ответ на комментарий
function unReplyComment( NoteId )
{
	var Answer = 'Ответить';
	if ( NoteId == 0 )
	{
		Answer = 'Написать сообщение';
	}
	$('#TitleAnswer' + NoteId).html( Answer );
	$('#CancelAnswer' + NoteId).css('display', 'none');
	document.forms['AddComment' + NoteId ].ToId.value = '0';
	return 0;
}

// отправляем комментарий
function addComment( id )
{
	var div = document.getElementById('OnlyComments' + id);

	// собираем данные с формы
	var jCaptcha = document.getElementById('CaptchaValue').value;
	var form = document.getElementById('AddComment' + id);
	var jToId = form.ToId.value;
	var jName = form.Name.value;
	var jEmail = form.Email.value;
	var jBody = form.Body.value;

	if ( jName === '' ||  jName === 'Имя' )
	{
		alert('Введите имя');
		form.Name.focus();
		return 1;
	}
	if ( jBody === '' ||  jBody === 'Сообщение' )
	{
		alert('Введите сообщение');
		form.Body.focus();
		return 1;
	}

	// показываем спиннер
	$('#Spinner' + id).css('display', 'inline');

	// отправляем эти данные на страницу через AJAX
	$.ajax({
		type: 'POST',
		url: '/query/comments.php',
		data:{
				'AddComment': 'true',
				'ToNote': id,
				'ToId': jToId,
				'Name': jName,
				'Email': jEmail,
				'Body': jBody,
				'Captcha': jCaptcha
			},
		success: function( Message ) {
			// скрываем спиннер
			$('#Spinner' + id).css('display', 'none');
			if ( Message === 'showCaptcha' )
			{
				showCaptcha(id);
				return 0;
			}
			$('#CaptchaValue').val('');
			div.innerHTML = Message;
			// если это сообщение о том, что комментарий добавлен
			if ( Message.indexOf( 'GoodBox' ) >= 0 )
			{
				// значит форму надо очистить
				form.reset();
				// убираем следы 'ответить'
				unReplyComment( id );
				// делаем обратно инпуты серенького цвета и снимаем с них фокус
				$('#AddComment' + id + ' input').
				add('#AddComment' + id + ' textarea').
				not('input[type="button"]').
				css('color', '#808080').blur();
			}
			if ( $('.GoodBox').size() > 0 )
			{
				$('.GoodBox').fadeTo(5000, 0.01);
				$('.GoodBox').slideUp('slow');
			}
			if ( $('.ErrorBox').size() > 0 )
			{
				$('.ErrorBox').fadeTo(5000, 0.01);
				$('.ErrorBox').slideUp('slow');
			}
			reloadCaptcha(0);
			return 0;
		},
		error: function() {
			$('#Spinner' + id).css('display', 'none');
			div.innerHTML = 'Произошла ошибка отправки данных';
			reloadCaptcha(0);
			return 0;
		}
	});
	// закрываем окно капчи
	cancelCaptcha();
	return 0;
}

// счётчик оставшихся символов для поля комментайрия
function textCounter( event, id )
{
	if ( ( (event.keyCode === 13) || (event.keyCode === 10) ) && (event.ctrlKey === true) ) // ctrl + enter
	{
		addComment(id);
		return 0;
	}

	var Limit = 1024;
	var Field = document.getElementById('AddCommentBody' + id);
	if ( Field.value.length > Limit )
	{
		Field.value = Field.value.substring( 0, Limit );
	}
	else
	{
		var count = Limit - Field.value.length;
		if ( count < 51 )
		{
			$('#Counter' + id).css('display', 'block');
		}
		else
		{
			$('#Counter' + id).css('display', 'none');
		}
		$('#Counter' + id).html('Осталось символов: ' + count);
	}
	return 0;
}



// очистка стандартных надписей на INPUT
function clearInput( Link, DefaultText )
{
	if ( Link.value === DefaultText )
	{
		Link.value = '';
		Link.style.color = '#000000';
	}
	return 0;
}

// вставка стандартных надписей на INPUT
function setInput( Link, DefaultText )
{
	if ( Link.value === '' )
	{
		Link.value = DefaultText;
		Link.style.color = '#808080';
	}
	return 0;
}



// поделиться ссылкой на прессу
function getPress()
{
	var form = document.getElementById('GetPress');
	$.ajax({
		type: 'POST',
		url: '/query/press.php',
		data:
		{
			'GetPress': 'true',
			'Link': form.GetPress.value
		},
		success: function( Message )
		{
			if ( Message === 'true' )
			{
				alert('Спасибо за информацию!');
				showHiddenContent('GetPress');
				form.reset();
			}
			else
			{
				alert('Произошла ошибка отправки данных');
			}
		},
		error: function()
		{
			alert('Произошла ошибка отправки данных');
		}
	});
	return 0;
}



//
function subscribe()
{
	$.ajax({
		type: 'POST',
		url: '/query/news.php',
		data:
		{
			'Subscribe': 'true',
			'Email': $('#Subscribe').val()
		},
		success: function( Message )
		{
			if ( Message === 'wrong' )
			{
				alert('Неправильный формат e-mail адреса');
			}
			else if ( Message === 'error' )
			{
				alert('Произошла ошибка сохранения данных');
			}
			else
			{
				alert(Message);
				showHiddenContent('SubscribeDiv');
			}
		},
		error: function()
		{
			alert('Произошла ошибка отправки данных');
		}
	});
}



// создать Fancybox
function createFancybox()
{
	$("a.gallery").fancybox	({
		'type': 'image',
		'titlePosition': 'inside',
		'transitionOut': 'fade',
		'transitionIn': 'fade',
		'overlayColor': '#333',
		'enableEscapeButton': true,
		'modal': false,
		'titleFormat': function (title, currentArray, currentIndex)
		{
			return "<div>" +
			"<div style='float: left;'>" + (currentIndex + 1) + ' / ' + currentArray.length + "</div>" +
			(title && title.length ? '<strong>' + title + '</strong>' : '&nbsp;' ) + "</div>";
		}
	});
}

