function Scroller(inElement, reversed)
{
    this.element = inElement;
	this.position = ('0,0');
    this.reversed = reversed || 'none';
    this.setBounds();
    this.lastDirection = this.direction;
    var self = this;
    this.element.addEventListener('touchstart', function(e) { return self.onTouchStart(e) }, false);
	window.addEventListener('orientationchange', function(e) { return self.onOrientationChange() }, false);
}

Scroller.prototype = {
	get position()
	{
	    return this._position;
	},
	
	// position strings are "x,y" with no units
	set position(pos)
	{
		if (this._position == undefined) {
			this._position = '0,0';
		}
			
	    var components = pos.split(',')
	    var deltaX = components[0] - 0;
	    var deltaY = components[1] - 0;
	    
	    if (this.reverse) {
		    var temp = deltaX;
		    deltaX = deltaY;
		    deltaY = temp;
	    }

		if (!this.ignoreBounds) {
			if (this.x + deltaX > this.minX) { deltaX = 0; }
			if (this.x + deltaX < -this.maxX) { deltaX = 0; }
			
			if (this.y + deltaY > this.minY) { deltaY = 0; }
			if (this.y + deltaY < -this.maxY) { deltaY = 0; }
		}
				
	    this._position = (this.x + deltaX) + ',' + (this.y + deltaY);
	    var currentTransform = new WebKitCSSMatrix(window.getComputedStyle(this.element).webkitTransform);
		this.element.style.webkitTransform = currentTransform.translate(deltaX,deltaY);
	 
	},
	
	onOrientationChange: function()
	{
		if (this.direction != this.lastDirection) {
		    if (this.reversed == 'both' || this.reversed == 'none') {
				var x = this.x;
				var y = this.y;
				
				this.ignoreBounds = true;
		        this.position = (y-this.x) + ',' + (x-this.y);
		        this.ignoreBounds = false;
		    }
	        this.setBounds();
 		    this.lastDirection = this.direction;
       }
	},
	
	setBounds: function()
	{
		computedStyle = window.getComputedStyle(this.element);
		fullWidth = parseInt(computedStyle.width) + parseInt(computedStyle.marginLeft) + parseInt(computedStyle.marginRight) + parseInt(computedStyle.paddingLeft) + parseInt(computedStyle.paddingRight);
		fullHeight = parseInt(computedStyle.height) + parseInt(computedStyle.marginTop) + parseInt(computedStyle.marginBottom) + parseInt(computedStyle.paddingTop) + parseInt(computedStyle.paddingBottom);
		xOffset = parseInt(computedStyle.left) || 0;
		yOffset = parseInt(computedStyle.top) || 0;
		
		this.minX = 0;
		this.maxX = fullWidth + xOffset - document.documentElement.clientWidth;
		this.minY = 0;
		this.maxY = fullHeight + yOffset - document.documentElement.clientHeight;
	},
	
	get direction()
	{
		if (window.orientation == 0 || window.orientation == 180) {
		    return 'vertical';
	    } else {
	    	return 'horizontal';
	    }
	},
	 
	get reverse()
	{
    	return (this.reversed == this.direction) || (this.reversed == 'both');
	},
	 
	// position strings are "x,y" with no units
	get x()
	{
	    return parseInt(this._position.split(',')[0]);
	},
	 
	set x(inX)
	{
	    var comps = this._position.split(',');
	    comps[0] = inX;
	    this.position = comps.join(',');
	},
	 
	get y()
	{
	    return parseInt(this._position.split(',')[1]);
	},
	 
	set y(inY)
	{
	    var comps = this._position.split(',');
	    comps[1] = inY;
	    this.position = comps.join(',');
	},
	
	onTouchStart: function(e)
	{
	    // Start tracking when the first finger comes down in this element
	    if (e.targetTouches.length != 1)
	        return false;
	 
	    this.startX = e.targetTouches[0].clientX;
	    this.startY = e.targetTouches[0].clientY;
	 
	    var self = this;
	    this.element.addEventListener('touchmove', function(e) { return self.onTouchMove(e) }, false);
	    this.element.addEventListener('touchend', function(e) { return self.onTouchEnd(e) }, false);
	 
	    return false;
	},
	
	onTouchMove: function(e)
	{
	    // Prevent the browser from doing its default thing (scroll, zoom)
	    e.preventDefault();
	 
	    // Don't track motion when multiple touches are down in this element (that's a gesture)
	    if (e.targetTouches.length != 1)
	        return false;
	 
	    var leftDelta = e.targetTouches[0].clientX - this.startX;
	    var topDelta = e.targetTouches[0].clientY - this.startY;

	 	if (this.direction == 'vertical') {
		    this.y = topDelta;	 	
	 	} else if (this.direction == 'horizontal') {
		    this.x = leftDelta;	
	 	} else {
		    this.position = leftDelta + ',' + topDelta;	 	
	 	}
	 
	    this.startX = e.targetTouches[0].clientX;
	    this.startY = e.targetTouches[0].clientY;
	 
	    return false;
	},
	
	onTouchEnd: function(e)
	{
	    // Prevent the browser from doing its default thing (scroll, zoom)
	    e.preventDefault();
	 
	    // Stop tracking when the last finger is removed from this element
	    if (e.targetTouches.length > 0)
	        return false;
	 
	 
		this.element.removeEventListener('touchmove', function(e) { return self.onTouchMove(e) }, false);
	    this.element.removeEventListener('touchend', function(e) { return self.onTouchEnd(e) }, false);
	 
	    return false;
	},
}

