
//------------------------------------------------------------------------Ingredient code---------------------------------------------------------------------------//


var colors = [
	"66CC33",	//green
	"FF9933",	//orange
	"CC99FF",	//light purple
	"6699CC",	//blue
	"FFFF66",	//yellow, hard to see
	"FF3333",	//red
	"99CCFF",	//light blue, hard to see
	"CCCC33",	//lime green
	"FFFFCC",	//light yellow, impossible to see on white
	"CCFFCC",	//light green, hard to see
	"FFCC99",	//light orange, hard to see
	"FFCCCC",	//light red
	"FFFFFF",	//white  impossible to see
	"CCCCCC",	//light gray, hard to see
	"99FFCC",	//turquose, hard to see
	"FFCCFF",	//light violet
	"CC9966",	//tan-orange
	"CC9900",	//burnt orange  IS THIS HERE??????
];

var ingDistance = [];

var miles;
var world_times;
var football_times;
var metersPerMile = "1609.344";

var polyColorNum = [];
var taken = [];

for (var i=0; i<colors.length; i++){
	taken[i] = "NO";

}


	var baseIcon = new GIcon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(21, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);

//this selects a color from the 'colors' array
//and returns the index number back to the calling variable
function addColor(number){
	if(number){
		//alert(number);
		taken[(number-1)] = "NO"
	} else {
		for(i=0; i<colors.length; i++){
			if (taken[i]=="NO"){
				taken[i] = "YES";
				return i;
				break;
			}
		}
	}
}

//this adds the related polygon  color to the Ingredient text
function addTextColor(x, color){
    text = document.getElementById("ing" + x);
    //colorstyle = "color:#" + color;
    text.style.color = color;
    text.style.fontWeight = 'bold';
    if(color=="#FFFFCC" || color=="#CCFFCC" || color=="#99CCFF" || color=="#FFCC99" || color=="#FFFF66" || color=="#99FFCC" || color=="#FFCCCC" || color=="#FFFFFF" || color =="#CCCCCC" || color=="#FFCCFF"){
	text.style.backgroundColor = "#999999";
    }
}

//this removes the related polygon color from the Ingredient text
function removeTextColor(x){
	text = document.getElementById("ing" + x);
	text.style.color = "#660000";
	text.style.fontWeight = 'normal';
	text.style.backgroundColor = "#FFFFFF";
}


