function formTextClick(id, defaultText)
{
	var t = $(id);
	if (t.value == defaultText)
		t.select();
};

// Работа с записью
var post =
{
	// Количество добавленных абзацев
	addParagraphsCount: 0,
	
	// Кнопка добавления
	addButton: null,
	
	// Контейнер дополнительных кнопок добавления
	addVariations: null,

	// Контейнер параграфов
	addParagraphs: null,

	// Обработчики событий
	addButtonClickHandler: function()
	{
		// Отображение подменю вариантов абзацев
		post.addVariations.style.display='block';
		post.addButton.style.display='none';
	},
	
	// Добавление абзаца
	addParagraph: function(type, value, id, cut, hidden)
	{
		// Скрытие подменю вариантов абзацев
		post.addVariations.style.display='none';
		post.addButton.style.display='inline';

		// Добавление контейнера абзаца
		var container = new Element('div', { 'class': 'postAddParagraph' });
		post.addParagraphs.grab(container);

		// Добавление специфических элементов для указанного типа
		switch(type)
		{
			// Текстовое поле
			case 'text':
				container.grab(new Element('textarea',{
					id: 'field' + post.addParagraphsCount,
					name: 'field[' + post.addParagraphsCount + ']',
					value: value || '',
					style: 'width: 600px;height:200px;'
				}));
				tinyMCE.init({
					auto_focus: 'field' + post.addParagraphsCount,
					elements: 'field' + post.addParagraphsCount,
					mode: 'exact',
					theme : (currentUser.status == "admin" ? "advanced" : "simple"),
					convert_urls : false
				});

				break;
			
			// Ролик с ютуба
			case 'youtube':
				container.appendText('Ролик YouTube: ');
				container.grab(new Element('input',{
					id: 'field' + post.addParagraphsCount,
					name: 'field[' + post.addParagraphsCount + ']',
					value: value || 'Адрес YouTube-ролика',
					style: 'width: 200px;',
					onclick: 'formTextClick(this.id, "Адрес YouTube-ролика")'
				}));
				break;
			
			// Ролик с google video
			case 'googlevideo':
				container.appendText('Ролик Google Video: ');
				container.grab(new Element('input',{
					id: 'field' + post.addParagraphsCount,
					name: 'field[' + post.addParagraphsCount + ']',
					value: value || 'Адрес ролика',
					style: 'width: 200px;',
					onclick: 'formTextClick(this.id, "Адрес ролика")'
				}));
				break;
			
			// Рисунок
			case 'image':
				container.innerHTML = 
					'<img src="/images/icons/ajax-loader.gif" alt="" id="imgLoader'+post.addParagraphsCount+'" style="display:none" />'+
					'<div id="imgWrapper'+post.addParagraphsCount+'">'+
						'<img src="'+(value ? '/images/uploaded/' + value + 'm.jpg' : '')+'" alt="" id="img'+post.addParagraphsCount+'" /><br />'+
						'<input id="fieldFile'+post.addParagraphsCount+'" name="field1['+post.addParagraphsCount+']" type="file" />'+
						' или из интернета: '+
						'<input id="fieldUrl'+post.addParagraphsCount+'" name="field2['+post.addParagraphsCount+']" value="" style="width:200px;" />'+
						'<input id="fieldValue'+post.addParagraphsCount+'" name="field['+post.addParagraphsCount+']" type="hidden" value="'+(value || '')+'" style="width:200px;" />'+
					'</div>';

				if (!value) $('img'+post.addParagraphsCount).fade('hide');

				// Аплоуд
				NS.ImageUpload.init({
					input: 'fieldFile'+post.addParagraphsCount,
					action: '/ajax/image/upload',
					onStart: sj.post.form.image.upload.bind(sj, post.addParagraphsCount),
					onFinish: function(res, id) {
						res.id = id;
						sj.post.form.image.onSuccessHandler(res);
					}.bindWithEvent(sj, post.addParagraphsCount)
				});

				// Загрузка из сети
				$('fieldUrl'+post.addParagraphsCount)
					.addEvent('change', function(e) {
						var id = e.target.id.substr(8);
						sj.post.form.image.upload(id, e.target.value);
					}).addEvent('click', function() {
						this.select();
					});

				break;
			
			// Игрушка
			case 'game':
				container.innerHTML =
					'<img src="/images/icons/ajax-loader.gif" alt="" id="gameLoader'+post.addParagraphsCount+'" style="display:none" />'+
					'<div id="gameWrapper'+post.addParagraphsCount+'">'+
						'<div id="game'+post.addParagraphsCount+'"></div><br />'+
						'<input id="fieldFile'+post.addParagraphsCount+'" name="field1['+post.addParagraphsCount+']" type="file" />'+
						'<input id="fieldValue'+post.addParagraphsCount+'" name="field['+post.addParagraphsCount+']" type="hidden" value="'+(value || '')+'" />'+
					'</div>';
				
				if (!value)
					$('game'+post.addParagraphsCount).fade('hide');
				else
					sj.post.form.game.setValue(post.addParagraphsCount, value);

				// Аплоуд
				NS.ImageUpload.init({
					input: 'fieldFile'+post.addParagraphsCount,
					action: '/ajax/swf/upload',
					onStart: sj.post.form.game.upload.bind(sj, post.addParagraphsCount),
					onFinish: function(res, id) {
						res.id = id;
						sj.post.form.game.onSuccessHandler(res);
					}.bindWithEvent(sj, post.addParagraphsCount)
				});

				break;
			
			// Игрушка в айфрейме
			case 'iframe':
				container.innerHTML =
					'<input id="field'+post.addParagraphsCount+'" name="field['+post.addParagraphsCount+']" value="'+(value || '')+'" />';
				break;
		}

		// Добавление скрытого поля с типом абзаца
		container.grab(post.getHidden('fieldType', type));

		// Добавление скрытого поля с идентификатором
		if (id) container.grab(post.getHidden('fieldID', id));

		// Добавление панели управления абзацем
		container.grab(post.getParagraphPanel(cut, hidden));

		post.addParagraphsCount++;
	},
	
	// Формирование скрытого поля
	getHidden: function(name, value)
	{
		return new Element('input',{
			id: name + post.addParagraphsCount,
			name: name + '[' + post.addParagraphsCount + ']',
			type: 'hidden',
			value: value
		});
	},
	
	// Формирование панели управления абзацем
	getParagraphPanel: function(cut, hidden)
	{
		var el = new Element('div', { 'class': 'panel' });

		el.grab(new Element('input', { type: 'hidden', name: 'fieldCut[' + post.addParagraphsCount + ']', value: '0' }));
		el.grab(cut
			? new Element('input', { type: 'checkbox', name: 'fieldCut[' + post.addParagraphsCount + ']', id: 'fieldCut' + post.addParagraphsCount, value: '1', checked: 'checked' })
			: new Element('input', { type: 'checkbox', name: 'fieldCut[' + post.addParagraphsCount + ']', id: 'fieldCut' + post.addParagraphsCount, value: '1' }));
		el.grab(new Element('label',{
			'for': 'fieldCut' + post.addParagraphsCount
		}).appendText('Под кат'));
		
		el.grab(new Element('input', { type: 'hidden', name: 'fieldHidden[' + post.addParagraphsCount + ']', value: '0' }));
		el.grab(hidden
			? new Element('input', { type: 'checkbox', name: 'fieldHidden[' + post.addParagraphsCount + ']', id: 'fieldHidden' + post.addParagraphsCount, checked: 'checked' })
			: new Element('input', { type: 'checkbox', name: 'fieldHidden[' + post.addParagraphsCount + ']', id: 'fieldHidden' + post.addParagraphsCount }));

		el.grab(new Element('label',
		{
			'for': 'fieldHidden' + post.addParagraphsCount
		}).appendText('Скрытый от гостей'));

		return el;
	},
	
	// Инициализация
	init: function()
	{
		// Инициализация элементов управления
		post.addButton = $('postAdd')
		post.addButton.addEvent('click', post.addButtonClickHandler);
		post.addVariations = $('postAddVariations');
		post.addParagraphs = $('postAdditions');

		// text
		post.addVariationButton('text', 'text', 'Добавить текст');

		// youtube
		post.addVariationButton('youtube', 'icon icFilm', 'Добавить ролик YouTube');

		// google video
		post.addVariationButton('googlevideo', 'icon icFilm', 'Добавить ролик Google Video');

		// image
		post.addVariationButton('image', 'icon icImage', 'Добавить изображение');

		// game
		post.addVariationButton('game', 'icon icApplication', 'Добавить игрушку');

		// iframe
		post.addVariationButton('iframe', 'icon icApplication', 'Добавить игрушку (iframe)');
	},
	
	addVariationButton: function(type, cssClass, value)
	{
		var el = new Element('span', { 'class': cssClass });
		el.appendText(value);
		el.addEvent('click', function()
		{
			post.addParagraph(type);
		});
		post.addVariations.grab(el);
	}
};

