/*

name         Google Maps support
author       Mark de Jong (http://www.spellcoder.nl)
copyright    (c) Senna Multimedia / Mark de Jong
version      march 2010

*/

var trackstyles = [ // undefined
					{ normal:	{ color: '#000000', weight: 3, opacity: 0.4}
					, hover:	{ color: '#AA6600', weight: 5, opacity: 0.85}
					, timebar:	{ color: 'rgba(255,255,255,0.6)' }
					}
					, // to school
					{ normal:	{ color: '#DD0000', weight: 3, opacity: 0.4}
					, hover:	{ color: '#FF6600', weight: 5, opacity: 0.85}
					, timebar:	{ color: 'rgba(255,128,0,0.6)' }
					}
					, // to home
					{ normal:	{ color: '#0000AA', weight: 3, opacity: 0.4}
					, hover:	{ color: '#0066FF', weight: 5, opacity: 0.85}
					, timebar:	{ color: 'rgba(0,128,255,0.6)' }
					}
					, // unknown
					{ normal:	{ color: '#AA00AA', weight: 3, opacity: 0.4}
					, hover:	{ color: '#FF66FF', weight: 5, opacity: 0.85}
					, timebar:	{ color: 'rgba(255,128,255,0.6)' }
					}
				];

spcMapTrack = function(map,item,options)
{
	console.log('Draw tracking track #'+item.data.id);//+' ('+trackpoints.length+' points, '+stoppoints.length+' stoppoints)');

	/*
	console.group();
	console.log('creating track instance');
	console.log(item);
	console.groupEnd();
	*/
	this.map = map;
	this.visible = false;
//	this.trackpoints = (typeof options != "undefined" && typeof options.pointssource == "string") ? item.data.track["pointssource"] : item.data.track.trackpoints;
	this.trackpoints = (typeof options != "undefined" && typeof options.pointssource == "string") ? item.data.track.trackpointsraw : item.data.track.trackpoints;

	if (!this.trackpoints)
		console.log("No valid trackpoints source ("+options.pointssource+")");

//	console.log(item.data.track);
//console.log(this.trackpoints);
//		console.log("No valid trackpoints source ("+options.pointssource+")");

	//this.arrows = [];
	this.points = [];
	
	this.posattimeitem = null;// id if marker which show's the position of a traveller on the track at a certain time

	var track = this.track = item.data;
	this.item = item; // complete item (take care of circ. ref)
	
	var stoppoints = item.data.track.stoppoints;

	for (var punt=0; punt < stoppoints.length; punt++)
	{
		var newitemid = this.addStopPoint(track.id, stoppoints[punt]);
		this.map.drawItemById(newitemid);
	}

	var trackstyle = trackstyles[item.data.type > 0 ? item.data.type : 0].normal;
	
	/******************************************************************************/
	// Draw an icon at the starting point of the track
	//var newitemid = this.addStartPoint(track.id, trackpoints[0]);
	//this.map.drawItemById(newitemid);

	// convert points array to an google.maps.LatLng array
	var punten = [];
	var trackpoints = this.trackpoints;
	for (var punt=0; punt < trackpoints.length; punt++)
		punten.push( new google.maps.LatLng( trackpoints[punt].lat, trackpoints[punt].lng ));

	// Draw an icon at the starting point of the track
	//var newitemid = this.addStartPoint(track.id, trackpoints[0]);
	//this.map.drawItemById(newitemid);
	
	//var color = test[track].hispeed ? '#0000ff' : '#ff0000';
	//var polyline = new GPolyline(punten, trackstyle.color, trackstyle.weight, trackstyle.opacity);
	var polyline = new google.maps.Polyline(
			{ map: this.map.gmap
			, path: punten
			, strokeColor: trackstyle.color
			, strokeWeight: trackstyle.weight
			, strokeOpacity: trackstyle.opacity
			});

	this.map.attachEventListeners(polyline, item.id, "track");

	this.overlay = polyline;
	this.overlay.realid = item.id;

	//this.showboundsforpolyline(polyline);

	//mygmap.centerOnItemById(newitemobj.id);

	//this.arrows = this.midArrows(punten);
}

