var map;

var zoom=-1;
var linewidth=-1;
var lineweight=-1;

var lastDate=-1;
var dateDifference=-1;

function isDefined(variable) {
	return (typeof(eval(object)[variable]) != 'undefined');
}

/** =======================================================================
 * Import tour XML
 * ===================================================================== */ 
var request = GXmlHttp.create();
request.onreadystatechange = drawTourCallback;
	request.open("GET", "/tourxml.php?tourId="+tourId, true);
//	request.open("GET", "/tourxml.php", true);

function drawTourCallback() {
	if (request.readyState == 4) {
		drawTour(request.responseXML);
	}
}

/** =======================================================================
 * Create small icons
 * ===================================================================== */ 
var tinyIconRed = new GIcon();
tinyIconRed.image = "/images/google/mm_20_red.png";
tinyIconRed.shadow = "/images/google/mm_20_shadow.png";
tinyIconRed.iconSize = new GSize(12, 20);
tinyIconRed.shadowSize = new GSize(22, 20);
tinyIconRed.iconAnchor = new GPoint(6, 20);
tinyIconRed.infoWindowAnchor = new GPoint(5, 1);

var tinyIconBlue = new GIcon();
tinyIconBlue.image = "/images/google/mm_20_blue.png";
tinyIconBlue.shadow = "/images/google/mm_20_shadow.png";
tinyIconBlue.iconSize = new GSize(12, 20);
tinyIconBlue.shadowSize = new GSize(22, 20);
tinyIconBlue.iconAnchor = new GPoint(6, 20);
tinyIconBlue.infoWindowAnchor = new GPoint(5, 1);

var tinyIconGreen = new GIcon();
tinyIconGreen.image = "/images/google/mm_20_green.png";
tinyIconGreen.shadow = "/images/google/mm_20_shadow.png";
tinyIconGreen.iconSize = new GSize(12, 20);
tinyIconGreen.shadowSize = new GSize(22, 20);
tinyIconGreen.iconAnchor = new GPoint(6, 20);
tinyIconGreen.infoWindowAnchor = new GPoint(5, 1);


/** =======================================================================
 * Tour URL
 * ===================================================================== */ 
var artist="";
var tourName="";

var prevPosition = undefined;
var prevCity = undefined;
var totalDistance = 0;
var mile = 1.609344;

/** =======================================================================
 * Parse XML and draw markers and lines
 * ===================================================================== */ 
var drawTour = function(response) {

	var tourinfo  = response.getElementsByTagName("tourinfo")[0];
	artist        = tourinfo.getElementsByTagName("artist")[0].firstChild.nodeValue;
	tourName      = tourinfo.getElementsByTagName("name")[0].firstChild.nodeValue;
	var mapLong   = tourinfo.getElementsByTagName("longitude")[0].firstChild.nodeValue;
	var mapLatt   = tourinfo.getElementsByTagName("latitude")[0].firstChild.nodeValue;
	var mapZoom   = tourinfo.getElementsByTagName("zoom")[0].firstChild.nodeValue;

	var mapZoomInt = zoom == -1 ? parseInt(mapZoom) : zoom;

	map.setCenter(new GLatLng(parseFloat(mapLatt), parseFloat(mapLong)), mapZoomInt);

	var tourItinerary = [];
	var concerts = response.getElementsByTagName("concert");

	for (var i = 0; i < concerts.length; i++) {
		var concert = concerts.item(i);
		var cancelled = concert.getAttribute("cancelled");
		if(cancelled != "true") {
			var lat = concert.getAttribute("lat");
			var lng	= concert.getAttribute("lng");
			var latlng = new GLatLng(parseFloat(lat), parseFloat(lng));

			tourItinerary.push(latlng);

			var distance=0;
			if(prevPosition != undefined) {
				distance = latlng.distanceFrom(prevPosition);
				totalDistance += distance;
				prevPosition = latlng;
			} else {
				prevPosition = latlng;
			}
			
			var marker = createMarker(latlng, concert, distance);
			map.addOverlay(marker);
		}

		if(dateDifference>10) {

			var lastShow = tourItinerary.pop();

			drawItinerary(tourItinerary);

			tourPauseItinerary = [];
			tourPauseItinerary.push(tourItinerary[tourItinerary.length-1]);
			tourPauseItinerary.push(lastShow);
			
			linewidth=1;
			lineweight=0.40;
			drawItinerary(tourPauseItinerary, linewidth, lineweight);

			newTourItinerary = [];
			newTourItinerary.push(lastShow);
			tourItinerary = newTourItinerary;

		} else if(i==concerts.length-1) {

			drawItinerary(tourItinerary);

		}
	}

}

