//Begins 
function loadScript() {
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
		'&callback=initialize';
	document.body.appendChild(script);
}

window.onload = loadScript;
//var executed=false;
var projectpng='/static/images/google_maps_icon/project.png';
var z;
var map;

var marker;
var mapOptions;
var ZOOM=4;
//Functions for current real time positions

function geocodePosition(pos) {
	geocoder = new google.maps.Geocoder();
	geocoder.geocode({
		latLng: pos
	},

	function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			$('[name=location]').val(results[0].formatted_address);
			$('[name=location_lat]').val(results[0].geometry.location.A);
			$('[name=location_lng]').val(results[0].geometry.location.F);
			$("#mapErrorMsg").hide(100);
		} else {
			$("#mapErrorMsg").html('Cannot determine address at this location.' + status).show(100);
		}
	});
}    	
function geocodeAddress() {
	var ajson = "https://maps.googleapis.com/maps/api/geocode/json?address=" + $('[name=location]').val()
	$.ajax({
		dataType: "json",
		url: ajson,
		success: function(d) {
			z = d.results[0].geometry.location
			$('[name=location_lat]').val(z.lat);
			$('[name=location_lng]').val(z.lng);
			marker.setPosition(z);
			map.setCenter(z);
		}
	});
}

function initializeProjectEdit() {
	var posLatLngHome = new google.maps.LatLng($('[name=location_lat]').val(), $('[name=location_lng]').val());
	marker = new google.maps.Marker({
		position: posLatLngHome,
		draggable: true,
		animation: google.maps.Animation.DROP,
		map: map,
		title: 'Office',
		icon: projectpng

	});
	google.maps.event.addListener(marker, 'dragend', function() {
		geocodePosition(marker.getPosition());
	});



}
function initialize() {
	var posLatLngHome = new google.maps.LatLng($('[name=location_lat]').val(), $('[name=location_lng]').val());
	mapOptions = {
		zoom: ZOOM,
		center: posLatLngHome,
            scrollwheel: false
	}
	map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
	
	marker = new google.maps.Marker({
		position: posLatLngHome,
		draggable: true,
		animation: google.maps.Animation.DROP,
		map: map,
		title: 'I was Office!',
		icon: projectpng

	});
	google.maps.event.addListener(marker, 'dragend', function() {
 		geocodePosition(marker.getPosition());
 	});
}
     