var App = Class.create({

	d: null,	// object literal from GDirections
	t: null,	// object literal from GDirections
	distance: null,
	price: null,
	time: { hours: null, minutes: null, sec: null },
	geocoder: null,
	point: null,
	
	initialize: function(point) {	
		
		Ajax.Responders.register({

			requestTime: null,
			
			onCreate: function(e){
				
				Element.show($("loading"));
			},
			
			onComplete: function(e) {
			
				Element.hide($("loading"));
			
				if (e.transport.status == 401){
				
					alert("Please login!");
				}
			},
			
			onExeption: function(e){
				
				alert("Hups, jossain on jottain vikkoo :)");
			}
		});
		
		// Hide elements on initialization
		document.getElementsByClassName('hideOnInit').invoke("hide");
		
		this.map = new Map(this, $("map"), point);
		this.gMap = this.map.gMap;
		this.geocoder = new GClientGeocoder();
		
		// Draw map
		this.draw();

		// Put Kiteentaksi on the map.
		/*
		var x = new GLatLng(point.lat, point.lng)
		var marker = new GMarker(x);
		this.gMap.addOverlay(marker);
		marker.openInfoWindowHtml("Kiteen Aluetaksi Oy<br />Keisarinkuja 3<br />82500 Kitee<br />013-10066");
		*/
		
		// Observe and execute app functionality
		this.observer();
		
	},

	// 	Buffers a method call, new call intercepts old one
	bufferMethodCall: function (object, method) {
	
		if (!this.waitForUser) {
				
			if (this.timerTimeout) {
				
				clearTimeout(this.timerTimeout);
      			delete this.timerTimeout;
				
			}

			this.timerTimeout = setTimeout(method.bind(object), 1400);
			
		}
	},

	checkAddress: function(address) 
	{
	  	
		if (this.geocoder) {

			this.geocoder.getLatLng(
							   address,
							   function(point) {
								   
				if (!point) {
			
					return false;
					
				} else {

						this.map.clear();
						var marker = new GMarker(point, {icon: Map.RedIcon, title: address});
						this.gMap.addOverlay(marker);
             			marker.openInfoWindowHtml(address);
					
				}
			
			}.bind(this));
			
		}
	  
	},
	
	draw: function()
	{

		var w = 400;
		var h = 400;
			
		$('map').setStyle({ width: w +"px", height: h +"px" });
		
	},
	
	observer: function() {
		
		// User wants to submit
		Event.observe('routeForm', 'submit', function(e) {
													  
			if (!$F('from') || $F('from') == "" || !$F('to') || $F('to') == "") {
				
				alert("Täytä sekä lähtöosoite että määränpää.");
				
			} else {
				
				try {
					
					this.map.route.from = $F('from');
					this.map.route.to = $F('to');
					this.dirs = new Directions(this, this.map);
					
					if (this.map.route.from && this.map.route.to) {
						
						this.map.clear();
						this.dirs.setDirections(this.map.route.from, this.map.route.to);
						
					}
					
				} catch(e) {
					
					alert("App: " + e);
					
				}
				
			}
			
		}.bind(this));

		// User wants to fill the form again
		Event.observe('submit2', 'click', function(e) {
													  
				$('results').hide();
				$('routeForm').show();
				
				this.map.clear();
													  
		}.bind(this));

		// User typed an address, check it beforehand
		Event.observe('from', 'blur', function(e) {
			
			this.checkAddress($F('from'));
													  
		}.bind(this));

		// User typed an address, check it beforehand
		Event.observe('to', 'blur', function(e) {
			
			this.checkAddress($F('to'));
													  
		}.bind(this));
		
	},

	showResults: function()
	{

		try {
			
			var time_id = start_prices[$F('time')];
			var start_price = time_id.price;
			
			var persons_id = per_km_prices[$F('persons')];
			var km_price = persons_id.price;
			
			this.distance = this.d.meters / 1000;
			
			// Final price in euros.
			this.price = ( start_price + km_price * this.distance ) / 100;
			
			this.time.hours = Math.floor(this.t.seconds / 3600);
			this.time.minutes = Math.floor((this.t.seconds - (this.time.hours * 3600)) / 60);
			this.time.sec = this.t.seconds % 60;
			
			$('routeForm').hide();
			
			$('summary_text').update('<p>Matkan pituus on <strong>' + this.distance + ' km</strong>, arvioitu ajoaika \
						  on noin <strong>' + this.time.hours + ' tuntia ' + this.time.minutes + ' minuuttia</strong>.</p>');
			$('start_text').update(time_id.description);
			
			// Have to convert number to string manually.
			$('start_price').update((start_price / 100).toString() + ' e');
			$('km_text').update(persons_id.description);
			$('km_price').update((Math.round(Math.round(km_price * this.distance * 100) / 100) / 100).toString() + ' e');
			$('total_price').update(Math.round(this.price * 100) / 100 + ' e');

			$('results').show();
		
		} catch(e) {
			
			alert("Results: " + e);
			
		}
		
	},
	
	test: function() {
		
		alert("hi");
		
	}
	
});
