/* MESSENGER
***************************************************************************************************/
var Messenger = Class.create(
{
// Необхідно залишити тільки контейнер
	initialize: function(container)
	{
		this.container = $(container);
		this.types = {error: 0, warning: 1, message: 2};
		this.msgStyles = ['msg-error', 'msg-warning', 'msg-message'];
		this.hasErrors = false;
		this.hasWarnings = false;
	},

	show: function()
	{
		this.container.setStyle({display: 'block'});
	},

	hide: function()
	{
		this.container.setStyle({display: "none"});
	},

	addMessages: function(messages)
	{
		var messagesText = "";
		for (var i=0; i<messages.length; i++){
			messagesText += '<p class=\'' + this.msgStyles[messages[i][1]] + '\'>' + messages[i][0] + '</p>';
			if(messages[i][1] == 0){
				this.hasErrors = true;
				this.container.fire('Messenger:throwError');
			} else if(messages[i][1] == 1) {
				this.hasWarnings = true;
				this.container.fire('Messenger:throwWarning');
			}
		}
		this.container.update(messagesText);
	},

	addMessage: function(text, messageType)
	{
		text += '<p class=\'' + this.msgStyles[messageType] + '\'>' + text + '</p>';
		if(messageType == 0){
			this.hasErrors = true;
			this.container.fire('Messenger:throwError');
		} else if(messageType == 1) {
			this.hasWarnings = true;
			this.container.fire('Messenger:throwWarning');
		}
		this.container.update(messagesText);
	}

});
CtPage.registerScript("Messenger");

var ElementsMessenger = Class.create(Messenger,
{

	show: function()
	{
		this.container.setStyle({display: 'block'});
	},

	hide: function()
	{
		this.container.setStyle({display: "none"});
	},

	addMessages: function(messages)
	{
		var messagesText = "";
		for (var key in messages){
			if(Object.isString(messages[key])){
				messagesText += '<p class=\'' + this.msgStyles[1] + '\'>' + messages[key] + '</p>';
				this.container.fire('Messenger:throwError');
			} else {
				messagesText += '<p class=\'' + this.msgStyles[messages[key][1]] + '\'>' + messages[key][0] + '</p>';
				if(messages[key][1] == 0){
					this.hasErrors = true;
					this.container.fire('Messenger:throwError');
				} else if(messages[key][1] == 1) {
					this.hasWarnings = true;
					this.container.fire('Messenger:throwWarning');
				}
			}
		}
		this.container.update(messagesText);
	}
});
CtPage.registerScript("ElementsMessenger");


/* UPDATE TRANSACTIONS COUNTER
***************************************************************************************************/
var UpdateTransactionsManager = Class.create({
	initialize: function(element)
	{
		this.element = element;
		this.openTransactions = new Hash();
		this.hasActive = false;
	},

	_complete: function()
	{
		this.element.fire('UpdateTransactionsManager:transactionsComplete');
	},

	add: function(id, value)
	{
		this.openTransactions.set(id, value);
		this.hasActive = true;
		//this.element.fire('UpdateTransactionsManager:startTransaction');
	},

	remove: function(id)
	{
		this.openTransactions.unset(id);
		this.element.fire('UpdateTransactionsManager:finishTransaction', {id: id});
		if(this.openTransactions.keys().length == 0){
			this.hasActive = false;
			this._complete();
		}
	},

	changeElement: function(element)
	{
		this.element = $(element.id);
	}
});
CtPage.registerScript("UpdateTransactionsManager");

