// -------------------------------------------------------------------------- //
// ------------------------------ Person ------------------------------------ //
// -------------------------------------------------------------------------- //

Person = function( age, target ) {
	Person.superClass.apply( this, new Array() );

	this.Id = 'Person';
	this.age = age;
	this.withSeat = ( age == 'baby' ? false : true );
	this.hover = false;

	this.element = this.createNode( 'div', { 'class': 'person' }, target );
	this.inner = this.createNode( 'div', { 'class': 'png' }, this.element );

	this.addHandler( this.element, 'mouseover', this.notify, 'ToggleHover' );
	this.addHandler( this.element, 'mouseout', this.notify, 'ToggleHover' );
	this.addHandler( this.element, 'click', this.notify, 'PersonClicked' );

	return this;
}
Person.inheritsFrom( HTMLGlif );

// -------------------------------------------------------------------------- //
// ------------------------------ Persons ----------------------------------- //
// -------------------------------------------------------------------------- //

Persons = function( target, limit ) {
	Persons.superClass.apply( this, arguments );
	this.element = target;

	this.inactive = this.getEl('inactive');
	this.active = this.getEl('active');
	this.arrow = this.getEl('arrow');
	this.label = this.getEl('label');

	this.activeUpper = this.active.firstChild;
	this.activeLower = this.active.lastChild;

	this.title = new HTMLGlif();
	this.title.element = this.getEl('psngrCount'); // выводит кол-во пассажиров
	this.tip = this.getEl('tip');	// подсказка

	this.controls = new Array();	// для выбора человека
	this.persons = new Array();		// список уже выбранных людей

	this.adult = 0;
	this.child = 0;
	this.baby = 0;

	this.seats = 1;

	this.limit;

	this.lastAdult = this.setPerson( 'adult' );
	this.lastAdult.setClassName( 'no', true );		// не удалить первого пассажира
}
Persons.inheritsFrom( HTMLGlif );

// -------------------------------------------------------------------------- //

// вставим объект (по возрасту) для выбора (серенькие)
Persons.prototype.setControl = function( age ) {
	var newPerson = this.createPerson( age, null, this.inactive );

	this.controls[ age ] = newPerson;
	newPerson.attachObserver( 'PersonClicked', this.controlClicked, this );
	return newPerson;
}

// реакция на клик по человечкам для выбора
Persons.prototype.controlClicked = function( params, obj ) {
	if( !this.check( obj ) ) return;
	this.setPerson( obj.age, obj.withSeat );
	this.checkOnDisable();
	this.setTitle();
	this.setTip( obj );
}

// вставим человека выбранного возраста
Persons.prototype.setPerson = function( age, withSeat ) {
	var newPerson;
	var target;
	this[ age ]++;
	if( age != 'adult' || !this.lastAdult ) {
		if (age == 'baby') {
			//var babyWithSeat = this.seats - this.adult - this.child;
			//target = (this.adult < this.baby && this.seats < 4 && babyWithSeat < 1 ) ? this.activeUpper : this.activeLower;
			target = ( withSeat ? this.activeUpper : this.activeLower );
		}
		else {
			target = this.activeUpper;
		}
		if ( withSeat && this.childWithSeat ){
			newPerson = this.createPerson( age, withSeat );		// вставляем чела до младенца с местом
			this.activeUpper.insertBefore( newPerson.element, this.childWithSeat.element );
		}
		else {
			newPerson = this.createPerson( age, withSeat, target );
		}
		if ( withSeat && age == 'baby' ){
			this.childWithSeat = newPerson;
		}
	} else {
		newPerson = this.createPerson( age, withSeat );		// вставляем взрослого перед обязательным взрослым
		this.activeUpper.insertBefore( newPerson.element, this.lastAdult.element );
	}

	this.persons[ this.persons.length ] = newPerson;
	newPerson.attachObserver( 'PersonClicked', this.personClicked, this );
	this.seats = this.activeUpper.childNodes.length;	// определяем количество мест
	this.notify( 'PersonCountChanged' );	// информируем контроллер
	return newPerson;
}

