var Passengers = function( passenger, el, handler ){
	this.passenger = passenger;
	this.item = el;
	this.ends = this.passenger.ends;
	this.min = this.passenger.min;
	this.max = this.passenger.max;
	this.input = this.item.find('input');
	this.text_block = this.item.find('.text');

	this.plus = this.item.find('.plus');
	this.minus = this.item.find('.minus');

	var val = parseInt(this.input.val());
	this.current_value = isNaN(val) ? 0 : val;
	
	this.handler = handler;
	this.init();
};

Passengers.prototype = {
	init: function(){
		this.attach_events();
		this.change_text();
		this.toggle_plus();
		this.toggle_minus();
	},

	attach_events: function(){
		var that = this;

		this.plus.click(function(){
			if( $( this ).is( '.disabled' ) ) return false;
			that.setValue( that.current_value + 1 );
		});

		this.minus.click(function(){
			if( $( this ).is( '.disabled' ) ) return false;
			that.setValue( that.current_value - 1 );
		});
	},

	toggle_plus: function(){
		if( this.current_value < this.max ){
			this.plus.removeClass( 'disabled' );
		} else {
			this.plus.addClass( 'disabled' );
		}
	},

	toggle_minus: function(){
		if( this.current_value > this.min ){
			this.minus.removeClass( 'disabled' );
		} else {
			this.minus.addClass( 'disabled' );
		}
	},

	change_text: function(){
		var
			end = '',
			ends_amount = this.ends.length,
			text = '';

		if( this.current_value >= ends_amount ){
			end = this.ends[ends_amount - 1];
		} else {
			end = this.ends[this.current_value];
		}

		if( this.current_value > 0 ){
			text = this.current_value + ' ' + end;
		} else {
			text = end;
		}

		this.text_block.text(text);
	},
	
	setValue: function( value ) {
		this.current_value = value;
		this.input.val( this.current_value );

		this.toggle_plus();
		this.toggle_minus();

		this.change_text();
		this.onChange();
	},
	
	setMax: function( value ) {
		this.max = value;
		if( this.current_value > this.max ) {
			this.setValue( this.max );
		} else {
			this.toggle_plus();
			this.toggle_minus();
		}
	},
	
	onChange: function() {
		if(
			this.handler &&
		    this.handler instanceof Function
		) {
			this.handler();
		}
	}
};
