
var rmap;
var ovmap;
var icons = [];
var allLegs = [];
var activeLeg;
var leglist_html;
var rallyname_html ="";
var default_image_height = 150;
var default_image_width = 200;

var sectlist_heading = '<p><strong>Sections</strong><br/>Jump to:</p>';
var leglist_heading = '<p><strong>Major Legs</strong><br/>Show on Map:</p>';

// add custom method to build html and open infoWindow
GMarker.prototype.openMyInfo = function() {
   	var html = "";
	var ih = "150";
	var iw = "200";
	
	html += '<div>';
	html += '<p><b>' + this.name + '</b></p>';
	html += '<p>' + this.description + '<br/>';
	if (this.photo) {
			
		html += '<a href="' + this.photo + '.jpg" target="_blank"><img src="' 
			+ this.photo + 't.jpg" width="' + this.pwide + '" height="' + this.phigh + '"/></a></p>';
	} else {
		html +=  '</p>';
	}
	html += '<div style="font-size: smaller; clear: both; float: bottom;">Marker: <a href="javascript:prevMarker(' 
			+ this.mnum + ')">Previous</a> || <a href="javascript:nextMarker(' + this.mnum + ')">Next</a></div>';

	if (this.mtype != "SS") {
		html += '<div style="font-size: smaller; clear: both; float: bottom;">This Section: <a href="javascript:thisSection(' + this.snum + ')">Start</a> || <a href="javascript:nextSection(' + this.snum + ')">End</a></div>';
	} else {
		if (isFirstSection(this.snum)) {
			html += '<div style="font-size: smaller; clear: both; float: bottom;">Section: <a href="javascript:thisSection(' + this.snum + ')">Start</a> || ';
		} else {
			html += '<div style="font-size: smaller; clear: both; float: bottom;">Section: <a href="javascript:prevSection(' + this.snum + ')">Previous</a> || ';
		}
		if (isLastSection(this.snum)) {
			html += ' <a href="javascript:lastMarker()">End</a></div>';
		} else {
			html += ' <a href="javascript:nextSection(' + this.snum + ')">Next</a></div>';
		}
	}
	
	html += '</div>';

	this.openInfoWindowHtml(html, {maxWidth:150});
}

function launchRallyMap(sourcefile) {
    if (GBrowserIsCompatible()) {
		setupIcons();
		initMap();
		GDownloadUrl("/rallymap/" + sourcefile,  loadRallyData);
	}
	else {
		document.getElementById("mainmap").innerHTML = "<p><b>Sorry, your browser is not compatible with RallyMap.</b></p><p>Please contact webmaster@rainierautosports.com if you need further assistance.</p>";
        // put something here			
	}
}

function initMap () {
	rmap = new GMap2(document.getElementById("mainmap")); //
	rmap.setCenter(new GLatLng(49.3004667, -120.9136833), 6, G_HYBRID_TYPE);
	resizeMap();
	rmap.addControl(new GLargeMapControl());
	rmap.addControl(new GMapTypeControl());
	rmap.addControl(new GScaleControl());
	rmap.addControl(new GOverviewMapControl());

	GEvent.addListener(rmap, "click", 
					   function(overlay, point) {
						   if (overlay) {
							   if (overlay.ismarker) {
								overlay.openMyInfo();
							   }
						   }
						   //if (point) {
							//   alert("clicked at: " + point.y + "  " + point.x);
						  //}
					   }
					   );

}

function refreshMap() {

	rmap.clearOverlays();
	
	rmap.panTo(allLegs[activeLeg].center);
	rmap.setZoom(allLegs[activeLeg].zoom);

	for (var m = 0; m < allLegs[activeLeg].markers.length; m++) {
		rmap.addOverlay(allLegs[activeLeg].markers[m]);
	}
	for (var p = 0; p < allLegs[activeLeg].plines.length; p++) {
		rmap.addOverlay(allLegs[activeLeg].plines[p]);
	}
	
	leglist_html = leglist_heading;
	for (var l = 0; l < allLegs.length; l++) {
		if (l == activeLeg) {
			leglist_html += allLegs[l].name + '<br/>';
			document.getElementById("legname").innerHTML = allLegs[l].name;
		} else {
			leglist_html += '<a href="javascript:showLeg(' + l + ')">' + allLegs[l].name + '</a><br/>';
		}
	}
 
	document.getElementById("leglist").innerHTML = leglist_html;
	document.getElementById("sectionlist").innerHTML = allLegs[activeLeg].sectlist;
	
	openMarker(0);
}

