var railwayExamples = [
	{	Name: 'Москва', Country: '', Id: 'b3c24b40-6efb-4097-b9ab-6e22b0a6cb5e', Code: '2000000' },
	{	Name: 'Санкт-Петербург', Country: '', Id: 'a7a0c53f-fec8-44aa-b164-7d9769232dfc', Code: '2004000' },
	{	Name: 'Екатеринбург', Country: '', Id: '00577053-e8e9-4279-a75d-5a91b319beaa', Code: '2030000' }
];
var perdicateErrorTexts = {
	errorPatternText: 'Неизвестный город или станция',
	errorEmptyText: 'Введите название станции'
}

// -------------------------------------------------------------------------- //

RailwayController = function() {
	RailwayController.superClass.apply( this, arguments );
	
	this.Id = 'RailwayController';
	this.searchUrl = '/railway/search/';
	this.form = this.createForm( railwayForm, this.getEl( 'form' ) );

	this.calendar = new Calendar( this.getEl( 'calendar-wrap' ), now, date44 );
	this.calendar.changeMode( 1 );
	this.calendar.attachObserver( 'CalendarDaySelected', this.form.setInputDate, this.form );
	this.calendar.attachObserver( 'CalendarDayUnSelected', this.form.unsetInputDate, this.form );

	this.form.attachObserver( 'DateInputSetted', this.calendar.setDate, this.calendar );

	this.persons = new railwayPersons( this.getEl( 'persons' ) );
	this.persons.attachObserver( 'PersonCountChanged', function(){ $('#resetForm').removeClass( 'hidden' ); }, this );

}
RailwayController.inheritsFrom( Controller );

// -------------------------------------------------------------------------- //

RailwayController.prototype.send = function() {
	var formResult = this.form.getParams();
	var persons = this.persons.getValue();

	//if( this.promo && this.promo.getData() ) oParams[ 'PromoCode'] = this.promo.getData();

	this.searchStoreSaveParams.addParams({ 'Commander.Command': 'SearchRailwayTariffs' });
	this.searchStoreSaveParams.addParams( formResult );
	this.searchStoreSaveParams.addParams( persons );
	this.searchStoreSaveParams.load();
}

RailwayController.prototype.checkStateOfStoreSaveParams = function() {
	var formResult = this.form.getParams();
	var persons = this.persons.getValue();

	this.searchStore.addParams({ 'Commander.Command': 'SearchRailwayTariffs' });
	this.searchStore.addParams( formResult );
	this.searchStore.addParams( persons );
	this.searchStore.load();
}

// -------------------------------------------------------------------------- //

// из Global вставляем значения
RailwayController.prototype.init = function( data ) {
	//return false; //временно отключаем инициализацию
	if( data[ 'From' ] ) this.form.inputs[ 0 ].setDefault( data[ 'From' ], data[ 'From' ][ 'Name' ] );
	if( data[ 'To' ] ) this.form.inputs[ 1 ].setDefault( data[ 'To' ], data[ 'To' ][ 'Name' ] );
	if( data[ 'Departure' ] && data[ 'Departure' ] != '0001-01-01T00:00:00' ) {
		var date = this.translateDate( data[ 'Departure' ] );
		if( date instanceof Date ) this.form.dates[ 0 ].setDefault( date );
	}
	this.form.check();
	
	if( data[ 'PersonsCount' ] ) {
		this.persons.set(
			Number( data[ 'PersonsCount' ][ 'Adults' ] ),
			Number( data[ 'PersonsCount' ][ 'Children' ] ),
			Number( data[ 'PersonsCount' ][ 'Infants' ] )
		);
	}
}

// заполняем из данных по ссылке партнера
RailwayController.prototype.initDataFromPartner = function( data ) {
	this.form.inputs[ 0 ].setDefault( data[ 'From' ], data[ 'From' ][ 'Name' ] );
	this.form.inputs[ 1 ].setDefault( data[ 'To' ], data[ 'To' ][ 'Name' ] );
}

