/////////////////////////////////////////////////////////////////////////////
//////  Ф о р м а  д о б а в л е н и я / р е д а к т и р о в а н и я  ///////
var CSrvAddEdt = Class.create();
CSrvAddEdt.prototype = {
	initialize: function(content, subUrl, recId, container, options) {
		this.content = content;
		this.subUrl = subUrl;
		this.recId = recId;
		this.container = container;
		this.onLoad = this.setEvents;
		
		if(typeof(options)!='undefined') {
			if (typeof(options['redirectUrl']) != 'undefined') this.editorOptions['redirectUrl'] = options['redirectUrl'];
			if (typeof(options['redirectAfterAdd'])!='undefined') this.editorOptions['redirectAfterAdd'] = options['redirectAfterAdd'];
			if (typeof(options['redirectAfterUpdate'])!='undefined') this.editorOptions['redirectAfterUpdate'] = options['redirectAfterUpdate'];
		}
	},//---------------------------------------------------------------------
	
	// Устанавливает события после загрузки контента
	setEvents: function(t) {
		if(t) this.cnt.innerHTML = t.responseText;
		
		var obj = this;
		this.form = $(this.content+'Form-'+this.recId);
		this.btnApply = $(this.content+'ApplyBtn-'+this.recId);
		this.btnReset = $(this.content+'ResetBtn-'+this.recId);
		this.msg = $(this.content+'Msg-'+this.recId);
		
		if(!this.cnt && this.container) this.cnt = $(this.container);
		if(typeof(this.root)=='undefined') this.root = '';
		
		// ----------------  ApplyBtn - кнопка "Применить"  -----------------
		if(this.btnApply) Event.observe(this.btnApply, 'click', function(obj){
			return function() {
				obj.applyData();
				return false;
			}
		}(this) );
		// ----------------  ResetBtn - кнопка "Очистить"  -----------------
		if(this.btnReset) Event.observe(this.btnReset, 'click', function(obj){
			return function() {
				obj.form.reset();
				return false;
			}
		}(this) );
		
		// --------------------  U p l o a d  i m a g e  --------------------
		obj.connImg = {};
		$(this.container).getElementsBySelector('.btn_img_upload').each( function(elem){
			var arr = elem.id.split('-'),
				indx = arr[1],
				col = arr[2];
			obj.connImg[col] = new CImgUpload(indx, col);
			
			Event.observe( elem, 'click', function(){
				var arr = elem.id.split('-'),
					indx = arr[1],
					col = arr[2];
				obj.connImg[col].upload();
			} );
		} );
		
		// ---------------------  U p l o a d  f i l e  ---------------------
		obj.connFile = {};
		$(this.container).getElementsBySelector('.btn_file_upload').each( function(elem){
			var arr = elem.id.split('-'),
				indx = arr[1],
				col = arr[2];
			obj.connFile[col] = new CFileUpload(indx, col);
			
			Event.observe( elem, 'click', function(){
				var arr = elem.id.split('-'),
					indx = arr[1],
					col = arr[2];
				obj.connFile[col].upload();
			} );
		} );
		
		// Обработчики на зависимые вып. списки
		$(this.content+'Form-'+this.recId).getElementsBySelector('.relation').each( function(elem){
			var i, N,
				res = elem.getAttribute('relation_elems').split('|'),
				func;
			for(i=0, N=res.length; i<N; i++) {
				Event.observe(elem, 'change', func = function(obj, dst, elem){
					return function() {
						var dstName = $(dst).name;
						var params = {'cont':obj.content, 'row_id':obj.recId, 'dstName':dstName};
						params[elem.name] = $F(elem);
						params[dstName] = $F(dst);
						new Ajax.Updater($(dst).parentNode, '/srv/dropdown/', {parameters: params } );
					}
				}(obj, res[i], elem) );
				func();
			}
		} );
		
		// Enable tinyMCE textareas
		if(typeof(tinyMCE)!='undefined') {
			$(this.content+'Form-'+this.recId).getElementsBySelector('.txt-tiny').each( function(elem){
				tinyMCE.execCommand('mceAddControl', false, elem.id);
			} );
		}
		
		if(this.onFormLoaded) this.onFormLoaded(this);
	},//---------------------------------------------------------------------
	
	applyData: function() {
		var i, N, params, paramsTranslated,
			addParams = [];
		if(!this.form) this.form = $(this.content+'Form-'+this.recId);
		// Clear previously markers
		this.clearMarkers();
		if(this.errFieldRow) this.errFieldRow.className = '';
		if(this.errFieldCell) this.errFieldCell.className = 'caption';

		if(this.onBeforeApply) {
			if(!this.onBeforeApply()) return false;
		}

		// Параметры, переданные на форму при её вызове
		//paramsTranslated = eval('(' + this.form.params.value + ')');
		if(typeof(tinyMCE)!='undefined') addParams = this.form.getElementsBySelector('.txt-tiny');
		for(i=0, N=addParams.size(); i<N; i++) {
			addParams[i].value = tinyMCE.getInstanceById( addParams[i].id ).getContent();
			addParams[i].show();
		}
		//if(paramsTranslated) params = Object.extend( paramsTranslated, this.form.serialize() );
		params = this.form.serialize();
		for(i=0, N=addParams.size(); i<N; i++) addParams[i].hide();

		new Ajax.Request(this.root+this.subUrl, {
			method: 'post',
			parameters: params,
			onLoading: function(obj) {
				return function(){
					obj.msg.update();
					obj.msg.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('loading'))] ) );
				}
			}(this),
			onLoaded: function(obj) {
				return function(){
					obj.msg.update();
					obj.msg.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('loading'))] ) );
				}
			}(this),
			onSuccess: function(obj) {
				return function(t){
					obj.parseSrvAnswer(t);
				}
			}(this),
			onFailure: function(obj) {
				return function(){
					obj.msg.update();
					obj.msg.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('server_connection_failure'))] ) );
				}
			}(this)
		});
	},//---------------------------------------------------------------------
	
	parseSrvAnswer: function(t) {
		this.msg.update();
		this.msg.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('answer_processing'))] ) );
		var json;
		try {
			json = this.json = eval('(' + t.responseText + ')');
		}
		catch(e) {
			this.msg.update('<div class="msg-err">' + _t('error') + '</div>' + t.responseText);
		}

		if(json.status) // Операция выполнена успешно
		{
			this.msg.update('<div class="msg-ok">'+json.message+'</div>');
			if(this.form.action.value==_TBL_ACT_ADD_/*add new record*/) {
				if(this.form.btnReset) {
					this.form.reset();
					try {
						if(this.form.btnReset.onclick) this.form.btnReset.onclick();
					}
					catch (e) {}

					// Clear the tinyMCE fields
					var mceFields = this.form.getElementsBySelector(' .mceEditorContainer');
					for(i=0, N=mceFields.size(); i<N; i++) {
						tinyMCE.getInstanceById( mceFields[i].previousSibling.id ).setHTML('');
					}
					// Clear the images fields if it exist
					this.cnt.getElementsBySelector('.images_info').each( function(elem){ elem.innerHTML = ''; } );
					this.cnt.getElementsBySelector('.images_list').each( function(elem){ elem.innerHTML = ''; } );
					// Clear the files fields if it exist
					this.cnt.getElementsBySelector('.files_info').each( function(elem){ elem.innerHTML = ''; } );
					this.cnt.getElementsBySelector('.files_list').each( function(elem){ elem.innerHTML = ''; } );
				}
				
				if(this.onRecordAdded) this.onRecordAdded();
			}
			
			if(this.clearMsgTimer!=null) window.clearTimeout(this.clearMsgTimer);
			this.clearMsgTimer = window.setTimeout( function(obj){
				return function(){
					obj.clearMsg();
				}
			}(this), 5000);
			
			try {
				// Перезагрузка строки в таблице
				if(this.connRow) this.connRow['rec-'+this.recId].load( {'row_id':this.recId} );
				// Если есть доп. информация обновляем и её
				if(this.connInfo && this.connInfo['rec-'+this.recId]) this.connInfo['rec-'+this.recId].load( {'row_id':this.recId} );
			}
			catch(e) {}
			
			if(this.onDataApplySuccess) this.onDataApplySuccess(json);
			if( (this.editorOptions['redirectAfterAdd'] && (this.form.action.value==_TBL_ACT_ADD_)) || this.editorOptions['redirectAfterUpdate'] ) {
				var url;
				if(this.editorOptions['redirectUrl']) url = this.editorOptions['redirectUrl'];
				else if(json.redirectUrl) url = json.redirectUrl;
				if(url==-1) history.back();
				else if(url) document.location = url;
			}
		}
		else // Ошибка
		{
			this.msg.update();
			var elem,
				div = this.msg.appendChild( elem = crElem('div', { 'class': 'msg-err' }, '', [crElem('b',null,null,_t('error_'))]) );
			elem.innerHTML += json.error.message;

			if(json.error.field) {
				this.errFieldRow = $(json.error.field + '-field_row-' + this.recId);
				this.errFieldCell = $(json.error.field + '-field_cell-' + this.recId);
				if(this.errFieldRow) this.errFieldRow.className = 'error';
				if(this.errFieldCell) this.errFieldCell.className = 'caption td-error';
			}
			if(json.errorList)
			{
				var i, N, elem, wraper;
				for(i=0, N=json.errorList.length; i<N; i++)
				{
					if(json.errorList[i].text) div.appendChild( crElem('div', null, null, json.errorList[i].text) );

					elem = $(json.errorList[i].fname);
					if(elem) {
						wraper = crElem('div', {'class':'marker'}, {'width':elem.getWidth()+'px'}, null);
						elem.wrap( wraper );
					}
				}
			}
			if(this.onDataApplyError) this.onDataApplyError(json);
		}
	},//---------------------------------------------------------------------
	
	clearMarkers: function(){
		if(!this.form) return false;
		var i, N, elems = this.form.getElementsByClassName('marker');
		for(N=elems.length, i=N-1; i>=0; i--) {
			elems[i].childNodes[0].unwrap('div', 'marker');
		}
	},//---------------------------------------------------------------------
	
	clearMsg: function() {
		this.msg.update();
		this.clearMsgTimer = null;
	},//---------------------------------------------------------------------
	
	editorOptions: {},
	container: null,
	form: null,		// form dom object
	connImg: {},	// коннекторы для загрузки изображений { '{column}':{conn}, '{column}':{conn} }
	connFile: {},	// коннекторы для загрузки файлов { '{column}':{conn}, '{column}':{conn} }
	connRow: null,	// передается из CSrvList, служит для обновления исходной строки
	json: null,
	msg: null,
	clearMsgTimer: null,
	onFormLoaded: null,
	onRecordAdded: null,	// обычно устанавливается из CSrvList, перегружает список после добавления записи
	onBeforeApply: null,	// use for data checking, preparing or preprocessing
	onDataApplySuccess: null,
	onDataApplyError: null,
	errFieldRow: null,
	errFieldCell: null
};
//////  Ф о р м а  д о б а в л е н и я / р е д а к т и р о в а н и я  ///////
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
///////////////////  У д а л е н и е  з а п и с и  //////////////////////////
var CSrvDel = Class.create();
CSrvDel.prototype = {
	initialize: function(content) {
		this.content = content;
		this.onLoad = this.parseSrvAnswer;
		
		this.msg = $(this.content+'Msg');
	},
	
	// запрос удаления
	doDelete: function(indx, url) {
		this.indx = indx;
		this.rowLayer = $(this.content+'RowLayer-'+indx),
		this.addInfoRow = $(this.content+'InfoRow-'+indx),
		this.edtRow = $(this.content+'EdtRow-'+indx),
		this.load( url );
	},//---------------------------------------------------------------------
	
	// Устанавливает события после загрузки контента
	parseSrvAnswer: function(t) {
		this.msg.update();
		this.msg.appendChild( crElem('div', { 'class': 'notice' }, '', _t('answer_processing')) );
		
		var json;
		try {
			json = eval('(' + t.responseText + ')');
		}
		catch(e) {
			this.msg.update('<div class="msg-err">' + _t('error') + '</div>' + t.responseText);
		}

		if(json.status) // Операция выполнена успешно
		{
			this.msg.update('<div class="msg-ok">'+json.message+'</div>');
			this.rowLayer.remove();
			if(this.addInfoRow) this.addInfoRow.remove();
			if(this.edtRow) this.edtRow.remove();
			if(this.clearMsgTimer!=null) window.clearTimeout(this.clearMsgTimer);
			this.clearMsgTimer = window.setTimeout( function(obj){
				return function(){
					obj.clearMsg();
				}
			}(this), 5000);
			if(this.onDeleteSuccess) this.onDeleteSuccess(json);
		}
		else // Ошибка
		{
			this.msg.update();
			var div = this.msg.appendChild( crElem('div', { 'class': 'msg-err' }, '', [crElem('b',null,null,_t('error_')), json.error.message]) );
		}
	},//---------------------------------------------------------------------
	
	clearMsgTimer: null,
	clearMsg: function() {
		this.msg.update();
		this.clearMsgTimer = null;
	},//---------------------------------------------------------------------
	
	indx: 0,
	rowLayer: null,
	addInfoRow: null,
	edtRow: null,
	onDeleteSuccess: null
};
///////////////////  У д а л е н и е  з а п и с и  //////////////////////////
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
/////////////////  З а г р у з к а  и з о б р а ж е н и я  //////////////////
var CImgUpload = Class.create();
CImgUpload.prototype = {
	initialize: function(indx, column) {
		this.id_ = indx;
		this.column = column;
		this.indx = '-'+indx+'-'+column;
		this.formName = 'form_image'+this.indx;
		this.frameName = 'upload_frame'+this.indx;
		this.msg = $('image_msg'+this.indx);
		this.imagesListName = 'images_list'+this.indx;
		
		this.setEvents();
	},//---------------------------------------------------------------------

	upload: function() {
		document[this.formName].operation.value = 'upload';
		this.process();
	},//---------------------------------------------------------------------
	
	delete_: function(elem) {
		document[this.formName].operation.value = 'del';
		document[this.formName].operation_item_id.value = this.column+n;
		this.process();
	},//---------------------------------------------------------------------
	
	process: function() {
		window.frames[this.frameName].window.document.inProgress = true;
		$(this.formName).submit();
		if(this.timer!=null) window.clearTimeout(this.timer);
		this.timer = window.setTimeout( function(obj){
			return function(){
				obj.checkUploadedFile();
			}
		}(this), 200);
		return true;
	},//---------------------------------------------------------------------
	
	checkUploadedFile: function(obj) {
		if(!window.frames[this.frameName].window.document.inProgress) {
			this.msg.update();
			this.showImages();
			this.setEvents();
		}
		else {
			this.msg.update();
			this.msg.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('loading'))] ) );
			this.timer = window.setTimeout(function(obj){
				return function(){
					obj.checkUploadedFile();
				}
			}(this), 200);
		}
	},//---------------------------------------------------------------------
	
	showImages: function() {
		var json;
		
		try {
			json = window.frames[this.frameName].window.document.getElementById('json').innerHTML;
			json = eval('(' + json + ')');
		}
		catch (e) { this.msg.innerHTML = '<B>' + _t('error') + '</B> ' + json; return; }
		if(json.status)	{
			$(this.imagesListName).innerHTML = window.frames[this.frameName].window.document.getElementById('images').innerHTML;
			$('images_info'+this.indx).innerHTML = window.frames[this.frameName].window.document.getElementById('images_info').innerHTML;
			document[this.formName]['image'+this.indx].value = '';
		}
		else {
			this.msg.innerHTML = '<B>' + _t('error_') + '</B>'+json.error.message;
		}
	},//---------------------------------------------------------------------
	
	setEvents: function() {
		var obj = this;
		
		// -----------  I m a g e  c o l s  d a t a  a p p l y  -------------
		$(this.imagesListName).getElementsBySelector('.btn_image_cols_apply').each( function(elem){
			if(!elem.getAttribute('event')) Event.observe( elem, 'click', function(){
				var arr = this.form.id.split('-'), rowId = arr[1], colName = arr[2], imageNum = arr[3],
					msgId = 'image_cols-' + rowId + '-' + colName + '-' + imageNum + '-Msg',
					conn = new CSrvConnect(msgId, '/srv/add_edt/cols_data/', '', true);
				
				this.form.cont.value = $(obj.formName).cont.value;
				var params = Element.extend(this.form).serialize();
				conn.load( params );

				return false;
			} );
			elem.setAttribute('event', true);
		} );
		
		// -------------------  D e l e t e  I m a g e  ---------------------
		$(this.imagesListName).getElementsBySelector('.lnk_image_delete').each( function(elem){
			if(!elem.getAttribute('event')) Event.observe( elem, 'click', function(){
				if(!confirm(_t('delete_image_confirmation'))) return false;
				
				var n = this.id.split('-')[3];
				document[obj.formName].operation.value = 'del';
				document[obj.formName].operation_item_id.value = obj.column+n;
				obj.process();
				return false;
			} );
			elem.setAttribute('event', true);
		} );
	},//---------------------------------------------------------------------
	
	id_: null,
	column: null,
	indx: null,
	formName: null,
	frameName: null,
	imagesListName: null,
	timer: null
};
/////////////////  З а г р у з к а  и з о б р а ж е н и я  //////////////////
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
///////////////////////  З а г р у з к а  ф а й л а  ////////////////////////
var CFileUpload = Class.create();
CFileUpload.prototype = {
	initialize: function(indx, column) {
		this.id_ = indx;
		this.column = column;
		this.indx = '-'+indx+'-'+column;
		this.formName = 'form_file'+this.indx;
		this.frameName = 'upload_frame'+this.indx;
		this.msg = $('file_msg'+this.indx);
		this.filesListName = 'files_list'+this.indx;
		
		this.setEvents();
	},//---------------------------------------------------------------------

	upload: function() {
		document[this.formName].operation.value = 'upload';
		this.process();
	},//---------------------------------------------------------------------
	
	delete_: function(elem) {
		document[this.formName].operation.value = 'del';
		document[this.formName].operation_item_id.value = this.column+n;
		this.process();
	},//---------------------------------------------------------------------
	
	process: function() {
		window.frames[this.frameName].window.document.inProgress = true;
		$(this.formName).submit();
		if(this.timer!=null) window.clearTimeout(this.timer);
		this.timer = window.setTimeout( function(obj){
			return function(){
				obj.checkUploadedFile();
			}
		}(this), 200);
		return true;
	},//---------------------------------------------------------------------
	
	checkUploadedFile: function(obj) {
		if(!window.frames[this.frameName].window.document.inProgress) {
			this.msg.update();
			this.showFiles();
			this.setEvents();
		}
		else {
			this.msg.update();
			this.msg.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('loading'))] ) );
			this.timer = window.setTimeout(function(obj){
				return function(){
					obj.checkUploadedFile();
				}
			}(this), 200);
		}
	},//---------------------------------------------------------------------
	
	showFiles: function() {
		var json;
		try { json = eval('(' + window.frames[this.frameName].window.document.getElementById('json').innerHTML + ')'); }
		catch (e) { this.msg.innerHTML = '<B>' + _t('error') + '</B>'; return; }
		if(json.status)	{
			$(this.filesListName).innerHTML = window.frames[this.frameName].window.document.getElementById('files').innerHTML;
			$('files_info'+this.indx).innerHTML = window.frames[this.frameName].window.document.getElementById('files_info').innerHTML;
			document[this.formName]['file'+this.indx].value = '';
		}
		else {
			this.msg.innerHTML = '<B>' + _t('error_') + '</B>'+json.error.message;
		}
	},//---------------------------------------------------------------------
	
	setEvents: function() {
		var obj = this;
		
		// --------------------  D e l e t e  F i l e  ----------------------
		$(this.filesListName).getElementsBySelector('.lnk_file_delete').each( function(elem){
			if(!elem.getAttribute('event')) Event.observe( elem, 'click', function(){
				if(!confirm(_t('delete_file_confirmation'))) return false;
				
				var n = this.id.split('-')[3];
				document[obj.formName].operation.value = 'del';
				document[obj.formName].operation_item_id.value = n;
				obj.process();
				return false;
			} );
			elem.setAttribute('event', true);
		} );
	},//---------------------------------------------------------------------
	
	id_: null,
	column: null,
	indx: null,
	formName: null,
	frameName: null,
	filesListName: null,
	timer: null
};
///////////////////////  З а г р у з к а  ф а й л а  ////////////////////////
/////////////////////////////////////////////////////////////////////////////