function drawItinerary(tourItinerary, linewidth, lineweight) {
	if(linewidth==undefined) {
		linewidth = 2;
	}
	if(lineweight==undefined) {
		lineweight = 0.85;
	}

	var polyline = new GPolyline(tourItinerary, "#7f7fff", linewidth, lineweight, {geodesic:true});
	map.addOverlay(polyline);
}

/** =======================================================================
 * Create marker
 * ===================================================================== */ 
function createMarker(point, concertData, distance) {
	
	var city  = concertData.getElementsByTagName("city")[0].firstChild.nodeValue;
	var state = concertData.getElementsByTagName("state")[0].firstChild.nodeValue;
	var venue = concertData.getElementsByTagName("venue")[0].firstChild.nodeValue;
	var capacity = concertData.getElementsByTagName("capacity")[0].firstChild.nodeValue;
	var url   = concertData.getElementsByTagName("url")[0].firstChild.nodeValue;
	var dates  = concertData.getElementsByTagName("date");
	
	var title = city;
	var html = "";
	html += "<span style=\"font-size:x-small;font-style:italic;\">"+tourName+"</span><br/>";
	html += "<b>"+artist+"</b><br/>"
	html += city+", "+state+"<br/>";
	html += "<a target=\"_blank\" href=\"" + url + "\">"+venue+"</a><br/>";
	html += "<span style=\"font-size:x-small;font-style:italic;\">capacity: "+capacity+"</span><br/>"

	var now = new Date();
	var nowYear = now.getFullYear();
	var nowMonth = now.getMonth()+1;
	var nowDay = now.getDate();
	now = new Date(nowYear,nowMonth,nowDay);

	var icon = tinyIconRed;
	var iconSet = false;

	if(dates.length>0) {
		html += "<span style=\"font-size:small;\">";
		title += " (";
		for(var i=0; i<dates.length; i++) {
			var date = dates[i].firstChild.nodeValue;
			var shortDateYear = date.substring(0,4);
			var shortDateMonth = date.substring(5,7);
			var shortDateDay = date.substring(8,10);
			var shortDateStr = shortDateMonth+'/'+shortDateDay;

			var shortDate = new Date(shortDateYear,shortDateMonth,shortDateDay);
			if(lastDate!=-1) {
				dateDifference = (shortDate.getTime()-lastDate.getTime())/(1000*60*60*24);
			}
			lastDate = shortDate;

			var setlistLink = "";
			if(!iconSet) {
				if(shortDate.getTime() == now.getTime()) {
					document.title+=".";
					icon = tinyIconGreen;
					iconSet = true;
				} else if(shortDate < now) {
					icon = tinyIconBlue;
					setlistLink = " <span style=\"font-size:x-small;\">(<a target=\"_blank\" href=\"http://sugarmtn.org/sets/"+shortDateYear+shortDateMonth+shortDateDay+".html\">setlist</a>)</span>";
				}
			}

			html += "<b>"+date+"</b>"+setlistLink;
			title += shortDateStr;
			if(i != dates.length-1) {
				html += ", ";
				if((i+1)%2==0) {
					html += "<br/>";
				}
				title += ", ";
			}
		}
		html += "</span><br/>";
		title += ")";
	}
	
	if(distance > 0) {
		var distanceKm = Math.round(distance/1000);
		var totalDistanceKm = Math.round(totalDistance/1000);
		var distanceMile = Math.round(distanceKm / mile);
		var totalDistanceMile = Math.round(totalDistanceKm / mile);
		
					
		html += "<span style=\"font-size:x-small;font-style:italic;\">";
		html += "distance since "+prevCity+": "+distanceKm+"km / "+distanceMile+" miles<br/>";
		html += "total distance: "+totalDistanceKm+"km / "+totalDistanceMile+" miles";
		html += "</span><br/>";
	}
	prevCity = city;

	var marker = new GMarker(point, {icon:icon, title:title});
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});

	return marker;
}

/** =======================================================================
 * Initialize map
 * ===================================================================== */ 
function initialize(nocontrol, overrideZoom, solidlines) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_canvas"));
		
		//map.setCenter(new GLatLng(42, -98), 4);
		
		//map.addControl(new GSmallMapControl());

		if(nocontrol!=undefined && nocontrol=="true") {
			// no controls
		} else {
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			
			map.enableScrollWheelZoom();
			map.enableContinuousZoom();
		}

		if(overrideZoom != undefined) {
			zoom=overrideZoom;
		}

		if(solidlines != undefined && solidlines=="true") {
			linewidth=3;
			lineweight=1;
		}

		request.send(null);
	}
}