/* COMMENT LINE
***************************************************************************************************/
var CommentLine = Class.create(
{
//
// Constructor
//
	initialize: function(ident, idParent, addActionUrl, getPageActionUrl, pagerUrlVarName, additionPermission)
	{
	//{ Fields
		this.container = $(ident + 'comment-line-container');
		this.ident = this.container.id;
		this.htmlIdent = ident;
		this.idParent = idParent;
		this.additionPermission = additionPermission;

		this.addActionUrl = addActionUrl;
		this.getPageActionUrl = getPageActionUrl;
		this.pagerUrlVarName = pagerUrlVarName;
		this.content = "";

		this.transactions = new RequestTransactionsManager(this.container);
		//this._messenger = new Messenger(this.container, 'comment-line-messages');
	//}

	//{ Objects
		//{ Add form
			this._addFormContainer = $(this.htmlIdent + "comment-line-addform");
			if(additionPermission == 1){
				this._addForm = new CommentLineAddForm(this, this._addFormContainer, this.addActionUrl, new Hash({id_parent: this.idParent}));
			// Events
				Event.observe(this._addFormContainer, "AddForm:addButtonClick", function(){this._onAddButtonClick()}.bind(this));
				Event.observe(this._addFormContainer, "AddForm:sendRequest", function(e){this.transactions.add()}.bind(this));
				Event.observe(this._addFormContainer, "AddForm:receiveResponse", function(e){
					this.transactions.remove();
					this.refresh(this._addForm.responseText);
				}.bind(this));
			}
		//}

		//{ Comments
			this._comments =  new Hash();
			this.updations = new RequestTransactionsManager(this.container);
			this.editedComments = new UpdateTransactionsManager(this.container);

			this._registerComments();
		//}

		//{ Pager
			var createPagerHandler = function(){
				var container = $(this.htmlIdent + "-commentline-pager");
				if (container) {
					this._pager = new Pager(this, container, this.getPageActionUrl, new Hash({id_parent: this.idParent}), pagerUrlVarName);
					this._observeToPager();
				}
			}.bind(this);
			CtPage.scriptIsReady("Pager", createPagerHandler);
		//}
	//}
	// //{ Observing to events
		// //Transactions
		// Event.observe(this.container, 'RequestTransactionsManager:transactionsComplete', function(){/*this._messenger.hide(); this.unblock()*/}.bind(this));
		// Event.observe(this.container, 'RequestTransactionsManager:startTransaction', function(){ /*this._messenger.addLoadingMessage(); this.block();*/}.bind(this));
	// //}

	},
//
//{  INNER METHODS
//
//{ Creating
	_registerComments: function()
	{
		var destroy = function(pair){
			pair.value.destroy();
		}.bind(this);
		this._comments.each(destroy);

		this._comments = new Hash();
		var containers = $$("div#" + this.htmlIdent + "comment-line-container div.commentline-item");
		var id;
		var commentParams;
		for(var i=0; i<containers.length; i++){
			id = containers[i].id.replace(this.htmlIdent + "commentline-item", "");
			commentParams = eval(containers[i].readAttribute('rel'));
			containers[i].writeAttribute('rel', null);
			if (commentParams.permissions.edition == 1 || commentParams.permissions.deletion == 1) {
				this._comments.set(id, new CommentLineComment(this, id, containers[i], commentParams.editActionUrl, commentParams.deleteActionUrl, new Hash({id_parent: this.idParent}), commentParams.permissions));
				Event.observe(containers[i], "Comment:open", function(e){this.editedComments.add(e.memo.comment.id, e.memo.comment)}.bind(this));
				Event.observe(containers[i], "Comment:finishEdition", function(e){this.editedComments.remove(e.memo.comment.id)}.bind(this));
				Event.observe(containers[i], "Comment:receiveResponse", function(e){
					this.updations.remove();
					if(e.memo.comment.isOpened){
						this.editedComments.add(e.memo.comment.id, e.memo.comment);
					}
					this.refresh(e.memo.comment.responseText);
				}.bind(this));
				Event.observe(containers[i], "Comment:sendRequest", function(e){
					this.updations.add();
					this.editedComments.remove(e.memo.comment.id);
				}.bind(this));
			}
		}
	},
//}
//{ Blocking
	block: function()
	{
		return false;
	},

	unblock: function()
	{
		return false;
	},

	refresh: function(content)
	{
		this.content = content;
		if(this.transactions.hasActive || this.updations.hasActive || this.editedComments.hasActive){
			Event.observe(this.container,'RequestTransactionsManager:transactionsComplete', this._refresh);
			Event.observe(this.container,'UpdateTransactionsManager:transactionsComplete', this._refresh);
			return false;
		} else {
			this._refresh();
			return true;
		}
	},

	_blockComments: function()
	{
		if(this._comments != null){
			var blockCommentHandler = function(item){
				item.value.block();
			};
			this._comments.each(blockCommentHandler);
		}
	},
//}

//{ User requests
	_requestForSavingData: function()
	{
		if(this.editedComments.hasActive){
			var userConfirm = confirm("Comment line has not saved data.\n Do you want to save it?");
			if (userConfirm){
				this._saveOpenedComments();
			} else {
				return false;
			}
		}
		return true;
	},
//}

//{ Data
	_saveOpenedComments: function()
	{
		var saveHandler = function(item){
			item.value.save();
		};

		this.editedComments.openTransactions.each(saveHandler);
	},

	_refresh: function()
	{
		Event.stopObserving(this.container,'RequestTransactionsManager:transactionsComplete', this._refresh);
		Event.stopObserving(this.container,'UpdateTransactionsManager:transactionsComplete', this._refresh);
		this.container = $(this.ident);
		this.container.replace(this.content);
		this._registerComments();

        var refreshPager = function(){
			var container = this.htmlIdent + "-commentline-pager";
			if ($(container)) {
				if (!this._pager) {
					this._pager = new Pager(this, container, this.getPageActionUrl, new Hash({id_parent: this.idParent}), this.pagerUrlVarName);
				} else {
					this._pager.refresh();
				}
				this._observeToPager();
			}
		}.bind(this);

		this.updations.changeElement(this.container);
		this.transactions.changeElement(this.container);
		this.editedComments.changeElement(this.container);

		CtPage.scriptIsReady("Pager", refreshPager);
	},
//}
//}

//
//{ Events handlers
//
	//{ Page button click
	_observeToPager: function()
	{
		Event.observe(this._pager.container, 'Pager:buttonClick', function(e){
			this._onPagerButtonClick()}.bind(this));
		Event.observe(this._pager.container, 'Pager:sendRequest', function(e){
			this.transactions.add();
			// this._messenger.addLoadingMessage();
		}.bind(this));
		Event.observe(this._pager.container, 'Pager:receiveResponse', function(e){
			this.transactions.remove();
			if(this.refresh(this._pager.content)){
				Element.scrollTo(this.container.id);
			}
		}.bind(this));
		Event.observe(this._pager.container, 'Pager:transactionsComplete', function(){
			// this._messenger.hide();
		}.bind(this));
	},

	_onPagerButtonClick: function()
	{
		if(this.editedComments.hasActive && this._requestForSavingData()){
			var getPageHandler = function(){
				Event.stopObserving(this.container,'UpdateTransactionsManager:transactionsComplete', getPageHandler);
				this._pager.sendRequest();
				this._blockComments();
			}.bind(this);
			Event.observe(this.container,'UpdateTransactionsManager:transactionsComplete', getPageHandler);
		} else {
			this._pager.sendRequest();
			// this._blockComments();
		}
	},
	//}
	//{ Add button click
	_onAddButtonClick: function()
	{
		this._addForm.addComment();
	},
	_onAddFormReceiveResponse: function()
	{
		this.transactions.remove();
		this.refresh(this._addForm.responseText);
	}
	//}
//}
});
CtPage.registerScript("CommentLine");