// создаем объект Персона для возможности выбрать или отменить выбор
Persons.prototype.createPerson = function( age, withSeat, target ) {
	var title = false;
	title = this[ age + 'Title'];
	/*switch( age ) {
		case 'adult': title = 'Взрослый'; break;
		case 'child': title = 'Ребенок'; 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 );
	if ( withSeat != null ) newPerson.withSeat = withSeat;
	return newPerson;
}

// -------------------------------------------------------------------------- //

Persons.prototype.personClicked = function( params, obj ) {
	if( obj.age == 'adult' ) {
		if( this.adult == 1 ) return;
		this.checkInfantCount();
		this.checkChildCount();		// только для гостиниц
	}

	if( obj == this.lastAdult && this.changeLastAdult( obj ) ) return;

	for( var idx in this.persons ) {
		if( obj == this.persons[ idx ] ) break;
	}

	this[ obj.age ]--;
	obj.remove();
	this.persons.splice( idx, 1 );
	if ( obj.age == 'baby' && obj.withSeat ){
		this.childWithSeat = false;
	}
	
	this.seats = this.activeUpper.childNodes.length;
	this.checkOnDisable();
	this.setTitle();
	this.setTip( false );
	this.notify( 'PersonCountChanged' );
}

// считаем младенцев. Их не должно быть больше чем взрослых ( в авиа - взрослых + младенец с местом )
Persons.prototype.checkInfantCount = function() {
	if( ( this.adult <= this.baby && this.seats == this.adult + this.child ) ||
	    ( this.adult + 1 <= this.baby && this.seats == this.adult + this.child + 1 ) ) {
		for( var c in this.persons ) {
			var cP = this.persons[c];
			if( cP.age == 'baby' && !cP.withSeat ) {
				cP.notify( 'PersonClicked' );
				break;
			}
		}
	}
}

// в гостиницах на одного взрослого только 1 ребенок
Persons.prototype.checkChildCount = function() {}

// если нажали на обязательного взрослого, то событие перехватывает предыдущий человек
Persons.prototype.changeLastAdult = function( obj ) {
	var el = this.lastAdult.element.previousSibling;
	for( var c in this.persons ) {
		var cP = this.persons[c];
		if( cP.element == el ) {
			cP.notify( 'PersonClicked' );
			return true;
		}
	}
	return false;
}

// -------------------------------------------------------------------------- //

// сделаем младенца с местом или отменим это
Persons.prototype.setSeatToBaby = function( flag ){
	this.controls[ 'baby' ].withSeat = flag;
}

// -------------------------------------------------------------------------- //

// больше нельзя кликнуть на человечка этого возраста и наоборот
Persons.prototype.setDisabled = function( age, flag ) {
	if( !this.controls[ age ] ) return;
	this.controls[ age ].disabled = flag;
	this.controls[ age ].setClassName( 'disabled', flag );
}

// -------------------------------------------------------------------------- //

// напишем слово "пассажиры" или "проживающие"
Persons.prototype.setLabel = function( label ) {
	this.setContent( label, this.label );
}

// подсветить объект Person при наведении мышки
Persons.prototype.toggleHover = function( params, obj ) {
	obj.hover = !obj.hover;
	var el = obj.element;
	
	/*var el = (params.target || params.srcElement).parentNode;
	var isPerson = ( $(el).hasClass('person') );
	if (!isPerson) return;	// isPerson;*/

	var naFlag = ( el.parentNode.id == 'inactive' );
	var disabled = obj.disabled;
	//var disabled = ( $(el).hasClass('disabled') );

	this.arrow.className = ( disabled || !naFlag && obj.hover) ? 'na' : ( obj.hover ? 'hover' : '' );

	obj.setClassName( 'hover', obj.hover );
	
	if ( obj.hover && !disabled ) {
		this.setTip( obj );	//.age, el.parentNode.id );
	}
	else {
		this.setTip( false );
	}
}

