var angleMemory = -1,
	rotation = 0,
	currentAngle = 0;

function onDeviceOrientation(dataEvent) {
	"use strict";
	if (dataEvent.alpha !== angleMemory) {
		var angle = dataEvent.alpha,
			deltaAngle,
			text = '',
			beta = dataEvent.beta,
			gamma = dataEvent.gamma,
			tiltportrait = '',
			tiltlandscape = '';
		
		
		if (beta <= -0.5) {
			tiltportrait = 'UP';
		}else if (beta >= 0.5){
			tiltportrait = 'DOWN';	
		} else  {
			tiltportrait = 'LEVEL';	
		}
		
		if (gamma <= -0.5) {
			tiltlandscape = 'LEFT UP';
		}else if (gamma >= 0.5){
			tiltlandscape = 'RIGHT UP';	
		} else  {
			tiltlandscape = 'LEVEL';	
		}
		
		
		if (angle < 68 || angle > 292) {
			text += 'N'; // north
		} else if (angle > 112 && angle < 248) {
			text += 'S'; // south
		}
		if (angle > 22 && angle < 158) {
			text += 'E'; // east
		} else if (angle > 202 && angle < 338) {
			text += 'W'; // west
		}

		deltaAngle = angleMemory - angle;
		if (Math.abs(deltaAngle) > 180) {
			if (deltaAngle > 0) {
				rotation -= ((360 - angleMemory) + angle);
			} else {
				rotation += (angleMemory + (360 - angle));
			}
		} else {
			rotation += deltaAngle;
		}

		angleMemory = angle;
		
		
		$('#direction').text(text);
		
		$("#angle").html(Math.round(angle) + "<sup>o</sup>");
			beta = Math.round(beta);
			gamma = Math.round(gamma);
			
			$('#overlaylevel').css('-moz-transform', 'translate(' + gamma + 'px,'+beta+'px)');
			
			beta = Math.abs(beta);
			gamma = Math.abs(gamma);
		$('#beta').html(beta + "<sup>o</sup> " + tiltportrait);
		$('#gamma').html(gamma + "<sup>o</sup> " + tiltlandscape);
			
		currentAngle = angle;
		
		$('#rotation').css('-moz-transform', 'rotate(' + rotation + 'deg)');
		/*
		$('#rotation').css('-webkit-transform', 'rotate(' + rotation + 'deg)');
		*/
		
		if ((beta<=1)&&(gamma<=1)&&(angle<=1)){
			$('#location').html('WOW, impressive!');
		} else if ((beta<=0.5)&&(gamma<=0.5)){
			$('#location').html('Perfectly level...');
		} else if ((beta<=1)&&(gamma<=1)){
			$('#location').html('Almost level...');
		} else{
			$('#location').html('Somewhere on Earth');
		}
	}
}

function incrementNumber(end){
	
    //Numbers
    var num = currentAngle;
    var perMinute = 75;
    var perSecond = perMinute / 60;
    
    //Element selection
    var count = document.getElementById("angle");
    
    function update(){
    	//Add the per-second value to the total
        num += Math.round(perSecond);
        //Display the count rounded without a decimal
        count.html(Math.round(num) + "<sup>o</sup>");
    }
    
    //Run the update function once every second
	while (num < end)
    	setInterval(update, 25 / perSecond);
	
	
	}

function startSensor() {
	"use strict";
	window.addEventListener("deviceorientation", onDeviceOrientation, false);
	
	window.addEventListener("compassneedscalibration", function(event) {
          alert('Your compass needs calibrating! Wave your device in a figure-eight motion');
          event.preventDefault();
      }, true);
}

function getLocation(){ 
	// Now fetch once, later on get constantly when in motion
	
	// Request a position. We accept positions whose age is not
    // greater than 10 minutes. If the user agent does not have a
    // fresh enough cached position object, it will automatically
    // acquire a new one.
		//navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge:600000});
		options = {
			enableHighAccuracy: false,
			timeout: 5000,
			maximumAge: 3600000
	  	};
		var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options);
		//var id = navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);
	
		function successCallback(position) {
		  // By using the 'maximumAge' option above, the position
		  // object is guaranteed to be at most 10 minutes old.
		  //$("#coordinates").html(LocationFormatter.decimalToDMS((position.coords.latitude).toFixed(5)) + ' - ' + LocationFormatter.decimalToDMS((position.coords.longitude).toFixed(5)));
		$("#coordinates").html(LocationFormatter.decimalLatToDMS(position.coords.latitude) + ' - ' + LocationFormatter.decimalLongToDMS(position.coords.longitude));
		}
	
		function errorCallback(error) {
		  // Update a div element with error.message.
		}
	
}

// Decimal Degrees = Degrees + minutes/60 + seconds/3600
// use: LocationFormatter.DMSToDecimal( 45, 35, 38, LocationFormatter.SOUTH );
// or:  LocationFormatter.decimalToDMS( -45.59389 );

function LocationFormatter(){
};

LocationFormatter.NORTH = 'N';
LocationFormatter.SOUTH = 'S';
LocationFormatter.EAST = 'E';
LocationFormatter.WEST = 'W';

LocationFormatter.roundToDecimal = function( inputNum, numPoints ) {
 var multiplier = Math.pow( 10, numPoints );
 return Math.round( inputNum * multiplier ) / multiplier;
};

LocationFormatter.decimalToDMS = function( location, hemisphere ){
 if( location < 0 ) location *= -1; // strip dash '-'
 
 var degrees = Math.floor( location );          // strip decimal remainer for degrees
 var minutesFromRemainder = ( location - degrees ) * 60;       // multiply the remainer by 60
 var minutes = Math.floor( minutesFromRemainder );       // get minutes from integer
 var secondsFromRemainder = ( minutesFromRemainder - minutes ) * 60;   // multiply the remainer by 60
 var seconds = LocationFormatter.roundToDecimal( secondsFromRemainder, 2 ); // get minutes by rounding to integer

 return degrees + '° ' + minutes + "' " + seconds + '" ' + hemisphere;
};

LocationFormatter.decimalLatToDMS = function( location ){
 var hemisphere = ( location < 0 ) ? LocationFormatter.SOUTH : LocationFormatter.NORTH; // south if negative
 return LocationFormatter.decimalToDMS( location, hemisphere );
};

LocationFormatter.decimalLongToDMS = function( location ){
 var hemisphere = ( location < 0 ) ? LocationFormatter.WEST : LocationFormatter.EAST;  // west if negative
 return LocationFormatter.decimalToDMS( location, hemisphere );
};

LocationFormatter.DMSToDecimal = function( degrees, minutes, seconds, hemisphere ){
 var ddVal = degrees + minutes / 60 + seconds / 3600;
 ddVal = ( hemisphere == LocationFormatter.SOUTH || hemisphere == LocationFormatter.WEST ) ? ddVal * -1 : ddVal;
 return LocationFormatter.roundToDecimal( ddVal, 5 );  
};



function init() {
	"use strict";
	startSensor();
	getLocation();
}



$(document).ready(init);
