var hotelExamples = [
	{	Name: 'Санкт-Петербург', Country: 'Россия', Id: '9481c5b4-69b9-426d-92f6-402b70b22f20', Code: 'LED' },
	{	Name: 'Прага', Country: 'Чехия', Id: '559e5181-c0e5-417e-b420-e242568f5546', Code: 'PRG' },
	{	Name: 'Москва', Country: 'Россия', Id: '607b4aa2-5281-406c-a2ce-4bd52c29ef9a', Code: 'MOW' }
];
var perdicateErrorTexts = {
	errorPatternText: 'Неизвестный город',
	errorEmptyText: 'Введите название города'
}


// -------------------------------------------------------------------------- //

HotelController = function() {
	HotelController.superClass.apply( this, arguments );
	
	this.Id = 'HotelController';
	this.searchUrl = '/hotel/search/';
	this.form = this.createForm( hotelForm, this.getEl( 'form' ) );

	this.calendar = new Calendar( this.getEl( 'calendar-wrap' ), now, date365 );
	this.calendar.changeMode( 2 );

	//this.calendar.attachObserver( 'calendarStatusChange', this.check, this );
	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 hotelPersons( this.getEl( 'persons' ) );
	this.persons.attachObserver( 'PersonCountChanged', function(){ $('#resetForm').removeClass( 'hidden' ); }, this );
}
HotelController.inheritsFrom( Controller );

// -------------------------------------------------------------------------- //

HotelController.prototype.send = function() {
	var formResult = this.form.getParams();
	var persons = this.persons.getValue();

	//if( this.promo /*&& this.promo.getData()*/ ) { oParams[ 'PromoCode'] = this.promo.getData(); }
	//oParams[ 'PromoCode'] = 'FORALL';

	this.searchStoreSaveParams.addParams({ 'Commander.Command': 'SearchHotelTariffs' });
	this.searchStoreSaveParams.addParams( persons );
	this.searchStoreSaveParams.addParams( formResult );
	this.searchStoreSaveParams.load();
}

HotelController.prototype.checkStateOfStoreSaveParams = function() {
	var formResult = this.form.getParams();
	var persons = this.persons.getValue();

	this.searchStore.addParams({ 'Commander.Command': 'SearchHotelTariffs' });
	this.searchStore.addParams( persons );
	this.searchStore.addParams( formResult );
	this.searchStore.load();
}

//----------------------------------------------------------------------------//

HotelController.prototype.init = function( data ) {
	//return data; //Удалить эту строку, если требуется вернуть инициализацию
	if( data[ 'CheckIn' ] && data[ 'CheckIn' ] != '0001-01-01T00:00:00' ) {
		this.form.dates[ 0 ].setDefault( this.translateDate( data[ 'CheckIn' ] ) );
	}
	if( data[ 'CheckOut' ] && data[ 'CheckOut' ] != '0001-01-01T00:00:00' ) {
		this.form.dates[ 1 ].setDefault( this.translateDate( data[ 'CheckOut' ] ) );
	}
	if( data[ 'City' ] ){
		var cityCode = data[ 'City' ][ 'Code' ];
		var codes = cityCode.split( '/' );
		if ( codes[ 0 ] == '' ){
			cityCode = codes[ 1 ];
		}
		else {
			cityCode = codes[ 0 ];
		}
		data[ 'City' ][ 'Code' ] = cityCode;
		this.form.inputs[ 0 ].setDefault( data[ 'City' ], data[ 'City' ][ 'Name' ] );
	}
	if( data[ 'MinRating' ] != 'NO_RATING' ) this.form.rating.setInitialValue( data[ 'MinRating' ] );

	this.form.check();
	
	if( data[ 'PersonsCount' ] ) {
		this.persons.set(
			Number( data[ 'PersonsCount' ][ 'Adults' ] ),
			Number( data[ 'PersonsCount' ][ 'Children' ] ),
			Number( data[ 'PersonsCount' ][ 'Infants' ] )
		);
	}
}

// заполняем из данных по ссылке партнера
HotelController.prototype.initDataFromPartner = function( data ) {
	this.form.inputs[ 0 ].setDefault( data[ 'City' ], data[ 'City' ][ 'Name' ] );
}

//----------------------------------------------------------------------------//

HotelController.prototype.checkState = function( result ) {
	if( Boolean( result[ 'CommandId' ] ) ) {
		this.fillForm( this.searchUrl, {
			'SearchId': result[ 'CommandId' ]/*,
			'MinHotelRating': this.tripClass.getData( 'min' ) || false,
			'MaxHotelRating': this.tripClass.getData( 'max' ) || false*/
		} );

		if( this.form.rating.getData( 'min' ) ) {
			this.fillForm( false, {
				'MinHotelRating': this.form.rating.getData( 'min' )
			});
		}

		if( this.form.rating.getData( 'max' ) ) {
			this.fillForm( false, {
				'MaxHotelRating': this.form.rating.getData( 'max' )
			});
		}

		this.submit();
	} else {
		alert( 'Извините, произошла ошибка. Попробуйте ещё раз.' );
	}
}