//This function adds or removes ingredient information to the map
//if the checkbox is checked, then it accesses getSteps.php which
//then writes and returns an xml file for that ingredient
//The allOverlays array collect all the added map overlays, which
//allows them to be removed by unchecking the box
function getIngSteps(x, checkbox){
	
	//remove the polygon and change the text color back to normal
	if(checkbox.checked==false) {
		number = polyColorNum[x] + 1;
		if(number){
			addColor((number));
			removeTextColor(x);
		}
		if(ingDistance[x]){
			miles -= ingDistance[x];
			div = document.getElementById("miles");
			div.innerHTML = miles;
			worldDistance(miles);
		}
		for(i=0; i<allOverlays[x].length; i++){
			map.removeOverlay(allOverlays[x][i]);
		}
	} else {
		var vertices = [];
		var polygon = [];
		var getVars = "?id=" + x;
		var markerPoints = [];
		allOverlays[x] = [];

		//alert(taken);
		polyColorNum[x] = addColor();
		//alert (polyColorNum[x]);
		var polyColor = "#" + colors[polyColorNum[x]];
		//alert(polyColor);
		var markerColor = colors[polyColorNum[x]];
		addTextColor(x, polyColor);

		var create = GXmlHttp.create();
		create.open("GET", "getSteps.php" + getVars, true);
		create.onreadystatechange = function(){
			if (create.readyState == 4){
				var xmlDoc = create.responseXML;
				// obtain the array of markers and loop through it
				var steps = xmlDoc.documentElement.getElementsByTagName("step");

				for (var i = 0; i < steps.length; i++){
					// obtain the attribues of each marker
					var title = steps[i].getAttribute("title");
					//alert(title);
					var info = steps[i].getAttribute("info");
					//alert(steps[i]);
					var html = "<div class='mapDiv'><h3>" + title + "</h3><p>" + info + "</p></div>";
					var lat = parseFloat(steps[i].getAttribute("lat"));
					var lng = parseFloat(steps[i].getAttribute("lng"));
					markerPoints[i] = new GLatLng(lat, lng);
					var numberedIcon = new GIcon(baseIcon);
					var markerName = markerColor + "__" + (i+1);
					//alert(markerName);
					numberedIcon.image = "http://www.thefoodmap.org/images/markers4/" + markerName + ".png";
					// Set up our GMarkerOptions object
					markerOptions = { icon:numberedIcon };
					var stepMarker = new GMarker(markerPoints[i], markerOptions);
					allOverlays[x].push(stepMarker);

					createIngMarker(stepMarker, html, i);
					vertices[i] = [];
					//var name = "point" + (i +1);
					//alert(name);
					//var polys = xmlDoc.documentElement.getElementsByTagName("name")
					//alert(polys.length);
					for (var a = 0; a < steps[i].childNodes.length; a++) {
						// get any line attributes
						//get the number of points, so we can add the first point (vertices[i][0]) to the end of vertices[i] to make a complete polygon
						last = steps[i].childNodes.length
						point = steps[i].childNodes[a]
						if (point.nodeType != 1) continue;
						//alert(point);
						var lat = parseFloat(point.getAttribute("lat"));
						var lng = parseFloat(point.getAttribute("lng"));
						var latlng = new GLatLng(lat, lng);
						vertices[i].push(latlng);
						//alert(vertices[i]);
						//alert(a);
						if(a == (last - 2)){
							//first = vertices[i];
							//var polyColor = colors[i];
							vertices[i].push(vertices[i][0]);
							polygon[i] = new GPolygon(vertices[i],polyColor, 3, 1,polyColor,0.2);
							allOverlays[x].push(polygon[i]);
							map.addOverlay(polygon[i]);
						}
					}



				}//for

				linkMarkers(markerPoints, x, polyColor);

			}//readystate
		}//onreadystatechange

		create.send(null);
	}//else
}

//this function adds polylines between the markers
//for the checked ingredient.  It takes three arguements.
//X marks the overlay/ingredient ID, color specifies the
//associated ingredient color (on the right panel, ingredient
//info), and points are the ????.  Addittionally, it adds the
//polyline lengths to the total number of miles travelled
//then adapts the world and football field values.
function linkMarkers(points, x, color){
	number = locations.length;
	//alert(number);
	points.push(locations[number-1]);
	//alert(points);
	polyOptions = {geodesic:true};
	polyline = new GPolyline(points, color, 5, .8, polyOptions);
	allOverlays[x].push(polyline);
	map.addOverlay(polyline);
	ingDistance[x] = Math.round(polyline.getLength()/metersPerMile);
	//alert(ingDistance[x]);
	if(ingDistance[x]>0){
		miles += ingDistance[x];
		div = document.getElementById("miles");
		div.innerHTML = miles;
		worldDistance(miles);
	}
}

/*  Might use this to round the football_times so it doesn't
   get soooo tedious.... */
function worldDistance(miles){
	var world = document.getElementById("world");
	var football = document.getElementById("football");
	world_times = Math.round((miles/24901.55)*100)/100; //Math.round(original*100)/100
	football_times = Math.round((miles/0.170454545)*100)/100;
	if(football_times>=1000){
		football_times = football_times/1000;
		football_times = Math.round(football_times*10)/10 + " thousand";
	} else if(football_times>=1000000){
		football_times = football_times/1000000 + " million";
	}
	world.innerHTML = world_times;
	football.innerHTML = football_times;
}


function createIngMarker(marker, html, i) {
//var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(html);
	});
	// save the info we need to use later for the side_bar
	map.addOverlay(marker);
	//return marker;
}

