var EditLine = function() {

	this.form = null;
	
	this.targetEx = null;

	this.add_line = function(tg) {
		this.targetEx = tg;
		this._do(0);
	}

	this.edit_line = function(tg, id) {
		this.targetEx = tg;
		this._do(id);
	}

	this._do = function(id) {
		if (!this.form) {
			this.form = new Ext.form.BasicForm(this.targetEx.body, {
				errorReader: new Ext.form.XmlErrorReader(),
				waitMsgTarget: true
			});
			this.form.initEl(this.targetEx.body);
		}
		var default_text = '';
		var line_tree_node = null; // For editing only
		if (id) {
			line_tree_node = this.targetEx.getNodeById('line_' + id);
			if (!line_tree_node) {
				msg_error('Cannot find requested node (' + id + ')');
				return;
			}
			default_text = line_tree_node.text;
		}
		Ext.Msg.prompt(id ? 'Редактирование линии' : 'Новая линия', id ? 'Новое название:' : 'Название линии:', function(btn, text) {
			if (btn == 'ok' && text.trim()) {
				this.form.submit({
					params: {
						id: id,
						line_title: text,
						cour_id: this.targetEx.getCourId()
					},
					method: 'POST',
					waitMsg: 'Сохранение...',
					url: 'actions/line.save.xml.php',

					failure: function(form, action) {
						msg_error('Line was not saved (server error). Please, reload the page and try again');
					},
					success: function(form, action) {
						if (id) {
							//line_tree_node.setText(text);
							app.tree_panel.setLineTextById(id, text);
							app.tree_panel_out.setLineTextById(id, text);
						} else {
							var xml = form.errorReader.xmlData;
							var root = xml.documentElement || xml;
							var line_node = Ext.DomQuery.selectNode('line', root);
							if (line_node)
							{
								var line_id = line_node.getAttribute('id');
								var m_id 	= line_node.getAttribute('main_id');
								//dd(line_id + "_" + m_id);
								this.targetEx.getRootNode().appendChild(new Ext.tree.TreeNode({
									id: 'line_' + line_id,
									id_line: 'line_' + line_id,
									type: 'line',
									int_id: line_id,
									main_id: m_id,
									text: text,
									iconCls: 'iconFolder',
									cour_id: this.targetEx.getCourId(),
									leaf: false,
									allowChildren: false,
									tree_id: this.targetEx.id
								}));
							} else {
								msg_error('Line was not saved (line node was not received). Please, reload the page and try again');
							}
						}
					},
					scope: this
				});
			}
		}, this, false, default_text);
	}
}