/* COMMENTLINE ADDFORM
***************************************************************************************************/
var CommentLineAddForm = Class.create(
{
//{ Constructor
	initialize: function(owner, container, addRequestUrl, requestParams)
	{
		this.owner = owner;
		this.container = container;
		this.addRequestUrl = addRequestUrl;
		this.params = requestParams;
		this.responseText = null;
		this.htmlIdent = owner.htmlIdent;
		this.form = $(this.container.id +"-form");

		this._messenger = new Messenger($(this.htmlIdent + 'discuss-form-messages'));
		this._messengerText = new ElementsMessenger($(this.htmlIdent + 'discuss-form-messages-text'));
		this._loader = $(this.htmlIdent + "comment-line-add-loader");
	//{ Controls

		this._addButton = pageControlsManager.getControl($(this.htmlIdent + "comment-line-add-button"));

		this._textarea = $(this.htmlIdent + "comment-line-addform-form-text");
		this._fbPostCheckbox = $(this.htmlIdent + "_fb_post");
		if (Object.isElement(this._fbPostCheckbox)) {
			this._fbPostPrevState = this._fbPostCheckbox.checked;
			this._fbPostPermission = this._fbPostCheckbox.checked;
			var initFbFunc = function() {
				FB.Event.subscribe('auth.statusChange', function(response) {
					if (FB.getSession()) {
						FB.api({method: 'fql.query', query: 'SELECT publish_stream FROM permissions WHERE uid = "' + FB.getSession().uid + '"'}, function(response) {
							if (!Object.isArray(response) || response.length < 1) {
								return;
							}

							this._fbPostPermission = !!response[0].publish_stream;
						}.bind(this));
					}
				});
			};
			if (window.fbLoaded) {
				initFbFunc();
			} else {
				var fbWaitFunc = function() {
					if (window.fbLoaded) {
						initFbFunc();
					} else {
						setTimeout(fbWaitFunc, 1000);
					}
				};
				setTimeout(fbWaitFunc, 1000);
			}

			Event.observe(this._fbPostCheckbox, 'click', this._fbPostChangeState.bindAsEventListener(this));
		}
	// //}
	//{ Observing
		Event.observe(this._addButton.element, 'Control:click', function(e){ this._onAddButtonClick() }.bind(this));
	//}
	},
//}
//{ Public methods
	block: function()
	{
		// this._editor.disable();
	},

	unblock: function()
	{
		this._addButton.setStatus(this._addButton.statuses.enabled);
		// this._editor.enable();
	},

	hide: function()
	{
		this.container.hide();
	},

	show: function()
	{
		this.container.show();
	},

//{ Requests
	//{ Add comment
	addComment: function()
	{
		// this._getEditor();
		// this.block();
		this._loader.setStyle({display: 'block'});
		this._messenger.hasErrors = false;
		this._messenger.hide();
		this._messengerText.hide();

		var onSuccessHandler = function(transport, json) {
			this._loader.setStyle({display: 'none'});
			if (json == null) {
				showFatalError(transport.responseText);
				return;
			} else {
				if(json.messages.header.length != 0) {
					this._messenger.addMessages(json.messages.header);
					if(this._messenger.hasErrors){
						this._messenger.show();
					} else {
						this._messenger.hide();
						this._textarea.value = "";
					}

				}
				if(json.messages.elements != null) {
					this._messengerText.addMessages(json.messages.elements.text);
					this._messengerText.show();
				}
			}
			this.responseText = transport.responseText;
			this.unblock();
			this.container.fire("AddForm:receiveResponse", {comment: this});
		}.bind(this);


		this.params = this.form.serialize(true);
		this.container.fire("AddForm:sendRequest");
		new Ajax.Request(this.addRequestUrl, {
			parameters: Object.toQueryString(this.params),
			onSuccess: onSuccessHandler,
			onFailure: function(){
				this.unblock();
				this.container.fire("AddForm:receiveResponse", {comment: this});
				alert("Cannot connect to server. Please check your connection settings.");
			}.bind(this)
		});
	},
	//}
//}
//}

//{ Private methods
	_onAddButtonClick: function()
	{
		this.container.fire("AddForm:addButtonClick", {comment: this});
		this._addButton.setStatus(this._addButton.statuses.active);
	},

	_fbPostChangeState: function() {
		var currentState = this._fbPostCheckbox.checked;
		if (this._fbPostPrevState == currentState || !currentState || !FB.getSession()) {
			this._fbPostPrevState = currentState;
			return;
		}

		this._fbPostPrevState = currentState;

		if (!this._fbPostPermission && window.fbLoaded) {
			FB.login(function(response) {
				this._fbPostCheckbox.checked = ('perms' in response && Object.isString(response.perms) && response.perms.search('publish_stream') != -1);
				this._fbPostPermission = this._fbPostPrevState = this._fbPostCheckbox.checked;
			}.bind(this), {perms: 'publish_stream'});
		}
	}
//}
});
CtPage.registerScript("CommentLineAddForm");

