// ---------------------------- FormController ------------------------------ //
//Контроллер Страницы с формой
// -------------------------------------------------------------------------- //

FormController = function() {
	FormController.superClass.apply( this, arguments );

	this.Id = 'FormController';
	this.forms = new Array();
	this.details = new Info();
	this.details.setClosable( true );
	this.errorMsg = '<big>Извините, произошла ошибка.</big>';
	this.status = false;

	//this.button = new Button( this.getEl( 'button' ), this.getEl( 'form' ), this.getEl( 'button' ).firstChild );
	//this.button.attachObserver( 'buttonSubmited', this.send, this );
	//this.button.attachObserver( 'buttonClicked', this.checkOnClick, this );
}
FormController.inheritsFrom( HTMLGlif );

// -------------------------------------------------------------------------- //
// создание формы
FormController.prototype.createForm = function( name, target, idx ) {
	if( window[ name + 'Form' ] ) {
		var form = this.createNode( 'div', { 'class': 'form ' + name.toLowerCase() }, target );
		var newForm = new window[ name + 'Form' ]( form, idx );
	} else {
		return false;
	}

	this.forms[ this.forms.length ] = newForm;
	newForm.attachObserver( 'formStatusChange', this.check, this );
	return newForm;
}

// удаление формы. Не знаю, зачем
FormController.prototype.removeForm = function( form ) {
	for( var c = this.forms.length; c; c-- ) {
		if(  this.forms[ c - 1 ] == form ) break;
	}
	form.remove();
	this.forms.splice( c -1, 1 );
}

// сделано для случая двух кнопок на странице
FormController.prototype.setButton = function( form ){
	var newButton = new Button( form.lastChild, form, form.lastChild.firstChild );
	newButton.attachObserver( 'buttonSubmited', this.send, this );
	newButton.attachObserver( 'buttonClicked', this.checkOnClick, this );
	return newButton;
}

// -------------------------------------------------------------------------- //

FormController.prototype.checkOnClick = function() {
	this.checkToSubmit();
	//this.setEmpty();
}

// проверка всех форм после заполнения какого-либо поля или при вводе данных из кук или xsl
FormController.prototype.check = function( form ) {
	this.status = true;

	for( var c in this.forms ) {
		if( !this.forms[ c ].status ) {
			this.status = false;
			break;
		}
	}

	this.button.setValid( this.status );
	return this.status;
}

// проверка всех форм при submit'е
FormController.prototype.checkToSubmit = function( form ) {
	this.status = true;

	for( var c in this.forms ) {
		if( !this.forms[c].checkToSubmit() ) {
			this.status = false;
			break;
		}
	}

	this.button.setValid( this.status );
	//return this.status;
}

// формирование параметров конкретной формы для посылки на сервер
FormController.prototype.getParams = function( form, number ) {
	var params = new Object();
	number = number || '';
	for ( var i = 0, lenI = form.inputs.length; i < lenI; i++ ){
		params[ form.inputs[ i ].name + number ] = form.inputs[ i ].getValueToParam();
	}
	return params;
}

// переопределяется в конкретном контроллере
FormController.prototype.send = function() {}

// посылка формы если ajax получил данные и потом их передал форме для посылки дальше
FormController.prototype.submit = function() {
	this.button.submit();
}

// произошла ошибка при выполнении ajax запроса
FormController.prototype.stateError = function( result ) {
	this.processing( false );
	if( result[ 'Error' ] && result[ 'Error' ][0] ) {
		this.alert( '<big>' + result[ 'Error' ][0]['Description'] + '</big>', true );
	} else {
		this.alert( this.errorMsg, true );
	}
}

// выводим окно "выполнение ajax запроса"
FormController.prototype.processing = function( flag, text ) {
	var html = document.body.parentNode;
	if( flag ) {
		if( this.bDiv ) return;
		var sc = ( document.documentElement.scrollTop || document.body.scrollTop || 0 ) + '';
		this.setStyle( { overflow: 'hidden' }, html );
		this.setStyle( { overflow: 'hidden' }, document.body );
		this.bDiv = new HTMLGlif( 'div', { 'class': 'process png' }, document.body );

		if(  '\v' == 'v' && typeof document.documentElement.style.maxHeight == "undefined" ) {
			this.bDiv.setStyle({ 'top': sc + 'px' });
		}

		this.bDiv.inner = this.createNode( 'div',
			{ 'class': 'process-msg' },
			this.bDiv.element,
			text + '... <img src="/images/inProgress.gif" width="48" height="48" alt="загрузка" title="загрузка">' );
	} else {
		this.setStyle( { overflow: 'auto' }, html );
		this.setStyle( { overflow: 'auto' }, document.body );
		if( this.bDiv ) {
			this.bDiv.remove();
			this.bDiv = false;
		}
	}
}

// вывод сообщения при ajax запросе
FormController.prototype.alert = function( text, closable ) {
	this.details.setClosable( closable );
	this.details.fill( text );
	this.details.show();
}

// -------------------------------------------------------------------------- //
/*
FormController.prototype.setEmpty = function() {
	for( var c in this.forms ) {
		this.forms[c].setEmpty();
	}
}
*/