function loadRallyData (xmlData, respCode) {
	var xmlDoc = GXml.parse(xmlData);	
	var rally = xmlDoc.documentElement;
	
	rallyname_html += rally.getAttribute("name");
	document.getElementById("rallyname").innerHTML = rallyname_html;
	
	var legs = rally.getElementsByTagName("leg");
	for (var l = 0; l < legs.length; l++) {
		var leg = legs.item(l);
		
		allLegs[l] = new Object;
		allLegs[l].name = leg.getAttribute("name");
		allLegs[l].center = new GLatLng(parseFloat(leg.getAttribute("baselng")),
							  			parseFloat(leg.getAttribute("baselat")));
		allLegs[l].zoom = parseFloat(leg.getAttribute("basezoom"));
		allLegs[l].markers = [];
		allLegs[l].sIndex = [];
		allLegs[l].plines = [];
		allLegs[l].sectlist = sectlist_heading;
		
		leglist_html += '<a href="javascript:showLeg(' + l + ')">' + leg.getAttribute("name") + '</a><br/>';

		var sCount = 0; // section count is unique to leg
		var mCount = 0; // marker count is unique to leg

		var sections = leg.getElementsByTagName("section");
		for (var s = 0; s < sections.length; s++) {
			var section = sections.item(s);	

			// Add markers for the section
			var markers = section.getElementsByTagName("marker");
			for (var m = 0; m < markers.length; m++) {
				var xmark = markers.item(m);
				
				if (xmark.getAttribute("show") == "no") continue;
	
				var smark = new createMarker( new GPoint(parseFloat(xmark.getAttribute("lng")),
														 parseFloat(xmark.getAttribute("lat"))),
											  xmark.getAttribute("type"));

				smark.name = xmark.getAttribute("name");
				// smark.title = xmark.getAttribute("name"); supposed to do tooltip
				smark.description = xmark.getAttribute("description");
				smark.snum = sCount;
				smark.mnum = mCount;

				if (xmark.getAttribute("photo")) {
					smark.photo = xmark.getAttribute("photo");

					smark.phigh = default_image_height;
					smark.pwide = default_image_width;
					
					if (xmark.getAttribute("pvert")) {
						smark.phigh = default_image_width;
						smark.pwide = default_image_height;
					}
					if (xmark.getAttribute("phigh")) 
						smark.phigh = xmark.getAttribute("phigh");
					if (xmark.getAttribute("pwide")) 
						smark.pwide = xmark.getAttribute("pwide");
				}
			
				allLegs[l].markers[mCount] = smark;
				
				if (smark.mtype == "SS") {
					allLegs[l].sIndex[sCount] = mCount;
					allLegs[l].sectlist += '<a href="javascript:openMarker(' + mCount + ')">' + smark.name + '</a><br/>';
				}
	
				mCount++;
			}
					
			// Add route line for the section
			var pline = [];
			var lcolor = (section.getAttribute("color") ? section.getAttribute("color") : "#000000");;
			if (section.getAttribute("type") == "TRN") {
				lcolor = "#00FF00";
			}
			if (section.getAttribute("type") == "TSD") {
				lcolor = "#FF3300";
			}

			var rpoints = section.getElementsByTagName("rpoint");
			for (var p = 0; p < rpoints.length; p++) {
				pline.push(new GPoint(parseFloat(rpoints[p].getAttribute("lng")),
                          		 	 parseFloat(rpoints[p].getAttribute("lat"))));
			}
			if (pline.length > 0) {
				allLegs[l].plines.push(new GPolyline(pline, lcolor, 10));
		    	// rmap.addOverlay(new GPolyline(pline, lcolor, 10));
			}
			sCount++;
		}
		allLegs[l].numsections = sCount;
	}
	
	// Open the first marker of first leg initially
	//openMarker(0);
	showLeg(0);
}

function showLeg(l) {
	 if (l >= 0 && l < allLegs.length) {
		if (l == activeLeg) {
			return;
		}
     	activeLeg = l;
		refreshMap();
	 }
}

function openMarker(i) {
     allLegs[activeLeg].markers[i].openMyInfo();
}

function nextMarker(i) {
	 if (i == (allLegs[activeLeg].markers.length - 1)) { return; }
     allLegs[activeLeg].markers[i+1].openMyInfo();
}

function prevMarker(i) {
    if (i == 0) { return; }
	allLegs[activeLeg].markers[i-1].openMyInfo();;
}

function lastMarker() {
	allLegs[activeLeg].markers[allLegs[activeLeg].markers.length-1].openMyInfo();;
}