// -------------------------------------------------------------------------- //
// -------------------------------- Form ------------------------------------ //
// -------------------------------------------------------------------------- //

railwayForm = function( target ) {
	railwayForm.superClass.apply( this, arguments );

	this.dates = new Array();
	
	this.inputs[ 0 ] = new PredicateInput({
		target: this.getEl( 'input1' ),
		type: 'text predicate',
		command: 'SearchRailwayLocation',
		big: true,
		name: 'From',
		label: 'откуда',
		tip: 'город или станция',
		examples: railwayExamples,
		required: true,
		errorPatternText: perdicateErrorTexts[ 'errorPatternText' ],
		errorEmptyText: perdicateErrorTexts[ 'errorEmptyText' ]
	});
	this.inputs[ 0 ].elementInput.tabIndex = 1;
	this.inputs[ 0 ].attachObserver( 'inputSetted', this.onInputSetted, this );
	this.inputs[ 0 ].attachObserver( 'inputStatusChange', function(){ this.check(); }, this );
	
	this.dates[ 0 ] = new DateInput({
		target: this.getEl( 'date1' ),
		type: 'd0',
		name: 'DateFrom',
		label: 'когда',
		tip: 'дд.мм.гггг',
		min: now,
		max: date44,
		required: true,
		errorInputText: datesErrorTexts[ 'errorInputText' ],
		errorPatternText: datesErrorTexts[ 'errorPatternText' ],
		errorEmptyText: datesErrorTexts[ 'errorEmptyText' ],
		errorMinMaxText: datesErrorTexts[ 'errorMinMaxText' ]
	});
	this.dates[ 0 ].elementInput.tabIndex = 2;
	this.dates[ 0 ].attachObserver( 'inputSetted', this.onInputSetted, this );
	this.dates[ 0 ].attachObserver( 'inputStatusChange', function(){ this.check(); }, this );

	this.inputs[ 1 ] = new PredicateInput({
		target: this.getEl( 'input2' ),
		type: 'text predicate',
		command: 'SearchRailwayLocation',
		big: true,
		name: 'To',
		label: 'куда',
		tip: 'город или станция',
		examples: railwayExamples,
		required: true,
		errorPatternText: perdicateErrorTexts[ 'errorPatternText' ],
		errorEmptyText: perdicateErrorTexts[ 'errorEmptyText' ]
	});
	this.inputs[ 1 ].elementInput.tabIndex = 3;
	this.inputs[ 1 ].attachObserver( 'inputSetted', this.onInputSetted, this );
	this.inputs[ 1 ].attachObserver( 'inputStatusChange', function(){ this.check(); }, this );
}
railwayForm.inheritsFrom( IndexForm );

// -------------------------------------------------------------------------- //
/*
railwayForm.prototype.onInputSet = function( params, obj ) {
	if( obj.data ) {
		switch( obj.idx ) {
			case 0:  obj.setTip( 'откуда' ); obj.input.focus(); break;
			case 1:  obj.setTip( 'куда' ); obj.input.focus(); break;
		}
	} else {
		obj.setTip( false );
	}
}
*/
// -------------------------------------------------------------------------- //

railwayForm.prototype.onInputSetted = function( params, obj ) {
	$('#resetForm').removeClass( 'hidden' );
	if ( obj[ 'Id' ] == 'DateInput' && !obj.error ){
		var date = obj.getData();
		var index = Number( obj.type.substr( 1 ) );
		this.notify( 'DateInputSetted', { index: index, data: date } );
	}
	if ( this.inputs[ 0 ].data && this.inputs[ 1 ].data && this.inputs[ 0 ].data[ 'Id' ] == this.inputs[ 1 ].data[ 'Id' ] ) {
		this.inputs[ 1 ].errorControllerText = 'Пункт выезда не может совпадать с пунктом приезда';
		this.inputs[ 1 ].errorFromController = true;
		this.inputs[ 1 ].checkPattern();
	}
	//this.check();
}

