var EditForm = function(config) {
	this.config = config;
	
	this.targetEx = null;
}

EditForm.prototype = {

	_init: function() {
		/*this.htmleditor = new Ext.form.HtmlEditor({
		xtype: 'htmleditor',
		name: 'html_short',
		fieldLabel: 'Text',
		height: 210,
		anchor: '98%',
		frame: true,
		layout: 'fit',
		enableFont: false
		});*/

		this.htmleditor = new Ext.form.TextArea({
			id: 'cube_editor_text_area',
			xtype: 'textarea',
			name: 'html_short',
			fieldLabel: 'Текст',
			height: 210,
			anchor: '98%'
		});

		this.fckeditor = null;

		this.fs = new Ext.FormPanel({
			frame: true,
			region: 'center',
			labelAlign: 'top',
			labelWidth: 85,
			width: 340,
			waitMsgTarget: true,

			// configure how to read the XML Data
			reader: new Ext.data.XmlReader({
				record: 'cube',
				success: '@success'
			}, [
			'title', 'html_short'
			]),

			// reusable error reader class defined at the end of this file
			errorReader: new Ext.form.XmlErrorReader(),

			defaultType: 'textfield',

			items: [{
				fieldLabel: 'Заголовок кубика',
				name: 'title',
				width: '100%'
			}, this.htmleditor]
		});

		// simple button add
		/*this.fs.addButton('Load', function(){
		this.fs.getForm().load({url:'http://d/cour/ext/examples/form/xml-form.xml', waitMsg:'Загрузка'});
		}, this);*/

		// explicit add
		var submit = this.fs.addButton({
			text: 'Сохранить',
			disabled: true,
			handler: function() {
				var cube_id = this.cube_id;
				var line_id_for_addition = this.line_id_for_addition;
				var params = {cube_id: cube_id};
				if (cube_id == 0) {
					params.line_id = line_id_for_addition;
				}
				params.cour_id = this.targetEx.getCourId(); 
				// FCKEditor
				document.getElementById('cube_editor_text_area').value = FCKeditorAPI.GetInstance('cube_editor_text_area').GetXHTML();
				this.fs.getForm().submit({
					params: params,
					method: 'POST',
					url: 'actions/form.cube.save.xml.php',
					waitMsg: 'Сохранение...',
					failure: function(form, action) {
						//dd('failure');
						//dd(action.result);
					},
					success: function(form, action) {
						var xml = form.errorReader.xmlData;
						
						var root = xml.documentElement || xml;

						var ok_test = Ext.DomQuery.selectValue('cube ok_test', root);
						var id = Ext.DomQuery.selectValue('cube id', root);
						var link_id = Ext.DomQuery.selectValue('cube link_id', root);
						var title = Ext.DomQuery.selectValue('cube title', root);
						var artificial_title = Ext.DomQuery.selectValue('cube artificial_title', root);
						var html_short = Ext.DomQuery.selectValue('cube html_short', root);
						var links = Ext.DomQuery.select('cube links link', root);

						var need_hide_function = false;
						if (ok_test != 'true')
						{
							msg_error('System error is occured while saving this cube (id = ' + cube_id + '). Try to reload the page');
						}
						else
						{
							if (cube_id == 0 || app.panel.cubes_cache[cube_id])
							{
								need_hide_function = true;
							}
						}
						this.win.hide(this.targetEl, function() {
							if (need_hide_function)
							{
								if (cube_id == 0)
								{
									var line_tree_node = this.targetEx.getNodeById('line_' + line_id_for_addition);
									if (line_tree_node)
									{
										//dd('added ' + 'cube_link_' + link_id);
										line_tree_node.appendChild(new Ext.tree.TreeNode({
											id: 'cube_link_' + link_id,
											type: 'cube',
											int_id: id,
											link_id: link_id,
											line_id: line_id_for_addition,
											text: title,
											leaf: true,
											allowChildren: false,
											cour_id: this.targetEx.getCourId()
										}));
									} else {
										msg_error('Cube was added but was not shown (line ' + line_id_for_addition + ' could not be found). Please, reload the page');
									}
								}
								else
								{
									for (var i = 0; i < links.length; i++)
									{
										link_id = links[i].getAttribute('id');

										//this.targetEx.setCubeTextById(id, title);
										app.tree_panel.setCubeTextById(id, title);
										app.tree_panel_out.setCubeTextById(id, title);
									}
									app.panel.cubes_cache[cube_id].data.title = artificial_title == '0' ? title : '';
									app.panel.cubes_cache[cube_id].data.html_short = html_short;
									app.panel.resort_panel();
								}
							}
						}, this);
					},
					scope: this
				});
			},
			scope: this
		});

		// simple button add
		this.fs.addButton('Отмена', function(){
			this.win.hide(this.targetEl);
		}, this);

		this.fs.on({
			actioncomplete: {
				fn: function(form, action) {
					if (action.type == 'load') {
						// FCKEditor
						var xml = this.fs.reader.xmlData;
						var root = xml.documentElement || xml;
						var html_short = Ext.DomQuery.selectValue('html_short', root);
						//dd(html_short.length);
						//dd(root.childNodes[0].childNodes[1].childNodes[0].textContent.length);
						
						submit.enable();
						
						if (typeof(FCKeditorAPI) != 'undefined') {
							FCKeditorAPI.GetInstance('cube_editor_text_area').SetData(document.getElementById('cube_editor_text_area').value);
						}
					}
				},
				scope: this
			}
		});

		var cfg = {
			title: 'Edit cube',
			layout: 'border',
			minWidth: 500,
			minHeight: 300,
			modal: true,
			closeAction: 'hide',
			border: false,
			items: this.fs,
			/*buttons: [{
			id: 'ok-btn',
			text: 'OK',
			handler: this.doCallback,
			scope: this
			},{
			text: 'Cancel',
			handler: function(){ this.win.hide(); },
			scope: this
			}],*/
			keys: {
				key: 27, // Esc key
				handler: function(){ this.win.hide(this.targetEl); },
				scope: this
			},
			listeners: {
				show: function() {
					//$('.post embed').css('display', 'none');
					$('.post embed').css('visibility', 'hidden');
				},
				hide: function() {
					//$('.post embed').css('display', 'block');
					$('.post embed').css('visibility', 'visible');
				}
			}
		};
		Ext.apply(cfg, this.config);
		this.win = new Ext.Window(cfg);
	},

	_show_window: function(cube_id, line_id_for_addition) {
		this.win.setTitle(cube_id == 0 ? 'Новый кубик' : 'Редактирование кубика');
		
		this.win.show(this.targetEl);
		/* Firefox fix - BEGIN */
		$('.x-toolbar.x-small-editor').css('width', 'auto');
		$('.x-toolbar.x-small-editor').css('height', 'auto');
		$('#x-form-el-html_short iframe').css('height', '220');
		/* Firefox fix - END */
		/* Tree toolbar compatibility fix - BEGIN */
		$('.x-form-element .x-form-text').css('width', '100%');
		$('.x-form-element .x-form-text').css('height', '22px');
		/* Tree toolbar compatibility fix - END */
		this.animateTarget = this.targetEl;
		this.fs.getForm().load({
			method: 'GET',
			url: 'actions/form.cube.get.xml.php?cube=' + this.cube_id,
			waitMsg: 'Загрузка',
			params: {
				cour_id: this.targetEx.getCourId()
			},
			failure: function(form, action) {
				msg_error('Requested object (id = ' + this.cube_id + ') does not exist on the server');
				this.win.hide(this.targetEl);
			},
			scope: this
		});
		return true;
	},

	show : function(trg, cube_id, line_id_for_addition) {
		this.targetEx = trg;
		//this.targetEl = Ext.get('cube_id_' + cube_id);
		this.targetEl = this.targetEx.getNodeById('cube_link_' + cube_id);
		this.cube_id = cube_id;
		this.line_id_for_addition = line_id_for_addition;
		
		if (cube_id == 0 && !line_id_for_addition) {
			Ext.Msg.alert('Внимание', 'Пожалуйста, сначала выберите линию');
			return false;
		}

		if (!this.win) {
			this._init();
			var th = this;
			$.getScript("fckeditor/fckeditor.js", function(data, textStatus) {
				th._show_window(cube_id, line_id_for_addition);

				th.fckeditor = new FCKeditor('cube_editor_text_area');
				th.fckeditor.BasePath = 'fckeditor/';
				//oFCKeditor.Config.EditorAreaCSS = 'css/main.css';
				//oFCKeditor.Config.BaseHref = '<xsl:value-of select="$static_prefix" />/';
				//th.fckeditor.Config['SkinPath'] = 'skins/office2003/';
				//th.fckeditor.Config['SkinDialogCSS'] = '../editor/skins/office2003/fck_dialog.css';
				th.fckeditor.ToolbarSet = 'IntCMF';
				th.fckeditor.Height = '320';
				th.fckeditor.ReplaceTextarea();
			});
		} else {
			this._show_window(cube_id, line_id_for_addition);
		}
	}

	/*doCallback : function() {
	var selNode = this.view.getSelectedNodes()[0];
	var callback = this.callback;
	var lookup = this.lookup;
	this.win.hide(this.animateTarget, function() {
	if(selNode && callback){
	var data = lookup[selNode.id];
	callback(data);
	}
	});
	}*/
};

// A reusable error reader class for XML forms
Ext.form.XmlErrorReader = function(){
	Ext.form.XmlErrorReader.superclass.constructor.call(this, {
		record : 'field',
		success: '@success'
	}, [
	'id', 'msg'
	]
	);
};
Ext.extend(Ext.form.XmlErrorReader, Ext.data.XmlReader);
