/*
 * @author Luis Merino
 * @copyright author
 * 
 * @created Sat Feb 20 01:50:45 CET 2010
 */

(function(){
	
Meio.Mask.createMasks('Reverse', {
	'Percent': {
		precision: 0,
		maxLength: 3
	}
});	

var CalculationHelper = this.CalculationHelper = new Class({
	
	Implements: Observable,
	
	_localization: function(tm){
		tm.load('occupancy-rules', 'request');
	},
	
	initialize: function(){
		this._localization(Vadingo.translationManager);
		this.setupElements();
		CalculationHelper.setupInputMask();
	},
	
	setupElements: function(){
		this.adult = {
			trigger: document.id('max_adults').store('type', 'adult'),
			table: new AdultsTable(document.id('adults-table'))
		};
		this.infant = {
			trigger: document.id('max_infants').store('type', 'infant'),
			table: new InfantsTable(document.id('infants-table'))
		};
		this.children = new ChildrenTableManager($$('.children-component'), this.adult.table);
		
		var self = this;
		$$(this.adult.trigger, this.infant.trigger).addEvent('change', function(){
			self['on'+this.retrieve('type').capitalize()+'Change'](this.get('value'));
		});
	},
	
	onAdultChange: function(value){
		this.adult.table.fireEvent('change', value);
	},
	
	onInfantChange: function(value){
		this.infant.table.fireEvent('change', value);
	}
	
});

CalculationHelper.extend({
	
	DEFAULT_PRICE: 80,
	
	price: null,
	
	setupInputMask: function(){
		var currency = MooTools.lang.get('Currency');
		$$('input.surcharge').each(function(input){
			if (input.get('meiomask')) return false;
			input.set('meiomask', 'decimal', 'reverse', {
				//symbol: currency.symbol,
				decimal: currency.decimal,
				thousands: currency.thousands,
				maxLength: 7,
				selectOfFocus: false
			});
		});
	}
	
});

var AdultsTable = new Class({
	
	Extends: HtmlTable,
	
	Implements: [Options, Events, Storage],
	
	options: {
		
	},
	
	initialize: function(element, options){
		this.parent(element, options);
		this.row = $$(this.body.rows)[0].removeClass('hide').dispose();
		this.addEvent('change', this.onChange);
		this.buildRows();
		this.tm = Vadingo.translationManager;
	},
	
	buildRows: function(){
		$each($$(this.body.rows, this.row), this.setupRowSelectors, this);
	},
	
	toElementRow: function(){
		return this.row;
	},
	
	onChange: function(value){
		this.store('count', value);
		var amount = value - this.body.rows.length;
		if (amount > 0) {
			amount.times(this.addRow, this);
		} else if (amount < 0) {
			(amount *= -1).times(this.deleteRow, this);
		}
		this.fireEvent('adultsChange', value);
	},
	
	addRow: function(times, amount){
		var count = this.retrieve('count');
		var len = this.body.rows.length;
		var number = len + 1;
		var row = this.setupRowSelectors(this.row.clone());
		var tds = row.retrieve('elements');
		var S = " ";
		tds[0]['title'].set('text', number + S + (count > 1 ? this.tm._('Adults') : this.tm._('Adult')));
		tds[1]['percent'].setProperty('name', tds[1]['percent'].getProperty('name').substitute({index: number}));
		tds[2]['surcharge'].setProperty('name', tds[2]['surcharge'].getProperty('name').substitute({index: number}));

		row.inject(this.body);
		CalculationHelper.setupInputMask();
	},
	
	deleteRow: function(times, amount){
		$$(this.body.rows).getLast().dispose();
	},
	
	setupRowSelectors: function(row){
		var elements = $$();
		
		Array(
			function(base){ // <td> #1
				var td = base.getElement('td:nth-child(1)');
				return {
					'column': td,
					'title': td.getElement('.title')
				};
			},
			function(base){ // <td> #2
				var td = base.getElement('td:nth-child(2)');
				return {
					'column': td,
					'percent': td.getElement('.percent'),
					'percent-of': td.getElement('.percent-of')
					//'helper-price': td.getElement('*:nth-child(3)'),
					//'currency': td.getElement('*:nth-child(4)')
				};
			},
			function(base){ // <td> #3
				var td = base.getElement('td:nth-child(3)');
				return {
					'column': td,
					'surcharge': td.getElement('.surcharge'),
					'currency': td.getElement('.currency')
				};
			}
		).each(function(query){
			elements.push(query(row));
		}, this);

		return row.store('elements', elements);
	}
	
});

var InfantsTable = new Class({
	
	Extends: HtmlTable,
	
	Implements: [Options, Events, Storage],
	
	options: {
		
	},
	
	initialize: function(element, options){
		this.parent(element, options);
		this.row = $$(this.body.rows)[0].removeClass('hide').dispose();
		this.addEvent('change', this.onChange);
		this.buildRows();
		this.tm = Vadingo.translationManager;
	},
	
	buildRows: function(){
		$each($$(this.body.rows, this.row), this.setupRowSelectors, this);
	},
	
	toElementRow: function(){
		return this.row;
	},
	
	onChange: function(value){
		this.store('count', value);
		var amount = value - this.body.rows.length;
		if (amount > 0) {
			amount.times(this.addRow, this);
		} else if (amount < 0) {
			(amount *= -1).times(this.deleteRow, this);
		}
	},
	
	addRow: function(times, amount){
		var count = this.retrieve('count');
		var len = this.body.rows.length;
		var number = len + 1;
		var row = this.setupRowSelectors(this.row.clone());
		var tds = row.retrieve('elements');
		
		tds[0]['title'].set('text', number + ' ' + (number != 1 ? this.tm._('Infants') : this.tm._('Infant')));
		tds[1]['surcharge'].set('value', '').setProperty('name', tds[1]['surcharge'].getProperty('name').substitute({index: number}));
		row.inject(this.body);
		CalculationHelper.setupInputMask();
	},
	
	deleteRow: function(times, amount){
		$$(this.body.rows).getLast().dispose();
	},
	
	//update: $empty,
	
	setupRowSelectors: function(row){
		var elements = $$();
		
		Array(
			function(base){ // <td> #1
				var td = base.getElement('td:nth-child(1)');
				return {
					'column': td,
					'title': td.getElement('.title')
				};
			},
			function(base){ // <td> #2
				var td = base.getElement('td:nth-child(2)');
				return {
					'column': td,
					'surcharge': td.getElement('*:nth-child(1)')
				};
			}
		).each(function(query){
			elements.push(query(row));
		}, this);

		return row.store('elements', elements);
	}
	
});

(function(){

var Component = $empty;

var ChildrenTableManager = this.ChildrenTableManager = new Class({
	
	Implements: Options,
	
	options: {
		templateIndex: 0
	},
	
	created: [], // Stores created components.
	
	initialize: function(selectors, adultsTableInstance, options){
		this.setOptions(options);
		this.tm = Vadingo.translationManager;
		adultsTableInstance.addEvent('adultsChange', this.onAdultsChange.bind(this));
		var base = selectors.shift();
		this.template = base.removeClass('hide').dispose();
		this.template.getElements('tbody tr').each(function(tr, index){
			if (index) tr.dispose();
		});
		selectors.each(this.addComponent, this);
	},

	displayComponent: function(value){
		this.created.each(function(component, index){
			component.node[(index > value ? 'add' : 'remove') + 'Class']('hide');
		});
	},
	
	addComponent: function(template, isClone){
		var component = this.setupComponent(template, isClone);
		this.created.push(component);
		return component.node;
	},
	
	removeComponent: function(index){
		this.created.pop().node.dispose();
	},
		
	setupComponent: function(template, isClone){
		var index = isClone === true ? '{index}' : this.created.length + 1;
		var count = this.created.length + 1;
		var component = new Component();
			component = {
				node: template,
				table: new ChildrenTable(template.getElement('table'), {adultIndex: count}),
				childrenSelect: template.getElement('select')
			};
		// label children
		component.node.getElement('label[for=adults-'+index+'-max_children]').set('for', 'adults-'+count+'-max_children');
		// select children
		component.childrenSelect.set({
			'id': 'adults-'+count+'-max_children',
			'name': 'adults['+count+'][max_children]'
		}).addEvent('change', function(e){ component.table.onChange(e.target.selectedIndex); });
		//title bar
		component.node.getElement('h3').set('text', component.node.getElement('h3').get('text').substitute({'%d': count}));
		// caption
		component.node.getElement('caption').set('text', component.node.getElement('caption').get('text').substitute({'index': count}));
		// return the object to save
		return component;
	},
	
	onAdultsChange: function(value){
		var amount = value - this.created.length;
		if (amount > 0) {
			amount.times(function(){
				this.addComponent(this.template.clone(), true).inject(this.created[this.created.length - 2].node, 'after');
			}, this);
		} else if (amount < 0) {
			(amount *= -1).times(function(){
				this.removeComponent(arguments);
			}, this);
		}
	}
	
});

})();

var ChildrenTable = new Class({
	
	Extends: HtmlTable,
	
	Implements: [Options, Events, Storage],
	
	options: {
		adultIndex: null
	},
	
	initialize: function(element, options){
		this.parent(element, options);
		this.row = $$(this.body.rows)[0].removeClass('hide').dispose();
		this.addEvent('change', this.onChange);
		this.buildRows();
		this.tm = Vadingo.translationManager;
	},
	
	buildRows: function(){
		$each($$(this.body.rows, this.row), this.setupRowSelectors, this);
	},
	
	onChange: function(value){
		this.store('count', value);
		var amount = value - this.body.rows.length;
		if (amount > 0) {
			amount.times(this.addRow, this);
		} else if (amount < 0) {
			(amount *= -1).times(this.deleteRow, this);
		}
	},
	
	addRow: function(times, amount){
		var count = this.retrieve('count');
		var len = this.body.rows.length;
		var number = len + 1;
		var row = this.setupRowSelectors(this.row.clone());
		var tds = row.retrieve('elements');
		var S = " ";
		
		tds[0]['title'].set('text', number + S + (count > 1 ? this.tm._('Children') : this.tm._('Child')));
		tds[1]['percent'].setProperty('name', tds[1]['percent'].getProperty('name').substitute({index: this.options.adultIndex, index_child: count}));
		tds[2]['surcharge'].setProperty('name', tds[2]['surcharge'].getProperty('name').substitute({index: this.options.adultIndex, index_child: count}));
		row.inject(this.body);
		CalculationHelper.setupInputMask();
	},
	
	deleteRow: function(times, amount){
		$$(this.body.rows).getLast().dispose();
	},
	
	setupRowSelectors: function(row){
		var elements = $$();
		
		Array(
			function(base){ // <td> #1
				var td = base.getElement('td:nth-child(1)');
				return {
					'column': td,
					'title': td.getElement('.title')
				};
			},
			function(base){ // <td> #2
				var td = base.getElement('td:nth-child(2)');
				return {
					'column': td,
					'percent': td.getElement('*:nth-child(1)'),
					'percent-of': td.getElement('*:nth-child(2)')
					//'helper-price': td.getElement('*:nth-child(3)'),
					//'currency': td.getElement('*:nth-child(4)')
				};
			},
			function(base){ // <td> #3
				var td = base.getElement('td:nth-child(3)');
				return {
					'column': td,
					'surcharge': td.getElement('*:nth-child(1)'),
					'currency': td.getElement('*:nth-child(2)')
				};
			}
		).each(function(query){
			elements.push(query(row));
		}, this);
		
		return row.store('elements', elements);
	}
});

})();