/////////////////////////////////////////////////////////////////////////////
///  Р е д а к т и р о в а н и е  " с о б с т в е н н о й "  з а п и с и  ///
var CSrvSelf = Class.create();
CSrvSelf.prototype = {
	initialize: function(content, url) {
		this.content = content;
		this.urlSecond = url;
		this.onLoad = this.getSelfId;
		
		this.msg = $(this.content+'Msg');
	},//---------------------------------------------------------------------

	// Получение с сервера ID
	getSelfId: function(t) {
		var json;
		try {
			json = eval('(' + t.responseText + ')');
		}
		catch(e) {
			this.msg.update('<div class="msg-err">' + _t('error') + '</div>');
		}

		if(json.status) {// Операция выполнена успешно
			this.msg.update();
			this.urlFirst = this.url;	// store the first url for the refresh button
			this.url = this.urlSecond + '&row_id=' + json.indx;
			
			this.connEdt = Object.extend(new CSrvConnect(this.cnt, this.root, this.url), new CSrvAddEdt(this.content, 'process/', json.indx, this.container) );
			this.connEdt.load();
			this.url = this.urlFirst;	// refresh first url as current
		}
	}
};
///  Р е д а к т и р о в а н и е  " с о б с т в е н н о й "  з а п и с и  ///
/////////////////////////////////////////////////////////////////////////////