function distance(lat1,lon1,lat2,lon2) {
	// from http://www.movable-type.co.uk/scripts/latlong.html
	var R = 6371; // km
	var dLat = (lat2-lat1).toRad();
	var dLon = (lon2-lon1).toRad(); 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) * 
	        Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	
	return d;
}

Number.prototype.toRad = function() {  // convert degrees to radians 
  return this * Math.PI / 180; 
} 

function getLocation() {
    if (navigator.geolocation) {
    	navigator.geolocation.getCurrentPosition(closestStation); }
}

function closestStation(position) {
	currentLat = position.coords.latitude;
	currentLon = position.coords.longitude;

	var weatherStations = {
		'Melbourne':
			{'lat':-37.81,'lon':144.97},
		'Melbourne Airport':
			{'lat':-37.67,'lon':144.83},
		'Avalon Airport':
			{'lat':-38.03,'lon':144.48},
		'Cerberus':
			{'lat':-38.36,'lon':145.18},
		'Coldstream':
			{'lat':-37.72,'lon':145.41},
		'Essendon Airport':
			{'lat':-37.73,'lon':144.91},
		'Frankston':
			{'lat':-38.15,'lon':145.12},
		'Geelong Airport':
			{'lat':-38.22,'lon':144.33},
		'Laverton':
			{'lat':-37.86,'lon':144.76}
		};
	
	var closest = 0;
	for (var i in weatherStations) {
		weatherStations[i]['distance'] = distance(weatherStations[i]['lat'], weatherStations[i]['lon'], currentLat, currentLon);
		if (!weatherStations[closest]) { closest = i }
		if (weatherStations[i]['distance'] < weatherStations[closest]['distance']) {
			closest = i;
		}
		window.console.log(i + ': ' + weatherStations[i]['distance'] + 'km');
	}
	window.console.log('Closest Station: ' + closest);
}

function loaded()
{
	if (navigator.userAgent.indexOf('iPhone') > 0) {
		// getLocation();
		window.scrollTo(0,1);
	    new Scroller(document.getElementById('forecast'));
	    new Scroller(document.getElementById('observations'), 'vertical');
	    if (window.navigator.standalone) {
			document.addEventListener('touchmove', function(e) { e.preventDefault(); }, true); }
	}
}

window.addEventListener('load', loaded, true);
