/**
* @name HiveGeoutils
* @version 0.9.0
* @author Joe Johnston <joe@socialhive.org>
* @copyright (c) 2009 Joe Johnston
* http://socialhive.org/hivemaps
* http://code.google.com/p/hivemaps
*
* Extends SOCIALHIVE.geo
*
* Refer to Chris Veness's code for lat,lon goodies ...
* http://www.movable-type.co.uk/scripts/latlong.html
**/

/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/

(function($){
	var defaultLang = 'en';
	// earth's mean radius
	var earthRadiusUnits = {
		'km': 6371,
		'mi': 3959,
		'm': 6371000
	};
	
	function lookupCountryCode(code, lang) {
	  return ISO3166[(lang || defaultLang)].codes[code];
	}
	
	var GeoConvert = {
		// convert degrees to radians
		degreesToRad: function(d) {
	  	return d * Math.PI / 180;
		},
		// convert radians to degrees (signed)
	 	radToDegrees: function(r) {
	  	return r * 180 / Math.PI;
		},
		// convert radians to degrees (as bearing: 0...360)
	 	radToBearing: function(r) {  
	  	return (this.radToDegrees(r)+360) % 360;
		}
	};
	
  
	function distance(lat1, lon1, lat2, lon2, units) {
		var R = earthRadiusUnits[(units || 'km')]; // earth's mean radius
		return Math.acos(Math.sin(GeoConvert.degreesToRad(lat1))*Math.sin(GeoConvert.degreesToRad(lat2)) +
			Math.cos(GeoConvert.degreesToRad(lat1))*Math.cos(GeoConvert.degreesToRad(lat2))*Math.cos(GeoConvert.degreesToRad(lon2-lon1))) * R;
	}


  var HiveGeo = {
    lookupCountryCode: lookupCountryCode,
		distance: distance,
		convert: GeoConvert
  };
  
  if (!window.SOCIALHIVE)
    window.SOCIALHIVE = {};
  if (!window.SOCIALHIVE.geo)
    window.SOCIALHIVE.geo = {};
  $.extend(window.SOCIALHIVE.geo, HiveGeo);
})(jQuery);