//------------------------------------------------------------------------------END Ingredient code-------------------------------------------------------------------------------//


//-----------------------------------------------Other code---------------------------------------------------//

	function addPathPolyline(loc1, loc2){
		polyOptions = {geodesic:true};
		polyline = new GPolyline([loc1, loc2], "#0099CC", 5, .8, polyOptions);
                distance = Math.round(polyline.getLength()/metersPerMile);                
		map.addOverlay(polyline);
		//alert(distance);	
		return distance;
	}
	
	
	function createMarker(point, i, html) {
	        var marker = new GMarker(point);


	        GEvent.addListener(marker, "click", function() {
	          marker.openInfoWindowHtml(html);
	        });
		
	        // save the info we need to use later for the side_bar
	        gmarkers[i] = marker;
                //alert(i + gmarkers[i]);
	        //htmls[i] = html;
		
	        // add a line to the side_bar html
	        //side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
	        //i++;
                map.addOverlay(marker);
	        //return marker;

	}
	  
	// This function picks up the click and opens the corresponding info window
	function myclick(i) {
		gmarkers[i].openInfoWindowHtml(htmls[i]);
	}
	
	
	
	 function addDirections( insideLocations, locations, locationsName ) {
		//alert(locations);
                //alert(locations[0]);
	        var path = document.getElementById('path_list');
			for(i=0; i<locationsName.length; i++){
					path.innerHTML += "<li><a href='javascript:myclick(" + i + ")'>" + locationsName[i] + "</a></li>";
			}	
			
			for(i=0; i<locations.length; i++){
				createMarker(locations[i], i, htmls[i]);
			}                            
                //alert(locationsName);
                var directions = new GDirections;
		//alert(directions);
            directions.loadFromWaypoints( insideLocations,
				{ getPolyline:true, getSteps:true } );
				
			GEvent.addListener(directions, "load", function() {
					pathDistance = directions.getDistance().meters / metersPerMile;
					//var response = directions.getStatus();
                                        if(miles>0) miles += Math.round(pathDistance);
					else miles =+ Math.round(pathDistance);
                                        var div = document.getElementById("miles");
					div.innerHTML = miles;
                                        worldDistance(miles);
        
					var bounds = directions.getBounds();
					if(locations.length>insideLocations.length){
                                                bounds.extend(outProductions[number2]);
                                                
                                        }
                                        map.setCenter( bounds.getCenter(),
					map.getBoundsZoomLevel(bounds) );
		
					
					var poly = directions.getPolyline();
					poly.color = "#0099CC";
					poly.opacity = 0.8;
					map.addOverlay( poly );
			});
	
			GEvent.addListener(directions, "error", function(){
					var status = directions.getStatus();
					alert("We're sorry, Google could not locate that address.  Please make sure it is correct and try again.");
			});
        		
        }
	/*	OLD CODE
	function bigMap(){
		div = document.getElementById("map");
		div.style.width = "800px";
		div.style.height = "600px";
	}
	
		function smallMap(){
		div = document.getElementById("map");
		div.style.width = "400px";
		div.style.height = "300px";
	}
	*/
	
	function disclaimer(){
	window.open('disclaimer.html','The_Food_Map_Disclaimer','height=400,width=500,toolbars=no,location=no,directories=no,status=no,menubar=no,copyhistory=no,resizable=yes,scrollbars=yes');
}

var n=0;
function bigMap(){
		button = document.getElementById("toggle");
		container = document.getElementById("outContainer");
		div = document.getElementById("map");
		if(n==0){
			container.style.width = "1040px"
			div.style.width = "800px";
			div.style.height = "600px";
			button.innerHTML = "Small Map";
			n=1;
		} else if(n==1){
			button.innerHTML = "Large Map";
			n=0;
			container.style.width = "800px"
			div.style.width = "560px";
			div.style.height = "420px";
		}

	}
//----------------------------------------End other code---------------------------------------------------------------//