var onereason = onereason || {};

onereason.location = ( function ( ) {
    var ourpos = {
		latitude: 55.61,
		longitude: 12.98
	};
	var msg;
	
	var init = function () {
		var pos = google.loader.ClientLocation;
		if ( !!pos ) {
			if ( pos && pos.latitude ) distance = distHaversine( ourpos.latitude, ourpos.longitude, pos.latitude, pos.longitude );
			if ( distance < 1 ) 								
				msg = "You know, you are really close by! It would be a shame if you didn't visit.";
			else if ( pos && pos.address.city == "Malmö" ) 		
				msg = "So we're in the same city! Why don't you drop us a visit?";
			else if ( pos && pos.address.city == "København" ) 		
				msg = "Hey, you're just across the Øresund! You could drop by in no time!";
			else if ( pos && pos.address.region == "Skåne" ) 
				msg = "Skåne isn't that big! Let us know when you're around Malmö";
			else if ( pos && pos.address.country_code == "SE" )	
				msg = "Hey we're in Sweden too you know! Say hello when you visit the southern tip of the country";
			else if ( distance > 3500 )
				msg = "I see you're on a different continent. Let's keep in touch so we will know when our paths cross!";
			else 
				msg = "You're in Europe, we're in Europe! Let's hope our paths cross some day soon!";
				
			//	add message to page
			var txt = document.createTextNode( msg )
			document.getElementById( 'distance' ).appendChild( txt );
			
			//	check if welcome message could be translated to user's browser language if != en
			if ( window.navigator.language && window.navigator.language != 'en' && google.language ) {
				var container = document.getElementById('home').getElementsByTagName('h2')[0];
				google.language.translate( container.innerHTML, "en", window.navigator.language.substr(0,2), function( result ) {
					if ( !result.error ) {
						container.innerHTML = result.translation;
					}
				});
			}
		}
	}
	
	
	/*
	 * Use Haversine formula to Calculate distance (in km) between two points specified by 
	 * latitude/longitude (in numeric degrees)
	 *
	 * example usage from form:
	 *   result.value = LatLon.distHaversine(lat1.value.parseDeg(), long1.value.parseDeg(), 
	 *                                       lat2.value.parseDeg(), long2.value.parseDeg());
	 * where lat1, long1, lat2, long2, and result are form fields
	 */
	var distHaversine = function( lat1, lon1, lat2, lon2 ) {
		var R = 6371; // earth's mean radius in km
		var dLat = ( lat2 - lat1 ).toRad();
		var dLon = ( lon2 - lon1 ).toRad();
		lat1 = lat1.toRad(), lat2 = lat2.toRad();
		
		var a = Math.sin( dLat / 2 ) * Math.sin( dLat / 2 ) +
			Math.cos( lat1 ) * Math.cos( lat2 ) * 
			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;
	}
    
    google.setOnLoadCallback( init );
	
})( );
