
var infoTpl = require (__dirname +'/info.xml');

var gmapsIsLoaded = false;
var gmapsLoadedCallback;

Hedera.Location = new Class
({
	Extends: Hedera.Form

	,locations: null

	,activate: function ()
	{
		this.gui.loaderPush ();
		
		this.infoBuilder = new Vn.Builder();
		this.infoBuilder.compileString (infoTpl);

		var sql = 'SELECT lat, lng, title, address, postcode, city, province, phone, language FROM location';
		this.conn.execQuery (sql, this.onLocationsDone.bind (this));
	
		if (!gmapsIsLoaded)
		{
			gmapsLoadedCallback = this.gmapsLoaded.bind (this);
			Vn.includeJs ('https://maps.google.com/maps/api/js'+
				'?sensor=false&callback=gmapsLoadedCallback', null, true);
		}
		else
			this.gmapsLoaded ();
	}

	,onLocationsDone: function (resultSet)
	{
		this.locations = resultSet.fetchArray ();
		this.allLoaded ();
	}

	,gmapsLoaded: function ()
	{
		this.gui.loaderPop ();
		gmapsIsLoaded = true;
		this.allLoaded ();
	}

	,allLoaded: function ()
	{
		if (!this.locations || !gmapsIsLoaded)
			return;

		var options = {
			 zoom: 4
			,mapTypeId: google.maps.MapTypeId.ROADMAP
			,center: new google.maps.LatLng (46.0, 4.0)
		};

		var div = this.$.form;
		var gmap = new google.maps.Map (div, options);

		locations.forEach (function (location) {
			this.createMarker (location, gmap);
		}, this);
	}
	
	,createMarker: function (location, gmap)
	{
		var scope = this.infoBuilder.load (this.doc, this, null, null, location);
		var div = scope.getMain ();
		
		var lat = new google.maps.LatLng (
			location.lat,
			location.lng
		);

		var marker = new google.maps.Marker ({
			 position: lat
			,tilte: location.title
			,map: gmap
		});

		var infoWindow = new google.maps.InfoWindow ({
			 content: div
		});

		google.maps.event.addListener (marker, 'click',
			this.openInfoWindow.bind (this, infoWindow, gmap, marker));
 		
 		if (Vn.Locale.language
		&& Vn.Locale.language == location.language)
 			this.openInfoWindow (infoWindow, gmap, marker);
	}
	
	,openInfoWindow: function (infoWindow, gmap, marker)
	{
		if (this.openedWindow)
			this.openedWindow.close ();

		infoWindow.open (gmap, marker);
		this.openedWindow = infoWindow;
	}
});

