/**************************************
 * Lactell JS - Gasser & Gasser
 **************************************/
var echo = function(msg) {
	if($('outMsg') == null) {
		var out = new Element('div',{'id': 'outMsg','style': 'position:absolute; z-index:99999; padding:0 4px; background:#FFF; color:#000;'});
		out.inject($(document.body),'top');
	}
	$('outMsg').appendText(msg);
	var br = new Element('br');
	$('outMsg').grab(br);
};

var initCarte = function() {
	
};

var getBaseUrl = function() {
	var base = $$('base');
	var url = '';
	if(base.length > 0) {
		url = base[0].getProperty('href');
	} else {
		var theUri = new URI();
		url = theUri.get('scheme')+'://'+theUri.get('host')+theUri.get('directory');
	}
	return url;
}

var calculator = new Class({
	Implements: Options,
	options: {
		container: 'pricecalculator',
		lineSelector: '.line',
		pointASelector: '#calculator_start',
		pointBSelector: '#calculator_dest',
		viaSelector: '#calculator_via',
		priceValueSelector: '.result .price .value',
		zoneValueSelector: '.result .zones .value',
		reduceSelector: 'input[name=calculator_reduce]:checked',
		classeSelector: 'input[name=calculator_classe]:checked',
		submitButtonSelector: '#calculator_submit'
	},
	initialize: function(options) {
		this.setOptions(options);
		
		this.container = $(this.options.container);
		this.form = this.container.getElement('form');
		this.lines = this.getLines();
		
		this.pointA = this.container.getElement(this.options.pointASelector);
		this.pointB = this.container.getElement(this.options.pointBSelector);
		this.pointA.set('value', '0');
		this.pointB.set('value', '0');
		
		this.via = this.container.getElement(this.options.viaSelector);
		
		this.reduce = this.container.getElement(this.options.reduceSelector);
		this.classe = this.container.getElement(this.options.classeSelector);
		
		this.priceValue = this.container.getElement(this.options.priceValueSelector);
		this.zoneValue = this.container.getElement(this.options.zoneValueSelector);
		
		//this.submitButton = this.container.getElement(this.options.submitButtonSelector);
		
		// stop the form submit
		this.form.addEvent('submit', function(event) {
			event.stop();
		});
		// on button click, check points
		this.pointA.addEvent('change', function(event) {
			if(this.checkPointAB()) {
				this.loadVia();
			}
		}.bind(this));
		this.pointB.addEvent('change', function(event) {
			if(this.checkPointAB()) {
				this.loadVia();
			}
		}.bind(this));
		this.via.addEvent('change', function(event) {
			this.showPrice();
			
		}.bind(this));
		
		this.container.getElements('input[type=radio]').addEvent('click', function(event) {
			this.showPrice();
		}.bind(this));
		
		$(document).addEvent('click', function(event) {
			this.checkVia();
		}.bind(this));
		/*this.submitButton.addEvent('click', function(event) {
			if(this.checkPointAB()) {
				//this.viaData = this.loadVia();
			}
		}.bind(this));
		*/
		//this.overDiv = new Element('div', {'class':'over'});
		//this.overDiv.inject(this.wrapIn);
		
		//this.overZoom = new Element('div', {'class':'overZoom'});
		//this.overZoom.inject(this.wrapIn);
		
		//this.fxOverDiv = new Fx.Tween(this.overDiv, {'property':'opacity','duration':500}).set(1);
		
		
	},
	getLines: function() {
		return this.container.getElements(this.options.lineSelector);
	},
	checkPointAB: function() {
		//var valueA = $(this.pointA.getSelected()[0]).get('value');
		this.valueA = this.pointA.get('value');
		this.valueB = this.pointB.get('value');
		
		if(this.valueA != '0' && this.valueB != '0') {
			return true;
		}
		return false;
	},
	loadVia: function() {
		var jsonRequest = new Request.JSON({
			'url': getBaseUrl()+'index.php?type=281&action=via&start='+this.valueA+'&dest='+this.valueB,
			'onSuccess': function(responseJSON){
				if(responseJSON.via) {
					this.setVia(responseJSON.via);
					this.setPrice(responseJSON.price);
					this.specialMsg = null;
					if(responseJSON.special) {
						this.specialMsg = responseJSON.special;
					}
					this.showPrice();
				} else {
					this.setVia([]);
					this.setPrice('');
					this.resetPrice();
				}
			}.bind(this),
			'onError': function(text, error){
				echo('error:'+error+':'+text);
			}.bind(this),
			'onComplete': function(){
				// complete
			}.bind(this),
			'onFailure': function(){
				echo('failure');
			}.bind(this)
		});
		jsonRequest.send();
	},
	setVia: function(data) {
		this.viaData = data;
		this.via.empty();
		// boucle de tous les via possibles pour A et B
		this.viaData.each(function(item,index) {
			// si n'est pas "toutes les zones", on affiche le via...
			if(item.tarifstufe < 10) {
				var opt = new Element('option',{'html':item.verkaufervia.replace(/\+/g,'-'),'value':item.vianr});
				opt.inject(this.via);
			}
		}.bind(this));
	},
	setPrice: function(data) {
		this.prices = data;
		
	},
	checkVia: function() {
		//var valueA = $(this.pointA.getSelected()[0]).get('value');
		this.valueA = this.pointA.get('value');
		this.valueB = this.pointB.get('value');
		this.valueVia = this.via.get('value');
		
		this.valueReduce = this.container.getElement(this.options.reduceSelector).get('value');
		this.valueClasse = this.container.getElement(this.options.classeSelector).get('value');
		
		if(this.valueA != '0' && this.valueB != '0' && this.valueVia != '0' && this.valueVia != '') {
			return true;
		}
		return false;
	},
	showPrice: function() {
		if(this.checkVia()) {
			var nbZones = this.getNbZones();
			this.priceValue.set('html',this.getPrice(nbZones));
			this.zoneValue.set('html',(nbZones == 0) ? 'Billet court parcours':'Billet '+nbZones+' zones');
			this.showWhatZone((nbZones == 0) ? true:false);
		}
	},
	resetPrice: function() {
		var nbZones = '';
		this.priceValue.set('html','');
		this.zoneValue.set('html','');
		this.showWhatZone(false);
	},
	showWhatZone: function(court) {
		if(!this.whatZone) {
			this.whatZone = new Element('div', {'class':'whatZone'});
			this.whatZone.inject(this.form,'after');
			this.whatZoneFx = new Fx.Slide(this.whatZone, {'duration':500}).hide();
			this.whatZoneOldCourt = !court;
		}
		if(this.whatZoneOldCourt != court) {
			this.whatZoneFx.cancel();
			this.whatZoneFx.slideOut().chain(function() {
				this.whatZone.set('text',(court) ? 'La mention "court parcours" vous permet de déterminer le prix de votre titre de transport':'Le nombre de zones vous permet de déterminer le prix de votre titre de transport');
				if(this.specialMsg) {
					var currentText = this.whatZone.get('text');
					this.whatZone.set('html', '<strong>'+this.specialMsg+'</strong><br />'+currentText);
				}
				this.whatZoneFx.slideIn();
			}.bind(this));
			this.whatZoneOldCourt = court;
		}
		if(this.specialMsg) {
			var currentText = this.whatZone.get('text');
			this.whatZone.set('html', '<strong>'+this.specialMsg+'</strong><br />'+currentText);
			this.whatZoneFx.show();
		} else {
			this.whatZone.set('text',(court) ? 'La mention "court parcours" vous permet de déterminer le prix de votre titre de transport':'Le nombre de zones vous permet de déterminer le prix de votre titre de transport');
			this.whatZoneFx.show();
		}
	},
	getNbZones: function() {
		var nbZones = this.viaData.filter(function(item,index) { return item.vianr == this.valueVia; }.bind(this))[0].tarifstufe;
		return nbZones;
	},
	getPrice: function(nbZones) {
		var price = 0;
		var zonePrice = null;
		if(this.valueReduce == 1) {
			zonePrice = this.prices[nbZones].reduit;
		} else {
			zonePrice = this.prices[nbZones].adulte;
		}
		if(this.valueClasse == 1) {
			price = zonePrice['1cl'];
		} else {
			price = zonePrice['2cl'];
		}
		return price.format({
			decimal: ".",
			decimals: 2,
			prefix: "Prix: CHF "
		});
	},
	addClasse: function() {
		
	}
});

//ondeVerteCarte = null;
window.addEvent('domready', function() {
	//initCarte();
	
	var ondeVerteCalculator = new calculator();
	
});