/* COMMENTLINE COMMENT
***************************************************************************************************/
var CommentLineComment = Class.create(
{
//{ Constructor
	initialize: function(owner, id, container, updateRequestUrl, deleteRequestUrl, requestParams, permissions)
	{
		this.owner = owner;
		this.container = container;
		this.updateRequestUrl = updateRequestUrl;
		this.deleteRequestUrl = deleteRequestUrl;
		this.params = requestParams;
		this.responseText = null;
		this.htmlIdent = owner.htmlIdent;
		this.id = id;
		this.isOpened = false;
		this.permissions = permissions;

		this._messenger = new Messenger(this.container, 'commentline-item-messages' + id);

		this._activeButton = null;
		this._controls = new Array();
		this._onFailureHandler = owner._onFailureHandler;
		this._editor = null;

	//{ Controls
		this._createForm();
		this._createDeleteButton();
	//}
	},
//}
//{ Public methods
	block: function()
	{
		this._deleteButton.setStatus(this._deleteButton.statuses.disabled);
	},

	unblock: function()
	{
		this._deleteButton.setStatus(this._deleteButton.statuses.enabled);
	},

	hide: function()
	{
		this.container.hide();
	},

	show: function()
	{
		this.container.show();
	},

	save: function()
	{
		if(this.permissions.edition == 1){
			this._editForm.save();
		}
	},


	destroy: function()
	{
		pageControlsManager.destroyControls(this._deleteButton);

		if(this.permissions.edition == 1){
			this._editFormDataSource = null;
			this._editForm.destroy();
		}
	},

	refresh: function()
	{
		pageControlsManager.destroyControls(this._deleteButton);
		this._createDeleteButton();

		if(this.permissions.edition == 1){
			this._editFormDataSource.refresh();
			this._editForm.refresh();
		}
	},

//{ Requests
	//{ Delete comment
	deleteComment: function()
	{
		//this._messenger.addMessage("Выполняется удаление");
		//this.messenger.show();
		this._deleteButton.setStatus(this._deleteButton.statuses.active);
		this.hide();

		var onSuccessHandler = function(transport, json) {
			if (json == null) {
				showFatalError(transport.responseText);
				return;
			} else if(json.messages.length != 0) {
//повідомлення при видалені можуть виникнути тоді коли буде якимось чином порушено цілістність бази даних а також коли на відповідний запис буде накладено заборону
				// this._messenger.addMessages(json.messages);
				// if(messenger.hasErrors){
					// messenger.show();
					// this._showComment(idComment);
				// }
			}
			this.responseText = transport.responseText;
			this.container.fire("Comment:receiveResponse", {comment: this});
		}.bind(this);

		var params = this.params;
		params.set('id_comment', this.id);
		this.container.fire("Comment:sendRequest", {comment: this});
		new Ajax.Request(this.deleteRequestUrl, {
			parameters: params.toQueryString(),
			onSuccess: onSuccessHandler,
			onFailure: function(){
				this.container.fire("Comment:receiveResponse", {comment: this});
				this._onFailureHandler();
			}
		});
	},
	//}
//}
//}

//{ Private methods
	_createForm: function()
	{
		if(this.permissions.edition == 1){
			this._editFormDataSource = new CommentLineEditFormDatasource($(this.container.id +"data"));
			this._editForm = new CommentLineEditForm($(this.container.id +"editform"), this.updateRequestUrl, this._editFormDataSource, this.container.id +"action");
			Event.observe(this._editForm.container, 'EditForm:startEdition', function(e){
				this.isOpened = true;
				this.container.fire("Comment:open", {comment: this});
			}.bind(this));
			Event.observe(this._editForm.container, 'EditForm:finishEdition', function(e){
				this.isOpened = false;
				this.container.fire("Comment:finishEdition", {comment: this});
			}.bind(this));
			Event.observe(this._editForm.container, 'EditForm:sendRequest', function(e){
				this.container.fire("Comment:sendRequest", {comment: this});
				this.block(); }.bind(this));
			Event.observe(this._editForm.container, 'EditForm:receiveResponse', function(e){
				this.responseText = e.memo.comment.responseText;
				this.unblock();
				this.container.fire("Comment:receiveResponse", {comment: this});
			}.bind(this));
		}
	},

	_createDeleteButton: function()
	{
		if(this.permissions.deletion == 1){
			this._deleteButton = pageControlsManager.getControl($(this.htmlIdent + "commentline-item-button-delete" + this.id));
			this._deleteButton.setStatus(this._deleteButton.statuses.enabled);
			Event.observe(this._deleteButton.element, 'Control:click', function(e){ this._onDeleteButtonClick() }.bind(this));
		}
	},

	_onDeleteButtonClick: function()
	{
		var userConfirm = confirm("Do you really want to delete this comment?");
		if (userConfirm){
			this.container.fire("Comment:delete", {comment: this});
			this.deleteComment();
		}
	}
//}
});
CtPage.registerScript("CommentLineComment");