spcMapTrack.prototype.hide = function()
{
	console.log("Track hide");

	this.overlay.setMap(null);

	if (this.posattimeitem > 0)
		mapmeta.getItemById(this.posattimeitem).instance.hide();
}

spcMapTrack.prototype.show = function()
{
	//console.log("Track show");

	this.overlay.setMap(this.map.gmap);

	if (this.posattimeitem > 0)
		mapmeta.getItemById(this.posattimeitem).instance.show();
}

spcMapTrack.prototype.setHover = function(hover)
{
	console.log('New hoverstate: '+(hover?'true':'false'));

	var tstyle;

	if (hover)
	{
		if (trackstyles[this.track.type]) {	
		tstyle = trackstyles[this.track.type].hover;
		}

		// fixme: can be done nicer with some kind of event callback
		product.showTrackSpecs(this.track.id);

		// development option
		if (product.state.devmode)
		{
			if (!this.rawtrack)
			{
				var itemclone = { shape: this.item.shape
								, type: this.item.type
								, data: JSON.parse(JSON.stringify(this.item.data))
								};
				var rawtrackitem = mapmeta.addMapItem2(itemclone);
				this.rawtrack = this.map.drawItemByRef(rawtrackitem, { pointssource: "trackpointsraw" });
			}
			else
			{
				this.rawtrack.show();
			}
		}
		
		product.sidebar.popup.setAnchor("topleft");
		product.sidebar.popup.position(10,10);
	}
	else
	{
		// development option
		if (this.rawtrack)
			this.rawtrack.hide();

		if (trackstyles[this.track.type]) {	
			tstyle = trackstyles[this.track.type].normal;
			this.overlay.setOptions({strokeColor: tstyle.color
						,strokeOpacity: tstyle.opacity
						,strokeWeight: tstyle.weight
						});
		}
	
		product.sidebar.popup.hide();
	
	}

	
}

spcMapTrack.prototype.destroy = function()
{
	console.log('Disabling track #'+trackid);
	
	this.removeOverlaysFromList(this.arrows);
	this.arrows = [];

	// remove start/stoppoints
	//this.removeOverlaysFromList(this.points);
//	this.map.removeItemsByOwnerId(trackid); // FIXME
			
	//this.gmap.removeOverlay(this.trackrefs[tel].overlay); // GMaps V2
	this.trackrefs[tel].overlay.set_map(null);
	this.visible = false;
}

spcMapTrack.prototype.removeOverlaysFromList = function(overlayslist)
{
	for(var tel=0; tel<overlayslist.length; tel)
		this.map.gmap.removeOverlay(overlayslist[tel]);
}

spcMapTrack.prototype.addStopPoint = function(trackid,point)
{
	// Maak een punt voor plekken waar tijdelijk gestopt is
	var newitem =	{ "name":		'Stoppunt'
					, "type":		12
					, "icon":		12 // TODO: movie icon
					, shape:		1
					, "shortdesc":	'Een stoppunt'
					, "photo":		null
					, "lat":		point.lat
					, "long":		point.lng
					, "published":	point.published
					, trackid:		trackid

					, temporary:	true
					, "volatile":	true
					, ownerid:		trackid
					};

	return mapmeta.addMapItem2(newitem);
}

spcMapTrack.prototype.addStartPoint = function(trackid,point)
{
	// Begin van een track
	var newitem =	{ "name":		'Beginpunt'
					, "type":		1
					, "icon":		3 // TODO: movie icon
					, shape:		1
					, "shortdesc":	''
					, "photo":		null
					, "lat":		point.lat
					, "long":		point.lng
					, "published":	point.published
					, trackid:		trackid

					, temporary:	true
					, "volatile":	true
					, ownerid:		trackid
					};

	return mapmeta.addMapItem2(newitem);
}

