var kamMaps = new Class({

	geocoder : null,
	map : null,
	markers : [],

	initialize: function() {
		this.geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(40.768505,-111.853244);
		var myOptions = {
			zoom: 8,
			center: latlng,
			disableDefaultUI: true,
			zoomControl: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		this.map = new google.maps.Map(document.getElementById("mapCanvas"), myOptions);		
	},

	addPostCode: function(zip) {
		this.geocoder.geocode( { 'address': zip}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK){
				this.map.setCenter(results[0].geometry.location);
				var marker = new google.maps.Marker({
					map: this.map,
					position: results[0].geometry.location,
					name: zip
				});
				this.markers.push(marker);
			} else {
//				alert("Geocode was not successful for the following reason: " + status);
			}
	  }.bind(this));	
	},

	checkZip: function(zip){
		var distance = Number.MAX_VALUE;
		var index = 0;
		this.geocoder.geocode( { 'address': zip}, function(results, status){
			if (status == google.maps.GeocoderStatus.OK){
				for(ix=0; ix< this.markers.length; ix++){
					var tmp = this.getDistance(results[0].geometry.location, this.markers[ix].position);
					if (tmp < distance){
						distance = tmp;
						index = ix;
				  	}
			 	}
			 	alert('nearest zipcode is :' + this.markers[index].name);
			}
  		}.bind(this));
	},

	getDistance: function(latlng1, latlng2){
		var R = 6371; // Radius of the earth in km
		var dLat = (latlng2.lat()-latlng1.lat()) * Math.PI / 180;  // Javascript functions in radians
		var dLon = (latlng2.lng()-latlng1.lng()) * Math.PI / 180;
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(latlng1.lat()  * Math.PI / 180) * Math.cos(latlng2.lat()  * Math.PI / 180) *		Math.sin(dLon/2) * Math.sin(dLon/2);
  		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  		var d = R * c; // Distance in km
  		d = d * 0.621371192;
  		
		return d;
	}
});