// -------------------------------------------------------------------------- //
// --------------------------------- Form ----------------------------------- //
// -------------------------------------------------------------------------- //

hotelForm = function( target ) {
	hotelForm.superClass.apply( this, arguments );

	this.Id = 'HotelForm';	
	this.dates = new Array();

	this.dates[ 0 ] = new DateInput({
		target: this.getEl( 'date1' ),
		type: 'd0',
		name: 'DateFrom',
		label: 'заезд',
		tip: 'дд.мм.гггг',
		min: now,
		max: date365,
		required: true,
		errorInputText: datesErrorTexts[ 'errorInputText' ],
		errorPatternText: datesErrorTexts[ 'errorPatternText' ],
		errorEmptyText: datesErrorTexts[ 'errorEmptyText' ],
		errorMinMaxText: datesErrorTexts[ 'errorMinMaxText' ]
	});
	this.dates[ 0 ].elementInput.tabIndex = 1;
	this.dates[ 0 ].attachObserver( 'inputSetted', this.onInputSetted, this );
	this.dates[ 0 ].attachObserver( 'inputStatusChange', function(){ this.check(); }, this );
	
	this.inputs[ 0 ] = new PredicateInput({
		target: this.getEl( 'input1' ),
		type: 'text predicate',
		command: 'SearchHotelLocation',
		big: true,
		name: 'To',
		label: 'куда',
		tip: 'город',
		examples: hotelExamples,
		required: true,
		errorPatternText: perdicateErrorTexts[ 'errorPatternText' ],
		errorEmptyText: perdicateErrorTexts[ 'errorEmptyText' ]
	});
	this.inputs[ 0 ].elementInput.tabIndex = 2;
	this.inputs[ 0 ].attachObserver( 'inputSetted', this.onInputSetted, this );
	this.inputs[ 0 ].attachObserver( 'inputStatusChange', function(){ this.check(); }, this );
	
	this.dates[ 1 ] = new DateInput({
		target: this.getEl( 'date2' ),
		type: 'd1',
		name: 'DateFrom',
		label: 'выезд',
		tip: 'дд.мм.гггг',
		min: now,
		max: date365,
		required: true,
		errorInputText: datesErrorTexts[ 'errorInputText' ],
		errorPatternText: datesErrorTexts[ 'errorPatternText' ],
		errorEmptyText: datesErrorTexts[ 'errorEmptyText' ],
		errorMinMaxText: datesErrorTexts[ 'errorMinMaxText' ]
	});
	this.dates[ 1 ].elementInput.tabIndex = 3;
	this.dates[ 1 ].attachObserver( 'inputSetted', this.onInputSetted, this );
	this.dates[ 1 ].attachObserver( 'inputStatusChange', function(){ this.check(); }, this );

	this.rating = new Select({
		target: this.getEl( 'class' ),
		type: 'select',
		name: 'tripClass',
		label: 'класс',
		tip: 'класс',
		list: [
			{	Name: '1...5 *', Value: 'NO_RATING', HTML: ['<small>1...5 *</small>'] },
			{	Name: '1...3 *', Value: 'ONE_STAR', HTML: ['<small>1...3 *</small>'], min: 'ONE_STAR', max: 'THREE_STAR' },
			{	Name: '3...4 *', Value: 'THREE_STAR', HTML: ['<small>3...4 *</small>'], min: 'THREE_STAR', max: 'FOUR_STAR' },
			{	Name: '4...5 *', Value: 'FOUR_STAR', HTML: ['<small>4...5 *</small>'], min: 'FOUR_STAR', max: 'FIVE_STAR' }
		],
		initialValue: 'NO_RATING'
	});
	this.rating.elementInput.tabIndex = 4;
	this.rating.attachObserver( 'inputSetted', function(){ $('#resetForm').removeClass( 'hidden' ); }, this );
}
hotelForm.inheritsFrom( IndexForm );

// -------------------------------------------------------------------------- //

hotelForm.prototype.onInputSetted = function( params, obj ) {
	$('#resetForm').removeClass( 'hidden' );
	if ( obj[ 'Id' ] == 'DateInput' ){
		var date = obj.getData();
		var index = Number( obj.type.substr( 1 ) );
		this.notify( 'DateInputSetted', { index: index, data: date } );
	}
	//this.check();
}

// -------------------------------------------------------------------------- //

hotelForm.prototype.reset = function(){
	this.inputs[ 0 ].reset();
	this.dates[ 0 ].clear();
	this.dates[ 1 ].clear();
	this.rating.setInitialValue( this.rating.initialValue );
	this.status = false;
}

