
var townsArray = [];  //  array of town data
var todaysIndex = 0;   //  index to townsArray that represents "today"

var markersArray = new Array();

	// Create the InfoWindow object
	var infowindow = new google.maps.InfoWindow({
  		content: 'Hello world',
		//pixelOffset: new google.maps.Size(0, 10)
	});


function initTownData(townDataFile)  {
	//var filePath = "file.txt";
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", townDataFile, false);
	xmlhttp.send(null);
	var fileContent = xmlhttp.responseText;

	// split content into array of lines of text
	townsArray = removeCommentBlankLines(fileContent);

	//  split each line into array of items
	for(i=0; i<townsArray.length; i++) {
		parseOneLine(townsArray[i]);
	}

	todaysIndex  = getTodaysIndex();
//alert("todaysIndex="+ todaysIndex);
}

function removeCommentBlankLines(content) {
	//  create the array from lines of text
	var contentArray = content.split('\n');
	
	var aLine;
	for(i=contentArray.length-1; i >=0; i--) {
		aLine = contentArray[i];
		//  parse out blank lines
		if(aLine =="")
			contentArray.splice(i,1);

		//  parse out comments
		if (aLine.substring(0, 2) == "//")
			contentArray.splice(i,1);
	}
	return contentArray;
}

function parseOneLine(townData) {
	var townDataArray = townData.split('**');
//alert(townDataArray.length +"+++"+ townDataArray);
}


//    figure out which indexed line in the town data represents "today" or "now"
//  indexes that will be returned are:
//    a.   -100000   if today is before any scheduled events
//    b.   index 0 to townsArray.length    if today is during one of the arrival/departure spans
//                                                             as found in the data
//    c.   negative of index 1 to townsArray.length    if today is between a departure and the
//                                                             next arrival; index of the next arrival is used
//                                                             e.g.  index 0, arriv 3 Feb, depart 4 Feb
//                                                                     index 1, arriv 6 Feb, depart 6 Feb
//                                                                     today is  5 Feb,  the returned index = -1
//    d.   100000    if today is after all scheduled events;  i.e. you missed the events!
//
function getTodaysIndex()  {
	var today = new Date();
	var todayMilliseconds = today.getTime();  //  get time in milliseconds (since 1970)

	//  first check and see if "today" is before any dates in the file
	var firstArrivalDate = new Date( getArrivalDate(0) );
	var firstArrivalMilliseconds = firstArrivalDate.getTime();
	if(todayMilliseconds < firstArrivalMilliseconds) return -100000;

	//  loop thru arrival & departure dates to find out which data entry represents today
	for (i=0; i < townsArray.length; i++)  {
		var arrivalDate = new Date( getArrivalDate(i) );
		var arrivalMilliseconds = arrivalDate.getTime();
		var departureDate = new Date( getDepartureDate(i) );
		var departureMilliseconds = departureDate.getTime();

		//      is "today somewhere between the beginning of the arrival day
		//  and the end of the departure day?
		if( (todayMilliseconds >= arrivalMilliseconds) && (todayMilliseconds <= (departureMilliseconds + 86400 * 1000) ) )  {
			return i;
		}

		//    check to see if today is between a previous departure and the next arrival
		if( i < (townsArray.length-1) )  {
			var nextArrivalDate = new Date( getArrivalDate(i+1) );
			var nextArrivalMilliseconds = nextArrivalDate.getTime();
			if( (todayMilliseconds > (departureMilliseconds + 86400 * 1000) ) && (todayMilliseconds < nextArrivalMilliseconds ) )  {
				return 0 - (i+1);
			}
		}
	}
	//  if we get here and no index returned, assume today is after all events
	return 100000;
}


function getTownLat(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[4];
}
function getTownLong(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[3];
}
function getTownName(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[2];
}
function getArrivalDate(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[0];
}
function getDepartureDate(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[1];
}
function getComments1(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[6];
}
function getComments2(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[7];
}
function getPictureURL(townNumber)  {
	var townData = townsArray[townNumber].split('**');
	return townData[8];
}


//     this function returns the file name of the flag to be used at a marker
//  based on "todaysIndex". Return different flags based on whether the index
//  passed as the parameter is equal to today's index, less than or greater than
//  or the negative of today's index
//
function getIcon(index)  {
	if(index == todaysIndex) return "flagGreen.png";
	if( (todaysIndex < 0) && (index == (0-todaysIndex)) ) return "flagRed.png";
	if(todaysIndex ==  -100000) return "footprintRed.png";
	if(todaysIndex ==  100000) return "footprintGreen.png";

	var theIndex;
	if(todaysIndex < 0)
		theIndex =  0-todaysIndex;
	else
		theIndex = todaysIndex;
	if(index < theIndex) return "footprintGreen.png";
	if(index > theIndex) return "footprintRed.png";
	return "flagGreen.png";
}


//           this function controls the content of the infoWindows
//    this function creator wraps up the function that must be passed to the
//  event listener for each marker; when attempted to put this in line within
//  the createTownMarkers function, the indexes didn't work properly
//  and we will only see the last infoWindow that was created
//      so, don't try to unwrap this function!!
function createfunc(index, googleMap) {
    return function() {
			//infowindow.content = "This is "+ getTownName(index);
			infowindow.content = "<div style='overflow-y:auto;'><p style='font: 12pt Arial,serif; font-style: oblique; font-weight: bold; color:#409D50; text-align:center;'>" + getTownName(index)+ "</p><img src='" + getPictureURL(index) + "' border=0 width=196 height=130><p>"+ getComments1(index) +"</p></div>";
			infowindow.open(googleMap, markersArray[index]); };
}


function createTownMarkers(theMap)  {
	//  add listener, so infowindow is closed when other portion of map is clicked
	google.maps.event.addListener(theMap, 'click', function() {
		infowindow.close();
	});

	//  loop through the 'towns' creating a marker for each and
	for (i=0; i < townsArray.length; i++)  {
		var theIcon = getIcon(i);
		var marker = new google.maps.Marker({
			map: theMap,
			position: new google.maps.LatLng(getTownLat(i), getTownLong(i)),
			title: getTownName(i),
			icon: theIcon
		});

		// Register event listeners to each marker to open a shared info
		// window displaying the marker's position when clicked or dragged.
		//   use the function creator
		google.maps.event.addListener(marker, 'click', createfunc(i, theMap) );                        
                           
		markersArray[i] = marker;
	}

}