/* COMMENTLINE EDIT FORM DATA SOURCE
***************************************************************************************************/
var CommentLineEditFormDatasource = Class.create(
{
//{ Constructor
	initialize: function(container)
	{
		if(!Object.isElement(container)){
			throw "Incorrect parametr passed";
		}
		this.container = container;
		this.ident = container.id;

		this._registerElements();
	},
//}
//{ Public methods
	getData: function()
	{
		var data = new Object();
		for(var key in this.fields){
			data[key] = this.fields[key].innerHTML.strip();
		}

		return data;
	},

	setData: function(data)
	{
		for(var key in data){
			if(typeof(this.fields[key]) != "undefined"){
				this.fields[key].update(data[key]);
			}
		}
	},

	hide: function()
	{
		this.container.hide();
	},

	show: function()
	{
		this.container.show();
	},

	refresh: function()
	{
		this.container = $(this.ident);
		this._registerElements();
	},
//}
//{ Private methods
	_registerElements: function()
	{
		this.fields = new Object();

		var elements = this.container.select("div.data");
		for(var i=0; i<elements.length; i++){
			this.fields[elements[i].id.replace(this.container.id +"_", "")] = elements[i];
		}
	}
//}
});
CtPage.registerScript("CommentLineEditFormDatasource");


/* COMMENTLINE EDIT FORM
***************************************************************************************************/
var CommentLineEditForm = Class.create(
{
//{ Constructor
	initialize: function(container, requestUrl, dataSourceContainer, controlsContainerId)
	{
		this.container = container;
		this.ident = container.id;
		this.controlsContainerId = controlsContainerId;
		this.requestUrl = requestUrl;
		this.responseText = null;
		this.form = null;
		this.isRendered = false;
		this.isOpened = false;
		this.dataSourceContainer = dataSourceContainer;

		this._messenger = null;
		this._messengerText = null;
	//{ Controls
		this._registerControls();
	//}

	//{ Template
		this.template = "<div id=\"#{containerId}-messages\" class=\"comment-line-messages form-messages\"></div></div><form id=\"#{containerId}-form\" name=\"#{containerId}discussform\"><input type=\"text\" name=\"#{key}\" class=\"hidden\" value=\"#{id}\"><input type=\"text\" name=\"#{parentKey}\" class=\"hidden\" value=\"#{id_parent}\"><div class=\"form-textarea\"><textarea name=\"text\" id=\"#{containerId}-addform-form-text\" maxlength=\"1000\">#{text}</textarea><div id=\"#{containerId}-addform-form-text_counter\" class = \"textarea_counter\"><span>1000</span></div></div><div id=\"#{containerId}-messages-text\" class=\"comment-line-messages form-messages\"></div></form>";
	//}
	},
//}
//{ Public methods
	block: function()
	{
		if(this.isOpened){
			this._cancelButton.setStatus(this._cancelButton.statuses.disabled);
			this._updateButton.setStatus(this._updateButton.statuses.disabled);
		} else {
			this._editButton.setStatus(this._editButton.statuses.disabled);
		}
	},

	unblock: function()
	{
		if(this.isOpened){
			this._cancelButton.setStatus(this._cancelButton.statuses.enabled);
			this._updateButton.setStatus(this._updateButton.statuses.enabled);
		} else {
			this._editButton.setStatus(this._editButton.statuses.enabled);
		}
	},

	hide: function()
	{
		this.container.hide();
	},

	show: function()
	{
		this.container.show();
	},

	save: function()
	{
		this.sendRequest();
	},

	refresh: function()
	{
		this.container = $(this.ident);
		this.destroy();

		this._registerControls();
	},

	destroy: function()
	{
		pageControlsManager.destroyControls(this._editButton);
		pageControlsManager.destroyControls(this._cancelButton);
		pageControlsManager.destroyControls(this._updateButton);
	},

//{ Requests
	//{ Add comment
	sendRequest: function()
	{
		this._cancelButton.setStatus(this._cancelButton.statuses.disabled);
		this._updateButton.setStatus(this._updateButton.statuses.active);

		this._loader.setStyle({display: 'block'});
		this._messenger.hide();
		this._messengerText.hide();

		var onSuccessHandler = function(transport, json) {
			this._loader.setStyle({display: 'none'});
			if (json == null) {
				showFatalError(transport.responseText);
				return;
			} else {
				if(json.messages.header.length != 0) {
					this._messenger.addMessages(json.messages.header);
					if(!this._messenger.hasErrors){
						this._messenger.hide();
						this._closeForm();
						this.dataSourceContainer.setData(this.form.serialize(true));
					} else {
						this.unblock();
						this._messenger.show();
					}
				} else {
					this._closeForm();
				}
				if(json.messages.elements != null) {
					this._messengerText.addMessages(json.messages.elements.text);
					this._messengerText.show();
				}
			}

			this.responseText = transport.responseText;
			this.unblock();
			this.container.fire("EditForm:receiveResponse", {comment: this});
		}.bind(this);


		this.params = this.form.serialize(true);
		this.container.fire("EditForm:sendRequest");
		new Ajax.Request(this.requestUrl, {
			parameters: Object.toQueryString(this.params),
			onSuccess: onSuccessHandler,
			onFailure: function(){
				this.unblock();
				this.container.fire("EditForm:receiveResponse", {comment: this});
				alert("Cannot connect to server. Please check your connection settings.");
			}.bind(this)
		});
	},
	//}
//}
//}

//{ Private methods
	_onEditButtonClick: function()
	{
		this.container.fire("EditForm:open", {EditForm: this});
		this._editButton.setStatus(this._editButton.statuses.active);
		this._renderForm();
		this.dataSourceContainer.hide();
		this.show();
	},

	_onCancelButtonClick: function()
	{
		this.container.fire("EditForm:cancel", {EditForm: this});
		this._cancelButton.setStatus(this._cancelButton.statuses.active);
		this._closeForm();
	},

	_onUpdateButtonClick: function()
	{
		this.container.fire("EditForm:submit", {EditForm: this});
		this.sendRequest();
	},

	_renderForm: function()
	{
		var templateData = this.dataSourceContainer.getData();
		templateData.text = templateData.text.replace(/<br\s*\/{0,1}>\s*/gi, "\n");
		// e(templateData.text);
		templateData.containerId = this.container.id;

		var template = new Template(this.template);

		this.container.update(template.evaluate(templateData));

		var textarea = this.container.down("textarea");
		var newHeight = this.dataSourceContainer.container.getDimensions().height;

		if (newHeight > parseInt(textarea.getStyle('height'))) {
			textarea.setStyle({height: newHeight + "px"});
		}

		this.form = $(this.container.id +"-form");

		//{ Create textarea object
			CtPage.scriptIsReady("FormTextarea", this._createTextareaElement.bind(this));
		//}
		this._messenger = new Messenger($(this.container.id +'-messages'));
		this._messengerText = new ElementsMessenger($(this.container.id +'-messages-text'));
		this._loader = $(this.container.id +'-loader');

		this.isOpened = true;
		this._editButton.setStatus(this._editButton.statuses.hidden);
		this._updateButton.setStatus(this._updateButton.statuses.enabled);
		this._cancelButton.setStatus(this._cancelButton.statuses.enabled);

		this.container.fire("EditForm:startEdition", {EditForm: this});
	},

	_closeForm: function()
	{
		this.isOpened = false;
		this._messenger.hide();
		this._editButton.setStatus(this._editButton.statuses.enabled);
		this._cancelButton.setStatus(this._cancelButton.statuses.hidden);
		this._updateButton.setStatus(this._updateButton.statuses.hidden);

		this.hide();
		this.dataSourceContainer.show();
		this.container.fire("EditForm:finishEdition", {EditForm: this});
	},

	_registerControls: function()
	{
		this._editButton = pageControlsManager.getControl(this.controlsContainerId + "-edit");
		this._editButton.setStatus(this._editButton.statuses.enabled);

		this._cancelButton = pageControlsManager.getControl(this.controlsContainerId + "-cancel");
		this._cancelButton.element.removeClassName('hidden');
		this._cancelButton.setStatus(this._cancelButton.statuses.hidden);

		this._updateButton = pageControlsManager.getControl(this.controlsContainerId + "-update");
		this._updateButton.element.removeClassName('hidden');
		this._updateButton.setStatus(this._updateButton.statuses.hidden);

		Event.observe(this._editButton.element, 'Control:click', function(e){ this._onEditButtonClick() }.bind(this));
		Event.observe(this._cancelButton.element, 'Control:click', function(e){ this._onCancelButtonClick() }.bind(this));
		Event.observe(this._updateButton.element, 'Control:click', function(e){ this._onUpdateButtonClick() }.bind(this));
	},


	//{ Temporary methods
	_createTextareaElement: function()
	{
		this.textarea = new FormTextarea($(this.container.id +"-addform-form-text"), this.container.id +"-addform-form-text");
	}
	//}
//}
});
CtPage.registerScript("CommentLineEditForm");