// -------------------------------------------------------------------------- //

hotelForm.prototype.getParams = function() {
	var result = new Object();
	result[ 'City' ] = this.inputs[ 0 ].getData( 'Id' );
	result[ 'CityName' ] = this.inputs[ 0 ].getData( 'Name' );
	result[ 'CityCountry' ] = this.inputs[ 0 ].getData( 'Country' );
	result[ 'CheckIn' ] = this.dates[ 0 ].getValueToParam();
	result[ 'CheckOut' ] = this.dates[ 1 ].getValueToParam();
	result[ 'MinHotelRating' ] = this.rating.getData( 'min' );
	result[ 'MaxHotelRating' ] = this.rating.getData( 'max' );
	return result;
}

// -------------------------------------------------------------------------- //
// -------------------------------- Persons --------------------------------- //
// -------------------------------------------------------------------------- //

hotelPersons = function() {
	
	this.Id = 'hotelPersons';

	this.adultTitle = 'Взрослый';
	this.childTitle = 'Ребенок';
	this.babyTitle = 'Люлька для младенца';

	this.babyNameNC = 'люлька для младенца';
	this.babyNameNCPl = 'люльки для младенца';
	this.babyNameGC = 'люльку для младенца';
	
	this.childNameNC = 'ребенок';
	this.childNameNCPl = 'детей';
	this.childNameGC = 'ребенка от 2-х до 12-ти лет с предоставлением места';
	
	this.adultNameNC = 'взрослый';
	this.adultNameNCPl = 'взрослых';
	this.adultNameGC = 'взрослого';

	hotelPersons.superClass.apply( this, arguments );

	this.setLabel( 'Количество проживающих:' );

	this.setControl( 'baby' );
	this.setControl( 'child' );
	this.setControl( 'adult' );

	this.checkOnDisable();
	this.setTitle();
}
hotelPersons.inheritsFrom( Persons );

// -------------------------------------------------------------------------- //
/*
Persons.prototype.personClicked = function( params, obj ) {
	if( obj.age == 'adult' ) {
		if( this.adult == 1 ) return false;
		this.checkInfantCount();
	}

	if( obj == this.lastAdult && this.changeLastAdult( obj ) ) return false;

	this[ obj.age ]--;
	obj.remove();
	
	for( var idx in this.persons ) {
		if( obj == this.persons[ idx ] ) break;
	}

	this.persons.splice( idx, 1 );

	this.checkOnDisable();
	this.setTitle();
	return true;
}
*/
	
hotelPersons.prototype.checkChildCount = function() {
	if( this.adult <= this.child ) {
		for( var c in this.persons ) {
			var cP = this.persons[ c ];
			if( cP.age == 'child' ) {
				cP.notify( 'PersonClicked' );
				break;
			}
		}
	}
}

hotelPersons.prototype.checkOnDisable = function() {
	this.setDisabled( 'adult', this.adult + this.child == 4 );
	this.setDisabled( 'child', ( this.adult + this.child == 4 || this.adult == this.child ) );
	this.setDisabled( 'baby', ( /*this.baby == this.adult ||*/ this.baby == 2 ) );
	
	//this.checkChildCount();
	this.lastAdult.setClassName( 'no', this.adult == 1 );
}

hotelPersons.prototype.check = function( obj ) {
	if( 
		( obj.age == 'adult' && this.adult + this.child == 4 ) ||
		( obj.age == 'child' && ( this.adult + this.child == 4 || this.adult == this.child ) ) ||
		( obj.age == 'baby' && ( /*this.baby == this.adult ||*/ this.baby == 2 ) )
	) return false;
	return true;
}

// -------------------------------------------------------------------------- //
/*
Persons.prototype.createPerson = function( age, target ) {
	var title = false;
	switch( age ) {
		case 'adult': title = 'Взрослый'; break;
		case 'child': title = 'Ребенок до 12 лет'; break;
		case 'baby': title = 'Младенец'; break;
	}

	var newPerson = new Person( age, target );
	this.setClassName( age, true, newPerson.inner );
	this.setProperty( { title: title }, newPerson.inner );
	newPerson.attachObserver( 'ToggleHover', this.toggleHover, this );
	return newPerson;
}
*/
// -------------------------------------------------------------------------- //

/*
hotelPersons.prototype.checkChildCount = function() {
	if( this.child > 0 && this.adult != 2 ) {
		for( var c in this.persons ) {
			var cP = this.persons[c];
			if( cP.age == 'child' ) {
				cP.notify( 'PersonClicked' );
				break;
			}
		}
	}
}
*/

// -------------------------------------------------------------------------- //

window.onload = function() {
	controller = new HotelController();

	if ( dataPromo ) controller.initDataFromPartner( dataPromo )
	else if( Global ) controller.init( Global[ 'Hotel' ] );
}