// Отображение изменения очков
var pts = 
{
	// Контейнер, внутри которого будет отображаться число
	container: null,

	// Положение курсора
	cursorX: null,
	cursorY: null,

	// Инициализация
	init: function()
	{
		pts.container = new Element('div',
		{
			id: 'ptsContainer',
			style: 'width:100px;height:30px;position:absolute;top:0;left:0;overflow:hidden;z-index:0;color:#00dc00;display:block;'
		});

		//pts.container.appendText('test');

		//$($(document.body).getElement('div')).grab(pts.containter);
	},

	// Обработчик движения мыши для получения координат курсора
	mouseOverHandler: function(event)
	{
		pts.cursorX = event.page.x;
		pts.cursorY = event.page.y;
	},
	
	// Экшн!
	action: function(points)
	{
		$(document.body).getElement('div').grab(pts.containter);

		//pts.container.appendText('+' + points);
		//pts.container.style.top = pts.cursorY + 'px';
		//pts.container.style.left = pts.cursorX + 'px';

		//pts.container.style.display = 'block';

		//console.log(pts);
	}
};

// Обновление цитаты
var citation =
{
	// Содержимое
	elContent: null,
	
	// Автор
	elAuthor: null,
	
	// Значок обновления
	elRefresh: null,

	// Индикатор загрузки
	elLoader: null,

	// Инициализация
	init: function()
	{
		// Назначение событий
		var c = $('citation');
		c.addEvent('click', citation.refresh);
		c.addEvent('mouseover', citation.onMouseOverHandler);
		c.addEvent('mouseout', citation.onMouseOutHandler);
		
		// Загрузка нужных элементов
		citation.elContent = $$('#citation .content')[0];
		citation.elAuthor = $$('#citation .copyright')[0];
		citation.elRefresh = $$('#citation .refresh')[0];
		citation.elLoader = $$('#citation .loader')[0];
		
		// Скрытие элементов
		citation.elRefresh.fade('hide');
		citation.elLoader.fade('hide');
	},

	// Загрузка новой цитаты
	refresh: function()
	{
		// Скрытие ненужных слоев
		citation.elContent.fade('out');
		citation.elAuthor.fade('out');
		citation.elRefresh.fade('out');

		// Индикатор загрузки
		citation.elLoader.fade('in');

		// Запрос
		var request = new Request.JSON({
			url: '/ajax/citations',
			onSuccess: citation.onSuccessHandler
		});

		request.send();
	},

	// Обработчик события при загрузке цитаты
	onSuccessHandler: function(response)
	{
		// Отображение данных
		citation.elContent.innerHTML = response.content;
		citation.elAuthor.innerHTML = response.author;

		// Отображение блоков
		citation.elContent.fade('in');
		citation.elAuthor.fade('in');
		citation.elRefresh.fade('in');

		// Скрытие индикатора загрузки
		citation.elLoader.fade('out');
	},
	
	// Обработчик события мыши
	onMouseOverHandler: function()
	{
		citation.elRefresh.fade('in');
	},

	// Обработчик события мыши
	onMouseOutHandler: function()
	{
		citation.elRefresh.fade('out');
	}
};