// покажем подсказку
Persons.prototype.setTip = function( obj /* age, pId, txt */) {
	if ( obj == false || obj.disabled ){
		this.tip.innerHTML = '';
		return;
	}
	var age = obj.age;
	var ageName = this[ age + 'NameGC' ];
	if ( obj.withSeat && obj.age == 'baby' ) ageName = this[ age + 'NameGCWithSeat' ];
	var toAddRemove = ( obj.element.parentNode.id == 'inactive' ) ? true : false;
	var actionTxt = ( toAddRemove ? 'добавить ' : 'исключить ' );
	var excludeTxt = '';
	
	var string = '';
	var pType = (this.Id == 'hotelPersons') ? 'гостей' : 'пассажиров';

	//var k = this.babyWithSeatCount();

/*	if (age == 'child') {
		ageName = 'ребенка';
		ageDetail = ' от 2х до 12-ти лет';
	}
	else if (age == 'baby') {
		ageName = 'младенца';
		ageDetail = ' до 2х лет';
		var seat = / *(this.seats < 4 && this.adult <= this.baby) ? ' с местом' : * /' без места';
		ageDetail += seat;
	}
	else if (age == 'adult') {
		ageName = 'взрослого';
		ageDetail = ' (старше 12-ти лет)';
	}
*/
	if ( toAddRemove ) {
		if ( this.seats == 4 && (age != 'baby' || this.baby >= this.adult) ) {
			excludeTxt = 'в заказе может быть до 4 ' + pType + ' с местом';
		}
	}
	else {
		if (age == 'adult' && this.adult == 1) {
			excludeTxt = 'нельзя исключить';
		}
	}

	string = excludeTxt || actionTxt + ageName;	// + ageDetail;
	this.tip.innerHTML = string;
}

// расскажем сколько кого было выбрано
Persons.prototype.setTitle = function() {
	var string = this.adult + '&nbsp;' + ( this.adult > 1 ? this.adultNameNCPl : this.adultNameNC );
	if ( this.child > 0 ) {
		string += ', ' + this.child + '&nbsp;' + ( this.child > 1 ? this.childNameNCPl : this.childNameNC );
	}
	if ( this.baby > 0 ) {
		string += ', ' + this.baby + '&nbsp;' + ( this.baby > 1 ? this.babyNameNCPl : this.babyNameNC );
	}
	this.title.setContent( string );
}

// -------------------------------------------------------------------------- //

// данные для параметров для формирования запроса на поиск
Persons.prototype.getValue = function() {
	//var bws = this.babyWithSeatCount();
	var babyWithSeat = this.seats != this.adult + this.child;
	var result = {
		Dlts: this.adult,
		Children: this.child + ( babyWithSeat ? 1 : 0 ),
		Infants: this.baby - ( babyWithSeat ? 1 : 0 )
	};
	return result;
}

// из сохраненных данных выставляем количество пассажиров
Persons.prototype.set = function( adults, childs, infants ) {
	if( this.controls.adult ) {
		for( var i = 0; i < adults - 1; i++ ) {
			this.controls.adult.notify( 'PersonClicked' );
		}
	}

	if( childs > 0 && this.controls.child ) {
		for( var i = 0; i < childs; i++ ) {
			this.controls.child.notify( 'PersonClicked' );
		}
	}

	if( infants > 0 && this.controls.baby ) {
		for( var i = 0; i < infants; i++ ) {
			this.controls.baby.notify( 'PersonClicked' );
		}
	}
}

// сбросить всех человечков
Persons.prototype.reset = function(){
	while (this.persons.length > 1) {
		var i = this.persons.length - 1;
		this.personClicked( i, this.persons[i] );
	}
}

Persons.prototype.check = function( obj ) {}

Persons.prototype.checkOnDisable = function( obj ) {}		// определяется в конкретном контроллере


// -------------------------------------------------------------------------- //
/*
Persons.prototype.babyWithSeatCount = function() {
	if (this.baby == 0) {
		return 0;
	}
	else {
		return this.seats - this.adult - this.child;
	}
}
*/