function Item() {

	this.script = '/php/items.phtml';

	this.oItem = false;
	this.oFormContainer = false;
	this.oForm = false;
	this.oFormText = false;

	this.itemId = false;
	this.objectId = false;
	this.objectUrl = false;
	this.objectName = false;
	this.objectEngName = false;
	this.objectYear = false;

	this.subscribeStatus = 'off';
	this.aSubscribeImg = {
		off: {src: '/i/sign_off.gif', alt: 'Получать комментарии на почту'},
		on:	{src: '/i/sign_on.gif', alt: 'Не получать комментарии на почту'},
		loading: {src: '/i/sign_loading.gif', alt: 'Получать комментарии на почту'}
	};

	this.attitude = false;

	this.type = false;

	this.state = 'wait';

	// меняем рейтинг итема
	this.Rate = function(id, rate) {

		if(!this.type)
			return false;

		$.ajax({
			data: {
				_action: 'rate',
				_type: oItem.type,
				item_id: id,
				rate: rate
			},
			success: function(xml) {

				var error = $('error', xml).text();
				var success = $('success', xml).text();
				var id = $('id', xml).text();
				var rate = $('rate', xml).text();

 				if(error) {
					alert('Ошибка изменения рейтинга');
					return false;
				}


				if(success > 0) {
					rateRes = '+' + Math.abs(success);
					rateClass = 'pos';
				} else if(success < 0) {
					rateRes = '&minus;' + Math.abs(success);
					rateClass = 'neg';
				} else {
					rateRes = '0';
					rateClass = 'zero';
				}

				if(rate != 0) {
					$('#rating' + id + ' div.icons').remove();
					$('#rating' + id).removeClass('vote');
				}

				$('#rating' + id + ' div.rating').attr('class', 'rating ' + rateClass).html(rateRes);

				return true;

			}
		});

    	return false;

	}

	// назначаем главные переменные для работы с итемами
	this.Attach = function(objectId, type, subscribeStatus) {

		that = this;

		this.objectId = objectId;
		this.type = type;

		if(this.type == 'comments') {
			this.subscribeStatus = subscribeStatus;
			this.ChangeSubscribeButton();
		}

		$.ajaxSetup({
			url: this.script,
			dataType: 'xml',
			type: 'POST'
		});

		var el = (this.type == 'reviews' ? $('#addReviewForm').get(0) : $('#addItemForm').get(0));

		if(el)
			this.oFormContainer = el;

		// прописываем стили фона для наведения на кнопки текстового редактора
		$('li',this.oFormContainer).not($('li.dvd',this.oFormContainer)).mouseover(function(){
			$(this).addClass("hover");
		}).mouseout(function(){
			$(this).removeClass("hover");
		});

		this.oForm = $('form', this.oFormContainer).get(0);

		this.oFormText = $('textarea', this.oFormContainer).get(0);

		// меняем кнопку "свернуть" на "развернуть" у свернутых тредов
		$('#items div.closed').each(function(){
			var id = this.id.replace('item','');
			oItem.CloseOpenItem(id, 'closed');
		});
		this.CloseOpenAll();
	}

	// редактируем итем
	this.Edit = function(itemId) {

		this.state = 'edit';

		this.CancelEdit(true);

		this.itemId = itemId;

		// прячем сам коммент
		this.oItem = document.getElementById('item' + this.itemId);
		if(this.oItem)
			this.oItem.style.display = 'none';

		$.ajax({
			data: {
				_action: 'edit',
				_type: oItem.type,
				_id: oItem.objectId,
				item_id: oItem.itemId
			},
			success: function(xml) {

				var error = $('error', xml).text();
				var itemText = $('success', xml).text();

				if(error) {
					alert(error);
					return false;
				}

				// вставляем кнопку с отменой редактирования
				$('#buttonCancel').show(0);

				oItem.oForm.onsubmit = oItem.Save;

				// меняем главную кнопку
				$('#buttonSubmit').val('Сохранить');

				// вставляем форму за редактируемым комментом
				$(oItem.oItem).after(oItem.oFormContainer);

				// показываем форму
				$(oItem.oFormContainer).show(0);

				oItem.oFormText.value = itemText;
				oItem.ChangeTextareaHeight();

				oItem.ToggleLinkWriteComment('show');

				return false;

			}
		});

		return false;

	}

	// прекращаем редактировать коммент
	this.CancelEdit = function(noSaveText) {

		// показываем коммент
		$('#item' + oItem.itemId).show(0);

		// показываем надпись "Написать коммент"
		oItem.ToggleLinkWriteComment('show');

		// форму на свое место
//		$('#items').after(oItem.oFormContainer);

//		if(!$.browser.msie)
			$(oItem.oFormContainer).insertAfter($('#items'));

		// скрываем и разлочиваем форму
		$('#addItemForm').hide(0);
		oItem.ButtonsUnlock();

		// если надо сбрасываем текст
		if(noSaveText && oItem.oFormText)
			oItem.oFormText.value = '';

		// сбрасываем указатель на родительский итем
		oItem.oForm._parent_id.value = '';

		oItem.itemId = false;

		return false;
	}

	// лочим форму
	this.ButtonsLock = function() {

		$('textarea', this.oForm).attr('disabled','disabled').addClass('disable');
		$('input', this.oForm).attr('disabled','disabled').hide(0);

		// думалка
		$('span.wait', this.oForm).show(0);

		return false;
	}

	// унлочим форму
	this.ButtonsUnlock = function() {

		$('textarea', this.oForm).removeAttr('disabled').removeClass('disable');
		$('input', this.oForm).removeAttr('disabled').show(0);

		// думалка
		$('span.wait', this.oForm).hide(0);

		return false;
	}

	// постим коммент
	this.Post = function() {

		oItem.ButtonsLock();

		var parentId = oItem.oForm._parent_id.value;

		$.ajax({
			data: {
				_action: 'post',
				_type: oItem.type,
				_id: oItem.objectId,
				_parent_id: parentId ? parentId : '',
				text: oItem.oFormText.value
			},
			success: function(xml) {

				var error = $('error', xml).text();
				var itemId = $('item_id', xml).text();
				var itemText = $('success', xml).text();
				var itemsCount = $('items_count', xml).text();

				if(error) {
					alert(error);
					return false;
				}

				var parentId = oItem.oForm._parent_id.value;
				var oChildItems = false;

				if(parentId) {

					// нет контейнера для чайлдов? создаём его!
					if($('#childItems' + parentId).length == 0)
						$('#item' + parentId).after('<div id="childItems' + parentId + '" class="in"></div>');

					oChildItems = $('#childItems' + parentId).get(0);

				} else {
					oChildItems = $('#items').get(0);
				}

				// просто перегружаем в случае ошибки
				if(!oChildItems)
					document.location.href = document.location.href;

				oItem.CancelEdit(true);
				// скрываем комент, добавляем на страницу и плавно отображаем
				itemText = itemText.replace('div class="comment','div class="comment none');
				$(oChildItems).append(itemText);
				$('#item' + itemId).show(0);

				// изменяем количество комментов на странице и показываем плашку над комментами, если надо
				oItem.CloseOpenAll();
				$('.comm_count').text(itemsCount);
				if(itemsCount == 1)
					$('#itemsTitle').show(0);


				// переходим на новый коммент
				document.location.href = document.location.href.replace(/#.+$/, '') + '#' + itemId;

				return false;

			}
		});

		return false;
	}


	// сохраняем отредактированный коммент
	this.Save = function() {

		oItem.ButtonsLock();

		$.ajax({
			data: {
				_action: 'save',
				_type: oItem.type,
				_id: oItem.objectId,
				item_id: oItem.itemId,
				text: oItem.oFormText.value
			},
			success: function(xml) {
				if(oItem.itemId)
					if(oItem.Replace(xml))
						oItem.CancelEdit(true);
			}
		});

		return false;
	}

	// скрываем / показываем ссылку "Написать комментарий" внизу
	this.ToggleLinkWriteComment = function(action) {

		if(action == 'hide') {

			// показываем заголовок "Написать комментарий"
			$('h1', this.oFormContainer).show(0);
			$('#NoAnswer').hide(0);

		} else if(action == 'show') {

			// скрываем заголовок "Написать комментарий" в форме
			$('h1', this.oFormContainer).hide(0);
			$('#NoAnswer').show(0);

		}
	}


	// перемещаем форму после итема, назначаем _parent_id и выводим ссылку внизу
    this.Answer = function(id) {

		// если состояние - редактирование, то текст не сохраняем в форме
		this.CancelEdit(this.state == 'edit' ? true : false);

		this.state = 'answer';

		this.ToggleLinkWriteComment('show');

		this.oItem = $('#item' + id).get(0);
		$(this.oFormContainer).insertAfter(this.oItem).show(0);

        this.oForm._parent_id.value = id;
		this.oFormText.focus();

        return false;

    }

	this.AnswerQuote = function(id) {

		this.Answer(id);

        el = document.getElementById('text' + id);
        if (el) {
            txt = el.innerHTML;
            txt = txt.replace(/<b>(.+?)<\/b>/gi, '[B]$1[/B]');
            txt = txt.replace(/[\r\n]/g, '');
            txt = txt.replace(/<div [^>]*quote[^>]*>(.+?)<\/div>/gi, '[QUOTE]$1[/QUOTE]');
            txt = txt.replace(/<\/p>/gi, "\n");
            txt = txt.replace(/<[^>]+>/g, '');

            el = document.getElementById('author' + id);
            if (el) {
                txt = '[QUOTE]\n[B]' + el.innerHTML + '[/B]\n' + txt + '[/QUOTE]\n';
            } else {
                txt = '[QUOTE]\n' + txt + '[/QUOTE]\n';
            }
        }

		if (document.addItemForm && document.addItemForm.text) {
		    document.addItemForm.text.value = txt;
		    document.addItemForm.text.focus();
		}

		return false;
    }

	// фигачим форму в конец вместо ссылки, убираем _parent_id
    this.NoAnswer = function() {

		// если состояние - редактирование, то текст не сохраняем в форме
		this.CancelEdit(this.state == 'edit' ? true : false);

		this.ToggleLinkWriteComment('hide');

//		if(!$.browser.msie)
//			$(this.oFormContainer).insertAfter($('#items'));

		$(this.oFormContainer).show(0);

		this.oForm._parent_id.value = '';
		this.oFormText.focus();
		this.ChangeTextareaHeight();

		return false;

    }

	// сворачиваем или разворачиваем итем и весь тред за ним
	this.ToggleThread = function(id) {

		threadState = $('#item' + id).attr("class").match(/closed/) ? 'opened' : 'closed';

		// сохраняем статус треда для корневного итема
		if(this.state == 'wait') {
			$.ajax({
				data: {
					_action: 'change_thread_state',
					_type: this.type,
					_id: this.objectId,
					item_id: id,
					state: threadState
				}
			});
		}

		oItem.CloseOpenThread(id, threadState);
		oItem.CloseOpenAll();

		return false;

	}

	// открываем или закрываем
	this.CloseOpenThread = function(id, threadState) {

		this.CloseOpenItem(id, threadState);

		// применяем ту же функцию ко всем дочерним комментам текущего
		$('div.comment', 'div#childItems' + id).each(function() {
			var id = this.id.replace('item','');
			oItem.CloseOpenItem(id, threadState);
		});
	}

	// открываем или закрываем
	this.CloseOpenItem = function(id, threadState) {

		if(threadState == 'opened') {
			// открываем
			$('#item' + id).removeClass('closed');
			$('a.open', '#item' + id).removeClass('open').addClass('close').attr('title','Свернуть тред');
			$('span.item_notice', '#item' + id).css('display','none');
		} else {
			// закрываем
			$('#item' + id).addClass('closed');
			$('a.close', '#item' + id).removeClass('close').addClass('open').attr('title','Развернуть тред');
			$('span.item_notice', '#item' + id).css('display','inline');
		}

		return false;
	}

	// меняем ссылку "свернуть всё" в зависимости от наличия свернутых коментов
	this.CloseOpenAll = function() {

		var openedExists = this.IsOpenedItemsExists();

		var text = openedExists ? 'свернуть всё' : 'развернуть всё';
		var newClass = openedExists ? 'up' : '';

		$('#itemsTitle .roll').removeClass('up').addClass(newClass).html('<span>' + text + '</span>').click(this.ToggleCloseOpenAll);

	}

	// открываем или закрываем все итемы в дереве
	this.ToggleCloseOpenAll = function() {

		var threadsState = oItem.IsOpenedItemsExists() ? 'closed' : 'opened';

		$.ajax({
			data: {
				_action: 'change_all_threads_state',
				_type: oItem.type,
				_id: oItem.objectId,
				state: threadsState
			},
			success: function(xml) {

				var error = $('error', xml).text();
				var success = $('success', xml).text();
				var state = $('state', xml).text();

				if(error)
					return false;

				// проходимся по айдищникам в ответе и сворачиваем, разворачиваем
				var aIds = success.split(',');
				$(aIds).each(function(k, id) {
					oItem.CloseOpenThread(id, state);
				});

				// меняем ссылку
				oItem.CloseOpenAll();

			}
		});
	}

	// проверяет есть ли открытые итемы в ленте
	this.IsOpenedItemsExists = function() {

		var openedExists = false;

		$('#items div.comment').each(function() {
			if(!this.className.match(/closed/))
				openedExists = true;
		});

		return openedExists;
	}

	// обрабатываем серверный ответ и либо выводим ошибку, либо подменяем старый итем that.itemId новым итемом из success
	this.Replace = function(xml) {

		var error = $('error', xml).text();
		var itemText = $('success', xml).text();

		if(error) {
			alert(error);
			return false;
		}

//		itemText = itemText.replace('div class="comment','div class="comment none');
		$('#item' + this.itemId).after(itemText).hide(0).remove();
//		setTimeout("$('#item' + that.itemId).get(0).removeNode(true);", 1000);

//		if($('#item' + this.itemId).length > 1)
//			$('#item' + this.itemId).show(0);

		return true;

	}

	// удаляем в корзину итем
	this.Delete = function(itemId) {

		this.CancelEdit(false);

		this.itemId = itemId;

		$.ajax({
			data: {
				_action: 'delete',
				_type: this.type,
				_id: this.objectId,
				item_id: this.itemId
			},
			success: function(xml) {
				if(oItem.itemId)
					oItem.Replace(xml);
			}
		});

		return false;
    }

	// восстанавливаем из корзины итем
    this.Restore = function(itemId) {

		this.CancelEdit(false);

		this.itemId = itemId;

		$.ajax({
			data: {
				_action: 'restore',
				_type: this.type,
				_id: this.objectId,
				item_id: this.itemId
			},
			success: function(xml) {
				if(oItem.itemId)
					oItem.Replace(xml);
			}
		});

		return false;
    }

	// удаляем итем безвозвратно
    this.Annihilate = function(itemId) {

		this.CancelEdit(false);

		this.itemId = itemId;

		if(confirm("Действительно ли вы хотите уничтожить безвозвратно это сообщение?")) {

			$.ajax({
				data: {
					_action: 'annihilate',
					_type: this.type,
					_id: this.objectId,
					item_id: this.itemId
				},
				success: function(xml) {

					var error = $('error', xml).text();
					var itemsCount = $('items_count', xml).text();
					var itemsId = $('items_id', xml).text();

					if(error) {
						$('p.ans', '#item' + itemId).append('<span class="dvd"> | </span><span class="err" style="color: red;">' + error + '</span>');
						return false;
					}

					// изменяем количество комментов на странице и скрываем плашку над комментами, если надо
					$('.comm_count').text(itemsCount);
					if(itemsCount == 0)
						$('#itemsTitle').hide(0);

					oItem.Replace(xml);
				}
			});
		}

		return false;
    }

	// блок св-в и методов для отзыва и сообщения

	// показываем и скрываем форму добавления итемов
	this.ToggleAddForm = function(action) {

		el = document.getElementById('addForm');
		if(el && el.tagName == 'DIV') {

			if(action == 'show')
				this.ShowMessage('form', 'none');

			// если хотим редактировать, то надо подгрузить форму или показать старый отзыв
			if(this.state == 'edit') {
				if(action == 'show') {
					var oReq = this.LoadItemForm();

					el.innerHTML = oReq.responseText; //.replace(/</g, '&lt;');

				} else {
					var itemFull = document.getElementById('itemFull');
					if(itemFull) {
						itemFull.style.display = 'block';
						$('#items').show(0);
						$('#NoAnswer').show(0);

						// чтобы работали BB-функции
						currentForm = 'addItemForm';
					}
				}
			} else {
				// переносим экран на форму
				if(action == 'show')
					document.location.replace(document.location.href.replace(/#.+$/, '') + '#tabs');
			}

			(action == 'show') ? $(el).show(500) : $(el).hide(0);

		} else {
			// чтобы сработала ссылка в href на ..../add
			return true;
		}

		(action == 'hide') ? $('#addButton').show(500) : $('#addButton').hide(0);

		return false;

	}

	// подгружаем форму в el
	this.LoadItemForm = function() {

//		$(el).load('/php/review.php', {
//			id: this.objectId,
//			action: 'get_form'
//		});


		if(!el)
			return false;

		var oReq = new AJAX_Request();

		if(this.itemId)
			oReq.Set('item_id', this.itemId);
		if(this.objectId)
			oReq.Set('_id', this.objectId);
		if(this.objectUrl)
			oReq.Set('_url', this.objectUrl);
		if(this.type)
			oReq.Set('_type', this.type);
		if(this.state)
			oReq.Set('_action', this.state);

		oReq.Send("/php/items_form.phtml", 'post');

		return oReq;

	}


	// выбираем фильм
	this.ReviewSelectFilm = function(xmlEl) {

		if(xmlEl) {
			cn = xmlEl.getElementsByTagName('_id');
			this.objectId = cn[0].childNodes[0] ? cn[0].childNodes[0].nodeValue : '';

			cn = xmlEl.getElementsByTagName('rus_name');
			this.objectName = cn[0].childNodes[0] ? cn[0].childNodes[0].nodeValue : '';

			cn = xmlEl.getElementsByTagName('eng_name');
			this.objectEngName = cn[0].childNodes[0] ? cn[0].childNodes[0].nodeValue : '';

			cn = xmlEl.getElementsByTagName('year');
			this.objectYear = cn[0].childNodes[0] ? cn[0].childNodes[0].nodeValue : '';
		}

		el = document.getElementById('film');
		if(el) {

			el.innerHTML = '';
			if(this.objectId) {

				el.innerHTML = '<h1>' + this.objectName + ' <span class="eng_name">' + this.objectEngName + ', ' + this.objectYear + ' </span><span class="dvd">|</span><span class="add"> [ <a href="#" onclick="return oItemsReview.ReviewChangeFilm();">изменить</a> ]</span></h1>';

				$('#lookupForm').hide(0);
				$('#film').show(0);

			} else {

				el.innerHTML = '';

				$('#lookupForm').show(0);
				$('#film').hide(0);

			}

		}

		return false;
	}

	this.ReviewChangeFilm = function() {

		if(!this.oForm)
			return false;

		this.objectId = false;
		this.attitude = false;
		this.ReviewToggleButton('like', false);
		this.ReviewToggleButton('hate', false);
		this.ReviewToggleButton('seen', false);

		this.oFormText.readOnly = this.attitude ? false : true;
		this.oFormText.className = this.attitude ? '' : 'disable';

		this.ReviewSelectFilm();

		return false;

	}

	this.ReviewToggleAttitude = function(att) {

		if(this.objectId) {

			if(att) {
				att = att.replace(/\d+/, '');
				el = document.getElementById('review_' + att);

				if(el) {
					if(el.className.match(/_p$/)) {
						el.className = att;

						if(att == 'like' || att == 'hate') {
							this.attitude = 'seen';
						} else {
							this.attitude = false;
						}

					} else {
						el.className = att + '_p';
						this.attitude = att;

						if(att == 'like') {
							this.ReviewToggleButton('hate', false);
						} else if(att == 'hate') {
							this.ReviewToggleButton('like', false);
						}
					}
				}

				if(this.attitude == false && att == 'seen') {
					this.ReviewToggleButton('like', false);
					this.ReviewToggleButton('hate', false);
				} else if(this.attitude == 'like' || this.attitude == 'hate') {
					this.ReviewToggleButton('seen', true);
				}

//				alert(this.attitude);
			}

		} else {
//			alert('Выберите фильм');
		}

		if(this.oForm) {
			this.oFormText.readOnly = this.attitude ? false : true;
			this.oFormText.className = this.attitude ? '' : 'disable';
		}

	}

	this.ReviewToggleButton = function(type, pushed) {

		el = document.getElementById('review_' + type);
		if(el)
			el.className = type + (pushed ? '_p' : '');

	}

	this.ReviewCheck = function() {

		if(!this.oForm)
			return false;

		if(!this.objectId || !this.attitude || this.oFormText.value.replace(/[\s]/g, '').length == 0) {
			this.ShowMessage('form', 'notice', 'Вы не заполнили все поля');
			return false;
		}

		if(this.state == 'edit') {

			$.ajax({
				data: {
					item_id: this.itemId,
					_id: this.objectId,
					_action: 'save',
					_type: 'reviews',
					attitude: this.attitude,
					text: this.oFormText.value
				},
				success: function(xml) {

					var error = $('error', xml).text();
					var success = $('success', xml).text();

					if(error) {
						that.ShowMessage('form', 'notice', error);
						return false;
					}

					// ответ хороший - меняем блок оценки
					if(success) {

						$('#items,#NoAnswer,#itemFull').show(0);

						$('#itemText').html(success);
						$('#addForm').text('');

						// меняем отношение
						$('#review_attitude').attr('class', 'att ' + that.attitude);
					}
				}
			});

			return false;

		} else {

			this.oForm._id.value = this.objectId;
			this.oForm.attitude.value = this.attitude;
			this.oForm.action = this.script;
			this.oForm.method = 'post';
			this.oForm.submit();

			return false;

		}

		return false;

	}

	// редактируем отзыв
	this.ReviewEdit = function(itemId, objectId) {

		this.itemId = itemId;
		this.objectId = objectId;
		this.type = 'reviews';
		this.state = 'edit';

		// берем текущее отношение
		this.attitude = $('#review_attitude').attr('class').replace('att ', '');

		$('#items,#NoAnswer,#itemFull').hide(0);

		// подгружаем и показываем форму редактирования
		this.ToggleAddForm('show');

		// поднимаемся наверх к форме редактирования
		document.location.href = document.location.href.replace(/#.+$/,'') + '#top';

		// находим форму и остальные объекты
		this.Attach(this.objectId, 'reviews');

		// чтобы работали BB-функции
		currentForm = 'addReviewForm';

		this.ChangeTextareaHeight();

		oItem.oFormContainer.style.display = 'none';

		this.ReviewToggleAttitude(this.attitude);

		return false;

	}

	// показываем месседж
	this.ShowMessage = function(id, type, text) {

		el1 = document.getElementById(id + '_notice');
		el2 = document.getElementById(id + '_ok');

		if(!el1 || !el2)
			return false;

		if(type == 'ok') {
			el1.style.display = 'none';
			el2.style.display = 'inline';
			co = el2.getElementsByTagName('SPAN');
			if(text) {
				co[0].innerHTML = text;
			} else {
				co[0].innerHTML = 'ok';
			}
		} else if(type == 'notice') {
			el1.style.display = 'inline';
			el2.style.display = 'none';
			if(text) {
				co = el1.getElementsByTagName('SPAN');
				co[0].innerHTML = text;
			}
		} else if(type == 'none') {
			el1.style.display = 'none';
			el2.style.display = 'none';
		}

		return true;
	}


	// показ изагрузка предпросмотра
	this.TogglePreview = function(show) {

		var curText = $("textarea[name='text']").val();
		var curPostcategory = $("#postcategory").val();
		var curObjects = $("#objects").val();
		var curTitle = $("#title").val();

		if (show) {

				 $.ajax({
		   			type: 'POST',
		   			url: '/php/items_preview.phtml',
		   			dataType: "html",
		   			data: {
						_action: 'preview',
						_type : 'post',
						text : curText,
						postcategory : curPostcategory,
						objects : curObjects,
						title : curTitle
					},
		   			success: function(html){
						$('#text_preview').html(html);
						$("#pagetitle").text("Предпросмотр сообщения").append('');
						$('#blog_form').hide(0);
						$('#view').fadeIn("normal");
						return false;
		   			}
		 		});
			} else {
				$("#pagetitle").text("Добавление сообщения");
				$('#view').hide(0);
				$('#blog_form').fadeIn("notmal");
			}
		return false;

    }

	// показ изагрузка предпросмотра
	this.ToggleReviewPreview = function(show) {

		var curText = $("textarea[name='text']").val();

		if (show) {

				 $.ajax({
		   			type: 'POST',
		   			url: '/php/items_preview.phtml',
		   			dataType: "html",
		   			data: {
						_action: 'preview',
						_type : 'review',
						text : curText,
						film : this.objectName,
						id : this.objectId
					},
		   			success: function(html){
						$('#text_preview').html(html);
						$("#pagetitle").text("Предпросмотр отзыва").append('');
						$('#review_form').hide(0);
						$('#view').fadeIn("normal");
						return false;
		   			}
		 		});
			} else {
				$("#pagetitle").text("Добавление отзыва");
				$('#view').hide(0);
				$('#review_form').fadeIn("notmal");
			}
		return false;

    }


}


// подписываем юзера на комменты
Item.prototype.Subscribe = function() {

	oItem.ChangeSubscribeButton('loading');

	$.ajax({
		data: {
			_action: oItem.subscribeStatus == 'on' ? 'unsubscribe' : 'subscribe',
			_type: oItem.type,
			_id: oItem.objectId
		},
		success: function(xml) {
			oItem.subscribeStatus = $('status', xml).text();
			setTimeout("oItem.ChangeSubscribeButton();", 2000);
		}
	});

	return false;

}

// меняем кнопку подписки
Item.prototype.ChangeSubscribeButton = function(status) {

	if(!status)
		status = this.subscribeStatus;

	$('.subscribeButton').attr({
		src: this.aSubscribeImg[status]['src'],
		title: this.aSubscribeImg[status]['alt'],
		alt: this.aSubscribeImg[status]['alt']
	});

	if(status == 'loading')
		$('.subscribeButton').css('cursor','auto').unbind();
	else
		$('.subscribeButton').css('cursor','pointer').click(this.Subscribe);

}


// показываем help к textarea
Item.prototype.ShowHelp = function() {
	alert('Нужна помощь? Глупец! Разобраться сам не можешь!?');
	return false;
}

// ищем контейнер для textarea
Item.prototype.SetTextarea = function(el) {
	this.oFormText = $('textarea', el.parentNode.parentNode.parentNode.parentNode.parentNode).get(0);

	// убираем подсвеченность с кнопок
	$('li',this.oFormContainer).not($('li.dvd',this.oFormContainer)).removeClass("hover");
}

// вставляем болд в textarea
Item.prototype.InsertBold = function(el) {
	this.SetTextarea(el);
	this.cursorPos = false;
	this.InsertTag('[b]', '[/b]');
}

// вставляем италик в textarea
Item.prototype.InsertItalic = function(el) {
	this.SetTextarea(el);
	this.cursorPos = false;
	this.InsertTag('[i]', '[/i]');
}

// вставляем заголовок в textarea
Item.prototype.InsertTitle = function(el) {
	this.SetTextarea(el);
	this.cursorPos = false;
	this.InsertTag('[h2]', '[/h2]');
}

// вставляем цитату в textarea
Item.prototype.InsertQuote = function(el) {
	this.SetTextarea(el);
	this.cursorPos = false;
	this.InsertTag('[quote]', '[/quote]');
}

// получаем выделенный в форме текст
Item.prototype.GetSelectedText = function() {
	var cursorPos = this.GetCursor();
	var str = this.oFormText.value.substring(cursorPos.start, cursorPos.end);
	return str;
}

// вставляем ссылку в textarea
Item.prototype.OpenLinkInterface = function(el) {
	this.SetTextarea(el);

	this.cursorPos = this.GetCursor();

	$('#linkError').text('').hide(0);
	$('#linkText').val(this.GetSelectedText());
	$('#linkUrl').removeClass('error').val('http://');

	oInterface.Open(el,'link2text');

	$('#linkUrl').get(0).focus();

	return false;
}

// вставляем линк в textarea
Item.prototype.InsertLink = function() {

	var url = $('#linkUrl').val();
	var text = $('#linkText').val();

	if(!ValidateUrl(url)) {
		$('#linkError').text('Это не ссылка! Пожалуйста, введите правильный URL').show(0);
		$('#linkUrl').addClass('error');
		return false;
	}

	oInterface.Hide();
	this.InsertTag('[url=' + url + ']' + text, '[/url]', true);

	return false;
}

// вставляем урл в textarea
Item.prototype.OpenUserInterface = function(el) {
	this.SetTextarea(el);

	this.cursorPos = this.GetCursor();

	$('#userError').text('').hide(0);
	$('#userText').val(this.GetSelectedText()).focus(function() {
		$('#userName').unbind('keyup');
	});

	$('#userName').val(this.GetSelectedText()).removeClass('error').keyup(function() {
		$('#userText').val($('#userName').val());
	});

	oInterface.Open(el,'user2text');

	$('#userName').get(0).focus();

	return false;
}

// вставляем юзера в textarea
Item.prototype.InsertUser = function() {

	var name = $('#userName').val();
	var text = $('#userText').val();

	$.ajax({
		url: '/php/register.phtml',
		data: {
			_action: 'check_login_exists',
			login: name
		},
		success: function(xml) {

			var error = $('error', xml).text();
			var success = $('success', xml).text();
			if(error) {
				$('#userError').text('Вы неправильно ввели имя сообщника').show(0);
				$('#userName').addClass('error');
				return false;
			}

			oInterface.Hide();
			oItem.InsertTag('[user=' + name + ']' + text, '[/user]', true);

			return false;
		}
	});

	return false;
}

// вставляем картинку в textarea
Item.prototype.OpenImageInterface = function(el) {

	this.SetTextarea(el);

	this.cursorPos = this.GetCursor();

	$('#imageError').text('').hide(0);
	$('#imageText').val(this.GetSelectedText());
	$('#imagePath').val('').removeClass('error').focus(function() {
		$('#imagePC').attr('checked','checked');
	});

	$('#imageUrl').val('http://').removeClass('error').focus(function() {
		$('#imageWeb').attr('checked','checked');
	});

	oInterface.Open(el,'image2text');

	$('form', $('#image2text')).ajaxForm({
		url: '/php/document.phtml',
		type: 'post',
		dataType: 'xml',
		success: function(xml) {

			var error = $('error', xml).text();
			var success = $('success', xml).text();
			var source = $('source', xml).text();

			if(error) {
				$('#imageError').text(error).show(0);
				if(source == 'pc') {
					$('#imagePath').addClass('error');
				} else if(source == 'web') {
					$('#imageUrl').addClass('error');
				}
				return false;
			}

			oInterface.Hide();
			oItem.InsertTag('[img=' + success + ']' + $('#imageText').val(), '[/img]', true);

			return false;

		}
	});

	return false;
}

// вставляем картинку в textarea
Item.prototype.InsertImage = function() {

	return false;

}

// вставляем видео в textarea
Item.prototype.OpenVideoInterface = function(el) {
	this.SetTextarea(el);

	var videoText = 'В данный момент мы поддерживаем обработку ссылок только на youtube.com, video.google.com, vision.rambler.ru, video.mail.ru и rutube.ru. Видеоролики с других сервисов не могут быть вставлены, для добавления ресурса в список разрешенных - напишите о нем в <a href="/support/">техподдержку</a>';

	this.cursorPos = this.GetCursor();

	$('#videoError').html(videoText);
	$('#videoUrl').val('http://').removeClass('error');
	$('#videoText').val(this.GetSelectedText());

	oInterface.Open(el,'video2text');

	$('#videoUrl').get(0).focus();

	return false;
}

// вставляем картинку в textarea
Item.prototype.InsertVideo = function() {

	var videoTextError = 'Мы не поддерживаем обработку ссылок с этого сайта. В данный момент обрабатываются ссылки только с сайтов youtube.com, video.google.com, video.rambler.ru, video.mail.ru и rutube.ru.';

	var url = $('#videoUrl').val();
	var text = $('#videoText').val();

	if(!ValidateUrl(url) || !url.match(/(youtube.com|video.google.com|vision.rambler.ru|video.mail.ru|rutube.ru)/)) {
		$('#videoError').html(videoTextError);
		$('#videoUrl').addClass('error');
		return false;
	}

	oInterface.Hide();
	this.InsertTag('[video=' + url + ']' + text, '[/video]', true);

	return false;
}

// вставляем таг в textarea
Item.prototype.InsertTag = function(starttag, endtag, special) {

	this.oFormText.focus();

	var scrtop = this.oFormText.scrollTop;
	var cursorPos = this.cursorPos ? this.cursorPos : this.GetCursor();

	if (cursorPos.start == cursorPos.end) {
		var nuCursorPos = cursorPos.start + starttag.length;
		this.oFormText.value = this.oFormText.value.substring(0,cursorPos.start) + starttag + endtag + this.oFormText.value.substr(cursorPos.end);
	} else {
		var txt_pre = this.oFormText.value.substring(0, cursorPos.start);
		var txt_sel = special ? '' : this.oFormText.value.substring(cursorPos.start, cursorPos.end);
		var txt_aft = this.oFormText.value.substring(cursorPos.end);

		this.oFormText.value = txt_pre + starttag + txt_sel + endtag + txt_aft;
		var nuCursorPos = String(txt_pre + starttag + txt_sel + endtag).length;
	}

	if(special)
		nuCursorPos = nuCursorPos + endtag.length;

	this.SetCursor(nuCursorPos, nuCursorPos);

	if(scrtop)
		this.oFormText.scrollTop = scrtop;

	// возвращаем кнопкам их первоначальный вид
	$('li',this.oFormContainer).not($('li.dvd',this.oFormContainer)).removeClass("hover");

	return false;
}

Item.prototype.SetCursor = function(start, end) {

	if(this.oFormText.createTextRange) {
		var range = this.oFormText.createTextRange();
		range.move("character", start);
		range.select();
	} else if(this.oFormText.selectionStart) {
		this.oFormText.setSelectionRange(start, end);
	}

}

Item.prototype.GetCursor = function() {

	var input = this.oFormText;

	input.focus();

	var result = { start: 0, end: 0 };

	if (input.setSelectionRange) {
		result.start = input.selectionStart;
		result.end = input.selectionEnd;
	} else if (!document.selection) {
		return 0;
	} else if (document.selection && document.selection.createRange) {
	    var range = document.selection.createRange();
	    var stored_range = range.duplicate();
	    stored_range.moveToElementText(input);
	    stored_range.setEndPoint('EndToEnd', range);
	    result.start = stored_range.text.length - range.text.length;
	    result.end = result.start + range.text.length;
	}

	return result;

}

// меняем высоту textarea
Item.prototype.ChangeTextareaHeight = function(oTextarea){

	var heightMin = 8;
	var heightMid = 20;
	var heightMax = 40;
	var rowMaxLength = 75;

	if(!oTextarea)
		var oTextarea = $(this).is('textarea') ? this : this.oFormText;

	if(!oTextarea)
		return false;

	// кол-во переносов строк
	var rowsCount = 1 + oTextarea.value.replace(/[^\n]/g,'').length;

	// кол-во длинных строчек
	var arRows = oTextarea.value.split('\n');
	for(var i=0; i<arRows.length; i++) {
		var wqe = arRows[i].length;
		var asd = Math.round(arRows[i].length / rowMaxLength - 0.5);
		rowsCount += Math.round(arRows[i].length / rowMaxLength - 0.5);
	}

	if(rowsCount > heightMid)
		$(oTextarea).attr('rows', heightMax);
	else if(rowsCount > heightMin && rowsCount <= heightMid)
		$(oTextarea).attr('rows', heightMid);
	else if(rowsCount <= heightMin)
		$(oTextarea).attr('rows', heightMin);

}


ValidateUrl = function(url) {

	if(!url.match(/^[:\/.\-\_a-z0-9\?\=&]{3,}/i) || !url.match(/\./i))
		return false;
	else
		return true;
}