function nextSection(i) {
	 if (i >= (allLegs[activeLeg].numsections - 1)) { return; }
     allLegs[activeLeg].markers[allLegs[activeLeg].sIndex[i+1]].openMyInfo();
}

function thisSection(i) {
	 if (i >= (allLegs[activeLeg].numsections - 1)) { return; }
     allLegs[activeLeg].markers[allLegs[activeLeg].sIndex[i]].openMyInfo();
}

function prevSection(i) {
	 if (i <= 0 ) { return; }
     allLegs[activeLeg].markers[allLegs[activeLeg].sIndex[i-1]].openMyInfo();
}

function isLastSection(i) {
	if (i == allLegs[activeLeg].numsections - 1) {
		return true;
	}
}
function isFirstSection(i) {
	if (i == 0) {
		return true;
	}
}
function createMarker(point, type) {
	var marker;
	
	if (type == "CP") {
		marker = new GMarker(point, icons["CP"]);		
	}
	else if (type == "SS") {
		marker = new GMarker(point, icons["SS"]);		
	}
	else if (type == "PH") {
		marker = new GMarker(point, icons["PH"]);	
	}
	else {
		marker = new GMarker(point);	
	}

	marker.ismarker = true;
	marker.mtype = type;
	return marker;
}

function setupIcons() {
			// intialize the checkpoint icon
		icons["CP"] = new GIcon();
		icons["CP"].image = "http://www.rainierautosports.com/rallymap/images/cp_20_green.png";
		icons["CP"].shadow = "http://www.rainierautosports.com/rallymap/images/mm_20_shadow.png";
		icons["CP"].iconSize = new GSize(12, 20);
		icons["CP"].shadowSize = new GSize(22, 20);
		icons["CP"].iconAnchor = new GPoint(6, 20);
		icons["CP"].infoWindowAnchor = new GPoint(5, 1);
		icons["CP"].imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0]; 
		icons["CP"].transparent = "http://www.rainierautosports.com/rallymap/images/mm_20_transparent.png";

		// intialize the photo icon
		icons["PH"] = new GIcon();
		icons["PH"].image = "http://www.rainierautosports.com/rallymap/images/ph_20_blue.png";
		icons["PH"].shadow = "http://www.rainierautosports.com/rallymap/images/mm_20_shadow.png";
		icons["PH"].iconSize = new GSize(12, 20);
		icons["PH"].shadowSize = new GSize(22, 20);
		icons["PH"].iconAnchor = new GPoint(6, 20);
		icons["PH"].infoWindowAnchor = new GPoint(5, 1);
		icons["PH"].imageMap = [4,0,0,4,0,7,3,11,4,19,7,19,8,11,11,7,11,4,7,0]; 
		icons["PH"].transparent = "http://www.rainierautosports.com/rallymap/images/mm_20_transparent.png";

		icons["SS"] = new GIcon();
		icons["SS"].image = "http://www.rainierautosports.com/rallymap/images/dd-start.png";
		icons["SS"].shadow = "http://www.rainierautosports.com/rallymap/images/shadow50.png";
		icons["SS"].iconSize = new GSize(20, 34);
		icons["SS"].shadowSize = new GSize(37, 34);
		icons["SS"].iconAnchor = new GPoint(9, 34);
		icons["SS"].infoWindowAnchor = new GPoint(9, 2);
		icons["SS"].infoShadowAnchor = new GPoint(18,25); 
		//icons["SS"].printImage="http://www.google.com/mapfiles/markerie.gif"; 
		//icons["SS"].mozPrintImage="http://www.google.com/mapfiles/markerff.gif"; 
		//icons["SS"].printShadow="http://www.google.com/mapfiles/dithshadow.gif"; 
		icons["SS"].imageMap=[9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0]; 
		icons["SS"].transparent="http://www.google.com/mapfiles/markerTransparent.png";
}


function e(id) {return document.getElementById(id);}

function getWindowHeight() {
    if (window.self && self.innerHeight) {
		return self.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}

function resizeMap() {
	var offset = 10;
    
	for (var elem = e("mainmap"); elem != null; elem = elem.offsetParent) {
        offset += elem.offsetTop;
	}
    var windowHeight = getWindowHeight();
    var height = windowHeight - offset - 1;
    if (height >= 0) {
        e("mainmap").style.height = height + "px";
        e("mapsidelist").style.height = height + "px";
    }
	if (rmap) {
		rmap.checkResize();
	}
	
}
