function comments_editor(block, editor_id)
{
	this.block = block;
	this.edit_block = null;
	this.editor_id = editor_id;
	this.mode = '';


	this.dogs = {};
	this.comments_url = '';
	this.comments_header = false;
	this.container_click_func = null;

	var ce = this;
	$('option', block.find('select#oid')).each(function()
	{
		var id = parseInt($(this).attr('value'));
		var name = $(this).text();
		if (!isNaN(id) && (id != 0)) ce.dogs[id] = name;
	});

	this.setup = function(comments_url, comments_header, container_click_func)
	{
		this.comments_url = comments_url;
		this.comments_header = comments_header;
		this.container_click_func = container_click_func;
	};

	this.validate_form = function(formData, form)
	{
		var tmce = tinyMCE.get(this.editor_id);
		var text = tmce.getContent();
		form.find('#text_err').remove();

		if (!text.length)
		{
			form.find('#text').after('<div class="error" id="text_err">Пожалуйста, оставте свое мнение.</div>');
			return false;
		}

		var links = text.match(/(<a[^>]*href=[^>]{1,}>)/gi);
		if ((links != null) && (links.length > 3))
		{
			form.find('#text').after('<div class="error" id="text_err">Пожалуйста, сократите количество гиперссылок до 3-х.</div>');
			return false;
		}

		if (text.match(/(\[url=http:\/\/)/gi) || text.match(/(\[url\].*?\[\/url\])/gi))
		{
			form.find('#text').after('<div class="error" id="text_err">На нашем сайте не поддерживаются гиперссылки в bb-тэгах.</div>');
			return false;
		}

		for (var i = 0, j = formData.length; i < j; i++)
		{
			if (formData[i].name == 'text')
			{
				formData[i].value = text;
				break;
			}
		}

		return true;
	};

	this.before_submit = function(formData, jqForm, options)
	{
		if (this.validate_form(formData, jqForm))
		{
			this.block.block({ message: '<div id="post_comment" style="color: #ffffff; font-size: 16px; font-weight: bold">Ждите...</div>',  centerX : 0, centerY: 0, css : { border: '0px', backgroundColor : 'transparent' }});
			return true;
		} else
		{
			return false;
		}
	};
	
	this.after_submit = function(responseText, statusText)
	{
		this.block.unblock();
		if (statusText == 'success')
		{
			switch (this.mode)
			{
				case 'edit':
				{
					this.after_edit(responseText, statusText);
					break;
				}

				case 'comment':
				{
					this.after_comment(responseText, statusText);
					break;
				}
			}
		} else
		{
			this.cancel();
		}
	};

	this.place_to_comment = function(block_item)
	{
		this.block.find('form').find('#text_err').remove();
		if (tinyMCE.get(this.editor_id)) tinyMCE.execCommand('mceRemoveControl', false, this.editor_id);
		block_item.after(this.block);
		if (!tinyMCE.get(this.editor_id)) tinyMCE.execCommand('mceAddControl', false, this.editor_id);
	};

	this.place_to_end = function()
	{
		this.block.find('form').find('#text_err').remove();
		if (tinyMCE.get(this.editor_id)) tinyMCE.execCommand('mceRemoveControl', false, this.editor_id);
		$('#new_comment_place').after(this.block);
		if (!tinyMCE.get(this.editor_id)) tinyMCE.execCommand('mceAddControl', false, this.editor_id);
	};

	this.edit = function(comment_id)
	{
		$('#add_comment_ctrl').hide();

		this.edit_block = $('#post_block_' + comment_id);
		this.edit_block.hide();
		this.place_to_comment(this.edit_block);

		var editor = this;

		this.block.find('h3').text('Редактирование комментария');
		this.block.find('div#comment_submit_buttons').html('<div id="edit_comment_submits"><input id="submit" type="submit" value="Сохранить" /><input id="cancel" type="submit" value="Отменить" /></div>');
		this.block.find('#cancel').bind('click', function(){editor.cancel.call(editor)});

		var select = this.block.find('select#oid');
		if (!select.length)
		{
			this.block.find('#add_comment_form').prepend('<div id="autor_id"><label for="oid">Автор:</label><select class="half" id="oid" name="oid"></select></div>');
			$('input[@type="hidden"]', this.block).find('input[@name="oid"]').remove();
		}

		editor.block.find('#autor_id').hide();
		select.empty();
		select.append('<option id="0">Я (автор поста)</option>');

		this.mode = 'edit';
		var options = {

			dataType:  'xml',
			beforeSubmit : function (formData, jqForm, options) { return editor.before_submit.call(editor, formData, jqForm, options)},
			success : function (responseText, statusText) { return editor.after_submit.call(editor, responseText, statusText)},
			url : this.comments_url + '/edit_comment_js_' + comment_id + '.html'
		};

		this.block.find('form').ajaxForm(options);
		this.block.block({ message: '<div id="post_comment" style="color: #ffffff; font-size: 16px; font-weight: bold">Ждите...</div>',  centerX : 0, centerY: 0, css : { border: '0px', backgroundColor : 'transparent' }});

		$.get(options.url, {}, function (xml)
				{
					editor.block.unblock();
					var status = $('comment', xml).find('status');
					if (parseInt(status.attr('code')) == 0)
					{
						var tmce = tinyMCE.get(editor.editor_id);
						if (tmce)
						{
							var data = $('comment', xml).find('content').text();
							editor.block.find('#text').val(data);
							tmce.setContent(data);
						}


						var dogs = $('comment', xml).find('dogs');
						if (dogs.length)
						{
							var sdid = 0;
							$('dog', dogs).each(function()
							{
								select.append('<option value="' + $(this).attr('id') + '">' + $(this).text() + '</option>');
								if ($(this).attr('selected') == 'true') sdid = parseInt($(this).attr('id'));
							});
							select.val(sdid);
							editor.block.find('#autor_id').show();
						} else
						{
							editor.block.find('#autor_id').hide();
						}

					} else
					{
						editor.cancel();
					}
				}
		);
        };

	this.after_edit = function(xml, statusText)
	{
		var status = $('comment', xml).find('status');
		if (parseInt(status.attr('code')) == 0)
		{
			// redirect to comment place if needed
			var comment_location = $('comment', xml).find('location').text();
			if (comment_location) this.redirect_if_needed(comment_location);

			var comment = $($('comment', xml).find('content').text());
			comment.hide();

			this.edit_block.after(comment);
			this.edit_block.remove();
			this.edit_block = null;
			comment.fadeIn('fast');

			this.place_to_end();
			this.comment();
		} else
		{
		        switch (parseInt(status.attr('code')))
			{
				default:
				case 100: // server error
				case 101: // access denied
				case 102: // not found
				{
					this.block.find('#text').after('<div class="error" id="text_err">' + status.text() + '</div>');
					break;
				}
		
				case 200: // too many links
				case 201: // bb-tags
				case 202: // content needed
				{
					this.block.find('#text').after('<div class="error" id="text_err">' + status.text() + '</div>');
					break;
				}
			}
		}
	};

	this.comment = function()
	{
		$('#add_comment_ctrl').show();

		this.block.find('h3').text('Добавление нового комментария');
		this.block.find('div#comment_submit_buttons').html('<input id="submit" type="submit" value="Написать" />');

		var select = this.block.find('select#oid');
		select.empty();
		select.append('<option id="0">Я</option>');

		var hd = false;
		for (var i in this.dogs)
		{
			hd = true;
			break;
		}

		if (hd)
		{
			for (var i in this.dogs)
			{
				select.append('<option value="' + i + '">' + this.dogs[i] + '</option>');
			}	

			this.block.find('#autor_id').show();
		} else
		{
			this.block.find('#autor_id').hide();
		}

		this.mode = 'comment';

		var editor = this;
		var options = {

			dataType:  'xml',
			beforeSubmit : function (formData, jqForm, options) { return editor.before_submit.call(editor, formData, jqForm, options)},
			success : function (responseText, statusText) { return editor.after_submit.call(editor, responseText, statusText)},
			url : this.comments_url + '/add_comment_js.html'
		};

		this.block.find('form').ajaxForm(options);
		this.block.find('#text').val('');
		var tmce = tinyMCE.get(this.editor_id);
		if (tmce) tmce.setContent('');
	};

	this.after_comment = function(xml, statusText)
	{
		var status = $('comment', xml).find('status');
		if (parseInt(status.attr('code')) == 0)
		{
			this.block.find('#text').val('');
			var tmce = tinyMCE.get(this.editor_id);
			if (tmce) tmce.setContent('');

			// redirect to comment place if needed
			var comment_location = $('comment', xml).find('location').text();
			if (comment_location) this.redirect_if_needed(comment_location);

			if ($('#comments_container').is('div') != true)
			{
				$('div.pagination').before((this.comments_header ? '<h2 class="m-top">Комментарии</h2>' : '') + '<div id="comments_container"></div>');
				$('#comments_container').bind('click', this.container_click_func);
			}

			var comment = $($('comment', xml).find('content').text());
			comment.hide();
			$('#comments_container').append(comment);
			comment.fadeIn('fast');
		} else
		{
		        switch (parseInt(status.attr('code')))
			{
				default:
				case 100: // server error
				case 101: // access denied
				case 102: // not found
				{
					this.block.find('#text').after('<div class="error" id="text_err">' + status.text() + '</div>');
					break;
				}
		
				case 200: // too many links
				case 201: // bb-tags
				case 202: // content needed
				{
					this.block.find('#text').after('<div class="error" id="text_err">' + status.text() + '</div>');
					break;
				}
			}
		}
	};

	this.cancel = function()
	{
		if (this.mode == 'edit')
		{
			if (this.edit_block != null)
			{
				this.edit_block.show();
				this.edit_block = null;
			}


			this.place_to_end();
			this.comment();
		}
	};

	this.redirect_if_needed = function(comment_location)
	{
		var document_location = String(document.location);
		var dl = document_location.indexOf('#');
		if (dl > 0) document_location = document_location.substring(0, dl);

		if (comment_location && (document_location != comment_location))
		{
			location.replace(comment_location);
			return;
		}
	};
};



var Comments =
{
	comments_url : '',
	comments_header : false,
	editor : null,

	init : function(comments_url, comments_header)
	{
		Comments.comments_url = comments_url;
		Comments.comments_header = comments_header;

		tinyMCE.init({
			mode : "exact",
			elements : "text",
			theme : "simple_ex",
			skin : "o2k7",
			skin_variant : "silver",
			language : "ru",
			plugins : "safari,inlinepopups,table,paste,fullscreen,emotions",

			relative_urls : false,

			content_css : "/css/editor.css",
			file_browser_callback : "openSwampyBrowser"
		});

		$(document).ready(
			function () 
			{
				$('#comment_id').css('margin-right', '0px');
				$('#comments_container').bind('click', Comments.container_click);

				Comments.editor = new comments_editor($('#comment_block'), 'text');
				Comments.editor.setup(Comments.comments_url, Comments.comments_header, Comments.container_click);
				Comments.editor.comment();
			}
		);
	},

	container_click : function(event)
	{
		var el = event.target;
		var id = $(el).attr('id'); 

		switch (id)
		{
			case 'delete_link':
			case 'delete_img':
			{
				event.preventDefault();
				Comments.editor.cancel();
				var alink = (id == 'delete_link') ? $(el) : $(el).parent();

				if (confirm('Вы точно хотите удалить этот комментарий ?'))
				{
					var href = alink.attr('href');
					href = href.replace('delete_comment', 'delete_comment_js');

					var block = alink.parent().parent().parent().parent();
					block.fadeOut('fast', function()
					{ 
						block.remove();
						$.get(href, {}, function(xml)
						{
							var status = $('comment', xml).find('status');
							if (parseInt(status.attr('code')) == 0)
							{
								var comment_location = $('comment', xml).find('location').text();
								if (comment_location) Comments.editor.redirect_if_needed(comment_location);
							}
						});
					});
				}
				break;
			}

			case 'edit_link':
			case 'edit_img':
			{
				event.preventDefault();
				Comments.editor.cancel();
				var alink = (id == 'edit_link') ? $(el) : $(el).parent();

				var block = alink.parent();
				while ((block.length != 0) && (block.attr('id').indexOf('post_block_') != 0)) 
				block = block.parent();

				var post_id = parseInt(block.attr('id').replace('post_block_', ''));
				Comments.editor.edit(post_id);
				break;
			}

			default:
			{
				break;
			}
		}
	}
};

var PM_Comments = {

	correspondence_id : 0,
	last_message_id : 0,
	fresh_timer : 0,

	init : function(corr_id)
	{
		PM_Comments.correspondence_id = corr_id;
		tinyMCE.init({
			mode : "exact",
			elements : "text",
			theme : "advanced",
			skin : "o2k7",
			skin_variant : "silver",
			language : "ru",
			plugins : "safari,inlinepopups,table,paste,fullscreen,emotions",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect,|,forecolor,backcolor",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,undo,redo,|,bullist,numlist,|,outdent,indent,blockquote,|,link,unlink,anchor,image,charmap,emotions,|,cleanup,code,fullscreen",
			theme_advanced_buttons3 : "",//tablecontrols,|,visualaid
			theme_advanced_buttons4 : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "",
			theme_advanced_path : false,
			theme_advanced_resizing : true,

			relative_urls : false,

			// Example content CSS (should be your site CSS)
			content_css : "/css/editor.css",
			file_browser_callback : "openSwampyBrowser"
		});

		$(document).ready(
			function () 
			{
				PM_Comments.last_message_id = PM_Comments.get_max_message_id();
				PM_Comments.init_form();
				PM_Comments.update_fresh_timer(true);
			}
		);
	},

	init_form : function()
	{
		var options = {
			beforeSubmit : PM_Comments.before_submit,
			success : PM_Comments.after_submit,
			dataType:  'xml',
			url : '/pm/cor_' + PM_Comments.correspondence_id + '/news_js_' + PM_Comments.last_message_id + '.html'
		};

		$('#new_message_form').ajaxForm(options);
	},

	before_submit : function(formData, jqForm, options)
	{
		var tmce = tinyMCE.get('text');
		var text = tmce.getContent();
		$('#text_err').remove();

		if (!text.length)
		{
			$('#text').after('<div class="error" id="text_err">Пожалуйста, введите текст сообщения.</div>');
			return false;
		}

		var links = text.match(/(<a[^>]*href=[^>]{1,}>)/gi);
		if ((links != null) && (links.length > 3))
		{
			$('#text').after('<div class="error" id="text_err">Пожалуйста, сократите количество гиперссылок до 3-х.</div>');
			return false;
		}

		if (text.match(/(\[url=http:\/\/)/gi) || text.match(/(\[url\].*?\[\/url\])/gi))
		{
			$('#text').after('<div class="error" id="text_err">На нашем сайте не поддерживаются гиперссылки в bb-тэгах.</div>');
			return false;
		}

		for (var i = 0, j = formData.length; i < j; i++)
		{
			if (formData[i].name == 'text')
			{
				formData[i].value = text;
				break;
			}
		}

		PM_Comments.update_fresh_timer(false);
		$('#new_message_block').block({ message: '<div id="post_comment" style="color: #ffffff; font-size: 16px; font-weight: bold">Ждите...</div>',  centerX : 0, centerY: 0, css : { border: '0px', backgroundColor : 'transparent' }});
		return true; 
	},

	after_submit : function(xml, statusText)
	{
		$('#new_message_block').unblock();
		PM_Comments.update_fresh_timer(true);

		if (statusText == 'success')
		{
			var status = $('state', xml).find('code');
			if (parseInt(status.attr('val')) == 0)
			{
				$('#text').val('');
				var tmce = tinyMCE.get('text');
				if (tmce) tmce.setContent('');
				PM_Comments.parse_answer(xml);
			} else
			{
			        switch (parseInt(status.attr('val')))
				{
					default:
					case 102: // not found
					{
						$('#text').after('<div class="error" id="text_err">' + status.text() + '</div>');
						break;
					}
			
					case 200: // too many links
					case 201: // bb-tags
					case 202: // content needed
					{
						$('#text').after('<div class="error" id="text_err">' + status.text() + '</div>');
						break;
					}
				}
			}
		} else
		{
			$('#text').after('<div class="error" id="text_err">Сервер временно недоступен</div>');
		}
	},

	get_max_message_id : function()
	{
		var lis = $('li.pm:last', $('#pm_messages_container'));
		if (lis.length)
		{
			var linka = lis.find('a[@name]');
			return parseInt(linka.attr('name'));
		}

		return 0;
	},

	update_fresh_timer : function(setup)
	{
		if (setup)
		{
			PM_Comments.fresh_timer = setTimeout(function()
			{
				PM_Comments.fresh_timer = 0;
				$.get('/pm/cor_' + PM_Comments.correspondence_id + '/news_js_' + PM_Comments.last_message_id + '.html', {}, function (xml)
				{
					PM_Comments.parse_answer(xml);
					PM_Comments.update_fresh_timer(true);
				});

			} , 5000);
		} else
		{
			clearTimeout(PM_Comments.fresh_timer);
			PM_Comments.fresh_timer = 0;
		}
	},

	parse_answer : function(xml)
	{
		var msg_container = $('#pm_messages_container');
		var old_messages = $('li.pm', msg_container);

		var messages = $('state', xml).find('messages');
		var new_messages = $('message', messages);

		var messages_display = 10;
		var eject = 0;

		if (messages_display - old_messages.length - new_messages.length < 0)
		{
			if (new_messages.length > messages_display)
			{
				eject = old_messages.length - 1;
			} else
			{
				eject = Math.abs(messages_display - new_messages.length - old_messages.length + 1);
			}
		}

		new_messages.each(function(i)
		{
			var new_item = $('<li class="pm">' + $(this).text() + '</li>');
			new_item.hide();

			if (eject)
			{
				var itd = $('li.pm:first', msg_container);
				itd.remove();
				eject --;
			}

			msg_container.append(new_item);
			new_item.fadeIn('fast');
		});

		PM_Comments.last_message_id = PM_Comments.get_max_message_id();
		PM_Comments.init_form();
	}
};