spcMapTrack.prototype.addPositionAtTimePoints = function()
{
	var point = this.track.track.trackpoints[0]; // take first point as initial position

	// redefine so as not to keep changing the same variable instance		
	var newitem =	{ "name":		"Track points"
					, "type":		100
					, "icon":		100
					, shape:		1
					, "shortdesc":	""
					, "photo":		null
					, "lat":		point.lat
					, "long":		point.lng
					, published:	true
					//, trackid:		trackid
					
					, temporary:	false //true
					, "volatile":	false //true
					, ownerid:		this.item.id
					};
	
	newitem = mapmeta.addMapItem2(newitem);			
	mygmap.drawItemByRef(newitem);
	return newitem;
}

spcGMap.prototype.drawTrack = function spcGMap_drawTrack(track)
{
	//if (this.trackIsVisible(track.id))
	//	return;

	/*	
	console.group();
	console.log('drawTrack');
	console.log(track);
	console.groupEnd();
	*/

	if (!track)
	{
		console.error('Cannot draw track, track is empty.');
		return;
	}

	var trackitem = this.getItemByTrackId(track.id);
	if (trackitem)
	{
		trackitem.instance.show();
		return;
	}

	/*
	console.group();
	console.log("Track:");
	console.log(trackitem);
	console.groupEnd();
	*/

	//this.track.track.trackpoints.length
	if (track.track.trackpoints.length < 2)
	{
		console.warn("Ignoring request to draw track #"+track.id+" because it has fewer than two points.");
		return;
	}
	
	// create an item entry for the track
	var newitem =	{ "name":		'Track'
					, "type":		3
					, "icon":		3

					, shape:		2
					, lat:			null //trackpoints[0].lat.lat
					, long:			null //trackpoints[0].lat.lng

					, "shortdesc":	''
					, "photo":		null
					, "temporary":	true
					, "published":	track.published
					
					, data:			track
					, trackid:		track.id
					};

	var itemid = mapmeta.addMapItem(newitem);
	this.drawItemById(itemid);
	
	this.trackrefs.push({ id: track.id
	                    , itemid: itemid
						});

	return itemid;
}

spcGMap.prototype.disableTrack = function disableTrack(trackid)
{
	console.log('disableTrack called to disable track #'+trackid);

	var item = this.getItemByTrackId(trackid);
	if (item)
		item.instance.hide();
	else
		console.error('Trying to disable an unknown track');
}

spcGMap.prototype.trackIsVisible = function spcGMap_trackIsVisible(trackid)
{
	var track = this.getItemByTrackId(trackid);
	if (track)
		return this.visible;
	else
		return false;
}

// TODO: check if works
spcGMap.prototype.trackIDToItemID = function(trackid)
{
	var item = this.getItemByTrackId(trackid);
	if (!item)
	{
		console.error('trackIDToItemID got unknown track id #'+trackid);
		return false;
	}
	else
		return item.itemid;
}

spcGMap.prototype.getItemByTrackId = function spcGMap_getTrackById(trackid)
{
	for(var tel=0; tel<this.trackrefs.length; tel++)
	{
		if(this.trackrefs[tel].id == trackid)
			return mapmeta.getItemById(this.trackrefs[tel].itemid);
	}
	
	return false;
}

spcGMap.prototype.centerOnTrack = function spcGMap_centerOnTrack(trackid)
{
	var track = this.getItemByTrackId(trackid);

	if (!track)
	{
		console.error('unknown track');
		return;
	}
	
	var routebounds = track.overlay.getBounds();
	var zoom  = gmap.getBoundsZoomLevel(routebounds);
	this.gmap.setCenter(routebounds.getCenter(), zoom);
	
	//setZoom
	//panTo
}
