var RatesCalendar = new Class({
	
	Implements: Options,
	
	options: {
		monthElement: '.monthly-calendar',
		monthName: '#current-month strong',
		replicateValues: true,
		activeClassname: 'active',
		inactiveClassname: 'inactive',
		autoStyle: true,
		mask: true,
		sliderOptions: {
			fxOptions: {
				duration: 750
			}
			/*
			onChange: $empty(intStep),
			onComplete: $empty(strStep),
			onNext: $empty(strStep),
			onPrevious: $emptu(strStep)
			*/
		}
	},
	
	touched: false,
	
	initialize: function(options){
		this.setOptions(options);
		this._localization(Vadingo.translationManager);
		
		var inputs = this.inputs = $$(this.options.monthElement + ' input[type=text]');
		var checkboxes = $$(this.options.monthElement + ' input[type=checkbox]');
		var active = this.options.activeClassname, inactive = this.options.inactiveClassname;
		var self = this;
		
		this.inputs.each(function(el, index){
			var parentEl = el.getParent().getParent();
			if (this.options.replicateValues){
				el.addEvent('focus', function(){
					var prev = (inputs[index - 1]) ? inputs[index - 1].get('value') : '';
					if (prev !== '' && this.get('value') === '') {
						this.set('value', prev);
					}
					if (self.options.mask && !this.retrieve('meiomask')) {
						this.meiomask('decimal', 'reverse', {
							//symbol: this.currency.symbol,
							decimal: self.currency.decimal,
							thousands: self.currency.thousands,
							maxLength: 8,
							autoEmpty: true,
							onInvalid: function(el){ el.highlight('#d4dff3'); }
						});
					}
					else this.select();
				});
				el.addEvent('blur', function(){
					if (this.get('value') !== '') {
						parentEl.className = active;
						checkboxes[index].checked = true;
					} else {
						checkboxes[index].checked = false;
						parentEl.className = inactive;
					}
				}.create({delay: 50, bind: el}));
			}
			el.addEvent('mouseup', function(e){
				e.preventDefault();
				this.select();
			});
			
			var doStyle = function(el){
				if (this.get('value') === '' || this.get('value') == '0') {
					el.className = inactive;
					checkboxes[index].checked = false;
				} else if (!checkboxes[index].checked) {
					el.className = inactive;
				} else {
					el.className = active;
				}
			}.bind(el);
			
			if (this.options.autoStyle)
				doStyle(parentEl);
		}.bind(this));
		
		checkboxes.addEvent('change', function(){
			if (!this.checked) {
				this.getParent().getParent().className = inactive;
			} else {
				this.getParent().getParent().className = active;
			}
		});
		
		this._alertBeforeExit();
	},
	
	_alertBeforeExit: function(){
		document.id('timeframes').addEvents({
			'keydown:relay(input[type=text])': this.touch.pass(true, this),
			'click:relay(input[type=checkbox])': this.touch.pass(true, this)
		});
		$E('.room-selector').getElements('a').addEvent('click', function(event){
			if (this.touched) {
				event.preventDefault();
				SqueezeDialog.open({
					msg: this.tm._('Are you sure you want to change of room type? Your current changes will be lost'),
					fn: function(el){
						location.href = el.get('href');
					}.pass(this)
				},{
					handler: 'confirm'
				});
			}
		}.bind(this));
	}.protect(),
	
	_localization: function(tm){
		this.currentMonth = document.id(this.options.monthName) || $E(this.options.monthName);
		this.tm = tm;
		this.date = {
			months: MooTools.lang.get('Date').get('months'),
			year: this.currentMonth.get('text')
		};
		this.currency = {
			decimal: MooTools.lang.get('Currency', 'decimal'),
			thousands: MooTools.lang.get('Currency', 'thousands'),
			symbol: MooTools.lang.get('Currency', 'symbol')
		};
	}.protect(),
	
	touch: function(status){
		if (this.touched == status) return;
		this.touched = status;
	}
	
});

(function(){

var newTitle = function(step){
	this.currentMonth.set('text', this.date.months[step] + ' ' + this.date.year);
};

RatesCalendar.implement({ // #TODO: Implement HistoryManager
	
	startSlider: function(){
		if (!('ViewSlider' in window)) throw new Error("The Class `ViewSlider` does not exists or has not been included.");
		
		var fragment = Number(new URI(location.href).get('fragment') || new Date().get('month') + 1);
		var step = fragment - 1;
		var options = $merge(this.options.sliderOptions, {'initialStep': step, 'steps': this.date.months.length, 'offsetStep': -1});
		var element = $E(this.options.monthElement).getParent();
		var slider = new ViewSlider(element, $extend(options, {'onChange': newTitle.bind(this)}));
		var self = this;

		newTitle.call(this, step);
		
		document.id('next-month').removeClass('hide').addEvent('click', slider.next.bind(slider));
		document.id('prev-month').removeClass('hide').addEvent('click', slider.previous.bind(slider));
		document.id('reset-month').removeClass('hide').addEvent('click', function(event){
			event.stop();
			SqueezeDialog.open({
				msg: self.tm._('Are you sure you want to reset the entire month?'),
				fn: function(){
					var els = $$(self.options.monthElement)[slider.step].getElements('input');
					els.highlight();
					els.set({'value': '', 'checked': false});
					self.touch(true);
				}
			},{
				handler: 'confirm'
			});
		});
		document.id('booknow-month').removeClass('hide').addEvent('click', function(event){
			event.preventDefault();
			$$(self.options.monthElement)[slider.step].getElements('input[type=checkbox]').set('checked', true);
		});
		
		this._preventSliderCorruption(slider);
	},
	
	_preventSliderCorruption: function(slider){
		var inputsArray = $$(this.options.monthElement).map(function(el){
			var inputs = el.getElements('input[type=text]');
			return $$([inputs[0], inputs.getLast()]);
		});
		
		inputsArray.each(function(inputs, pos){
			inputs[0].addEvent('tab', function(e){
				if (e.shift) slider.set(pos - 1);
			});
			inputs[1].addEvent('tab', function(e){
				if (!e.shift) slider.set(pos + 1);
			});
		});
	}.protect()
	
});

})();