var sj = {

	// Сообщение об ошибке
	error: {

		// Элемент-контейнер
		elContainer: null,
		
		// Кнопка закрытия
		elClose: null,
		
		// Контент
		elContent: null,
		
		// Инициализация
		init: function()
		{
			// Загрузка элементов
			sj.error.elContainer = $('error');
			sj.error.elClose = $$('#error .close')[0];
			sj.error.elContent = $$('#error .content')[0];

			sj.error.elContainer.fade('hide');

			// Назначение событий
			sj.error.elClose.addEvent('click', sj.error.close);

			// Возможность перетаскивания
			var d = new Drag(sj.error.elContainer, {
				snap: 0,
				onSnap: function(el){
					sj.error.elContainer.fade(0.5);
					sj.error.elContainer.style.cursor = 'move';
				},
				onComplete: function(el){
					sj.error.elContainer.fade('in');
					sj.error.elContainer.style.cursor = 'default';
				}
			});
		},

		// Открытие окна
		open: function(text, x, y)
		{
			with(sj.error)
			{
				if (!x) x = $(window).getWidth() / 2 - elContainer.getWidth() / 2;
				if (!y) y = $(window).getHeight() / 2 - elContainer.getHeight() / 2;
				elContainer.style.left = x + 30 + 'px';
				elContainer.style.top = y - 30 - sj.error.elContainer.getCoordinates().height + 'px';
				elContent.innerHTML = text;
				elContainer.fade('in');
			}
		},

		// Закрытие окна
		close: function()
		{
			sj.error.elContainer.fade('out');
		}
	},

	// Пост в списке постов
	post: {

		// Рейтинг поста
		rating: {
			// Инициализация
			init: function()
			{
				$$('.postRatingIncrease').each(function(item) {
					item.addEvent('click', sj.post.rating.onIncreaseClickHandler);
				});
				$$('.postRatingDecrease').each(function(item) {
					item.addEvent('click', sj.post.rating.onDecreaseClickHandler);
				});
			},

			// Обработчик клика на кнопки рейтинга поста
			onIncreaseClickHandler: function(e)
			{
				return sj.post.rating.setRating('increase', e);
			},

			onDecreaseClickHandler: function(e)
			{
				return sj.post.rating.setRating('decrease', e);
			},
			
			setRating: function(action, e)
			{
				var p = e.target.getAttribute('params').split(';');
				if (p[0] == '1')
				{
					// Скрытие
					$('postRating'+p[1]).fade('out');
					$('postRatingIncrease'+p[1]).fade('out');
					$('postRatingDecrease'+p[1]).fade('out');

					// Запрос
					var request = new Request.JSON({
						url: '/ajax/posts/'+action+'/id/'+p[1],
						onSuccess: sj.post.rating.onSuccessHandler
					});

					request.send();
				}
				else
				{
					sj.error.open(
						'Для участия в голосовании вам необходимо <a href="/account/login">авторизоваться</a> или <a href="/account/register">зарегистрироваться</a>.',
						e.page.x, e.page.y
					);
				}

				return false;
			},
			
			onSuccessHandler: function(response)
			{
				var el = $('postRating'+response.id);
				if (el)
				{
					el.innerHTML = response.rating;
					el.fade('in').addClass('starred');

					$('postRatingDecrease'+response.id).style.display = 'none';
					$('postRatingIncrease'+response.id).style.display = 'none';
				}
			}
		},
		
		// Форма добавления/редактирования поста
		form: {
			// Параграф-изображение
			image: {
				// Загрузка изображения
				upload: function(id, url)
				{
					// Отображение индикатора загрузки
					$('imgLoader'+id).style.display='block';

					// Скрытие лишних элементов
					$('imgWrapper'+id).fade('out');

					// Из сети
					if (url)
					{
						// Запрос
						var request = new Request.JSON({
							url: '/ajax/image/web',
							data: {'id': id, 'url': url},
							onSuccess: sj.post.form.image.onSuccessHandler
						});
						request.send();
					}
				},

				// После окончания загрузки
				onSuccessHandler: function(response)
				{
					if (response)
					{
						with(response)
						{
							var w = $('imgWrapper'+id);

							try
							{
								if (error) throw(error);
								if (img == '') throw('Произошла ошибка при загрузке изображения');

								var i = $('img'+id).addEvent('load', function(){
									$(this).fade('in');
								}).src='/images/uploaded/'+img+'m.jpg';

								// Установка в качестве значения имени загруженного изображения
								$('fieldValue'+id).value = img;
							}
							catch (e)
							{
								//sj.error.open(e);
								alert(e);
							}

							$('imgLoader'+id).style.display='none';
							w.fade('in');
						}
					}
				}
			},
			
			// Параграф-игрушка
			game: {
				// Установка значения
				setValue: function(id, value) {
					var g = $('game'+id);
					g.innerHTML =
						'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="550" height="400" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0">'+
							'<param name="movie" value="/uploaded/swf/'+value+'.swf" />'+
							'<param name="quality" value="high" />'+
							'<param name="wmode" value="transparent" />'+
							'<embed type="application/x-shockwave-flash" wmode="transparent" width="550" height="400" src="/uploaded/swf/'+value+'.swf" pluginspage="http://www.macromedia.com/go/getflashplayer" quality="high"></embed>'+
						'</object>';
					g.fade('show');
					$('fieldValue'+id).value = value;
				},
				
				// Загрузка флешки
				upload: function(id, url)
				{
					// Отображение индикатора загрузки
					$('gameLoader'+id).style.display='block';

					// Скрытие лишних элементов
					$('gameWrapper'+id).fade('out');
				},

				// После окончания загрузки
				onSuccessHandler: function(response)
				{
					if (response)
					{
						with(response)
						{
							var w = $('gameWrapper'+id);

							try
							{
								if (error) throw(error);
								if (file == '') throw('Произошла ошибка при загрузке файла');

								sj.post.form.game.setValue(id, file)
							}
							catch (e)
							{
								alert(e);
							}

							$('gameLoader'+id).style.display='none';
							w.fade('in');
						}
					}
				}
			}
		}
	},
};

window.addEvent('domready', function() {
	// ReMooz
	ReMooz.assign('#content a.remooz');

	// Citation
	if ($('citation'))
		citation.init();

	// Error
	sj.error.init();

	// Rating
	sj.post.rating.init();
});