// -------------------------------------------------------------------------- //

railwayForm.prototype.reset = function(){
	this.inputs[ 0 ].reset();
	this.inputs[ 1 ].reset();
	this.dates[ 0 ].clear();
	this.status = false;
}

// -------------------------------------------------------------------------- //

railwayForm.prototype.getParams = function() {
	var result = new Object();
	result[ 'From' ] = this.inputs[ 0 ].getData( 'Id' );
	result[ 'FromName' ] = this.inputs[ 0 ].getData( 'Name' );
	result[ 'To' ] = this.inputs[ 1 ].getData( 'Id' );
	result[ 'ToName' ] = this.inputs[ 1 ].getData( 'Name' );
	if( !result[ 'From' ] || !result[ 'To' ] ) return false;
	result[ 'Departure' ] = this.dates[ 0 ].getValueToParam();
	return result;
}

// -------------------------------------------------------------------------- //
/*
railwayForm.prototype.getError = function() {
	var errMsg = 'Город отбытия совпадает с городом прибытия.';
	for( var c in this.inputs ) {
		if( !this.getInput( c ).status ) {
			errMsg = 'Вы не указали город ';
			switch ( Number( c ) ) {
				case 0 : errMsg += 'отбытия'; break;
				case 1 : errMsg += 'прибытия'; break;
			}
			errMsg += '.\n';
		}
		else if (!this.dates[0].data) {
			errMsg = 'Укажите дату отбытия';
		}
	}
	return errMsg;
}
*/
// -------------------------------------------------------------------------- //
// ------------------------------ Persons ----------------------------------- //
// -------------------------------------------------------------------------- //

railwayPersons = function() {
	
	this.Id = 'railwayPersons';

	this.adultTitle = 'Взрослый';
	this.childTitle = 'Ребенок';
	this.babyTitle = 'Младенец';

	this.babyNameNC = 'ребенок до&nbsp;5-ти лет';
	this.babyNameNCPl = 'детей до&nbsp;5-ти лет';
	this.babyNameGC = 'ребенка до&nbsp;5-ти лет без&nbsp;предоставления места';
	
	this.childNameNC = 'ребенок';
	this.childNameNCPl = 'детей';
	this.childNameGC = 'ребенка от&nbsp;0 до&nbsp;10-ти&nbsp;лет с&nbsp;предоставлением места';

	this.adultNameNC = 'взрослый';
	this.adultNameNCPl = 'взрослых';
	this.adultNameGC = 'взрослого';

	railwayPersons.superClass.apply( this, arguments );

	this.setLabel( 'Количество пассажиров:' );

	this.setControl( 'baby' );
	this.setControl( 'child' );
	this.setControl( 'adult' );
	
	this.checkOnDisable();
	this.setTitle();
}
railwayPersons.inheritsFrom( Persons );

// -------------------------------------------------------------------------- //

railwayPersons.prototype.checkOnDisable = function() {
	this.setDisabled( 'adult', this.adult + this.child + this.baby == 4 );
	this.setDisabled( 'child', this.adult + this.child + this.baby == 4 );
	this.setDisabled( 'baby', ( this.baby == this.adult || this.adult + this.child + this.baby == 4 /* || this.baby == 2*/ ) );
	
	this.lastAdult.setClassName( 'no', this.adult == 1 );
}

railwayPersons.prototype.check = function( obj ) {
	if( 
		( ( obj.age == 'adult' || obj.age == 'child' ) && this.adult + this.child + this.baby == 4 ) ||
		( obj.age == 'baby' && ( this.baby == this.adult || this.adult + this.child + this.baby == 4 ) )
	) return false;
	return true;
}

// -------------------------------------------------------------------------- //

window.onload = function() {
	controller = new RailwayController();

	if ( dataPromo ) controller.initDataFromPartner( dataPromo )
	else if( Global ) controller.init( Global[ 'Railway' ] );
}