var kml_version = 13; // Just to force Google to update its cache.
var zoomed_data = {};
var dash_markers = [];
var rail_markers = [];
var current_overlays = [];
var overlays_on = null;

var dash_polyline = null;
var dash_active_polyline = null;

var caltrain_active_polyline = null;

var rail_polyline = null;
var rail_active_polyline = null;

var poiMarkers = [];
var lastclick=null;
var poiIcon = new GIcon();
poiIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
poiIcon.iconSize = new GSize(20, 34);
poiIcon.shadowSize = new GSize(37, 34);
poiIcon.iconAnchor = new GPoint(9, 34);
poiIcon.infoWindowAnchor = new GPoint(9, 2);
poiIcon.infoShadowAnchor = new GPoint(18, 25);


function init_map () {
	map = new GMap(document.getElementById("google_map"));
	map.setCenter(new GLatLng(37.333358, -121.890109), data.zoom);
	map.addControl(new ZoomControl());
	
	zoomed_data[data.zoom] = data;
	
	init_garages(data);
	init_moto_lots(data);
	init_lines(data);
	
GEvent.addListener(map, "click", map_click);
//GEvent.addListener(map,"click", function(overlay, latlng,overlaylatlng) {     
//  if (latlng) { 
//    var myHtml = "The GPoint value is: " + map.fromLatLngToDivPixel(latlng) + " at zoom level " + map.getZoom();
//    map.openInfoWindow(latlng, myHtml);
//  } 
//  if (overlaylatlng) { 
//    var myHtml = "The overlay latlng GPoint value is: " + map.fromLatLngToDivPixel(overlaylatlng) + " at zoom level " + map.getZoom();
//    map.openInfoWindow(overlaylatlng, myHtml);
//  }
//});
	GEvent.addListener(map, "zoomend", map_zoomend);
	
	reset_overlays();
}

function unload_map () {
	try {
		GUnload();
	} catch ( e ) {
		// 2007-04-16: IE 6 throws an exception.
	}
}

function init_garages ( data ) {
	var i, j, garage, arrow, color;
	
	for ( i = 0 ; i < data.garages.length ; i++ ) {
		garage = data.garages[i];
		
		for ( j = 0 ; j < garage.points.length ; j++ ) {
			garage.points[j] = array_to_point(garage.points[j]);
		}
	}
}

function init_moto_lots ( data ) {
	var i, lot, v_x, v_y;
	
	for ( i = 0 ; i < data.moto_lots.length ; i++ ) {
		lot = data.moto_lots[i];
		
		if ( ! lot.point_a || ! lot.point_b ) {
			// Skip motorcycle lots with no location.
			continue;
		}
		
		lot.point_a = array_to_point(lot.point_a);
		lot.point_b = array_to_point(lot.point_b);
		
		v_x = lot.point_a.lng() - lot.point_b.lng();
		v_y = lot.point_a.lat() - lot.point_b.lat();
		
		lot.click_polygon_points = [
			find_point(lot.point_a, -v_y, v_x, 0.0001),
			find_point(lot.point_a, -v_y, v_x, -0.0001),
			find_point(lot.point_b, -v_y, v_x, -0.0001),
			find_point(lot.point_b, -v_y, v_x, 0.0001)
		];
		
		lot.polyline = new GPolyline(
			[ lot.point_a, lot.point_b ], "#FF3333", 3, 1);
	}
}

function init_lines ( data ) {
	var i, j, line, points, markers, icon,
		dash_points = [], caltrain_points = [], rail_points = [];
	
	for ( i = 0 ; i < data.lines.length ; i++ ) {
		line = data.lines[i];
		
		if ( line.id == 1 ) {
			// Light rail
			points = rail_points;
			markers = rail_markers = [];
			icon = new GIcon(line_icon, "assets/templates/sjdp/parking_map/light_rail_icon.png");
		} else if ( line.id == 2 ) {
			// DASH
			points = dash_points;
			markers = dash_markers = [];
			icon = new GIcon(line_icon, "assets/templates/sjdp/parking_map/dash_icon.png");
		} else if ( line.id == 3 ) {
			// Caltrain
			points = caltrain_points;
			markers = [];
			// Icon doesn't exist.
			icon = null;
		} else {
			// Some other line we don't know about.
			continue;
		}
		
		for ( j = 0 ; j < line.points.length ; j++ ) {
			points.push(array_to_point(line.points[j]));
		}
		
		for ( j = 0 ; j < line.stops.length ; j++ ) {
			markers.push(create_line_stop(line.stops[j], icon));
		}
	}
	
	dash_polyline = new GPolyline(dash_points, "#FF3333", 4, .5);
	rail_polyline = new GPolyline(rail_points, "#000000", 4, .5);
	
	dash_active_polyline = new GPolyline(dash_points, "#FF3333", 4, 1);
	rail_active_polyline = new GPolyline(rail_points, "#000000", 4, 1);
	caltrain_active_polyline
		= new GPolyline(caltrain_points, "#000000", 4, .5);
}

function create_line_stop ( stop_info, icon ) {
	var marker = new GMarker(array_to_point(stop_info), { icon : icon });
	
	if ( stop_info[2] ) {
		GEvent.addListener(marker, "click",
			function() {
				marker.openInfoWindowHtml(
					'<div class="line_stop">'
						+ entity_escape(stop_info[2])
					+ '</div>');
			});
	}
	
	return marker;
}

function set_overlays ( new_overlays ) {
	var i, new_current = [];
	
	// Don't just set current_overlays to new_overlays, since modifications to
	// new_overlays would then change current_overlays.
	
	for ( i = 0 ; i < new_overlays.length ; i++ ) {
		if ( ! array_contains(current_overlays, new_overlays[i]) ) {
			map.addOverlay(new_overlays[i]);
		}
		
		new_current.push(new_overlays[i]);
	}
	
	for ( i = 0 ; i < current_overlays.length ; i++ ) {
		if ( ! array_contains(new_overlays, current_overlays[i]) ) {
			map.removeOverlay(current_overlays[i]);
		}
	}
	
	current_overlays = new_current;
}

function reset_overlays () {
	var i, j, overlays = [ dash_polyline, rail_polyline ];
	
	overlays = overlays.concat(dash_markers, rail_markers);
	
	if ( ! data.garage_kml ) {
		data.garage_kml = {};
	}
	
	if ( ! data.garage_kml[""] ) {
		data.garage_kml[""] = new GGeoXml(
			"http://www.sjdowntownparking.com.php5-13.websitetestlink.com/garages.kml.html&kml=1&zoom="
			+ data.zoom + "&v=" + kml_version);
	}
	
	overlays.push(data.garage_kml[""]);
	
	for ( i = 0 ; i < data.moto_lots.length ; i++ ) {
		if ( data.moto_lots[i].polyline ) {
			overlays.push(data.moto_lots[i].polyline);
		}
	}
	
	set_overlays(overlays);
}

function update_overlays () {
	var overlays = [], i, programs;
	
	if ( ! overlays_on ) {
		reset_overlays();
		return;
	}
	
	if ( overlays_on.rail ) {
		overlays = overlays.concat([ rail_active_polyline ], rail_markers);
	}
	
	if ( overlays_on.dash_line ) {
		overlays = overlays.concat([ dash_active_polyline ], dash_markers);
	}
	
	if ( overlays_on.caltrain ) {
		overlays = overlays.concat([ caltrain_active_polyline ]);
	}
	
	if ( overlays_on.moto ) {
		for ( i = 0 ; i < data.moto_lots.length ; i++ ) {
			if ( data.moto_lots[i].polyline ) {
				overlays.push(data.moto_lots[i].polyline);
			}
		}
	}
	
	programs = [];
	for ( i in overlays_on ) {
		if ( overlays_on[i] ) {
			programs.push(i);
		}
	}
	programs.sort();
	programs = programs.join(",");
	
	if ( ! data.garage_kml ) {
		data.garage_kml = {};
	}
	
	if ( ! data.garage_kml[programs] ) {
		data.garage_kml[programs] = new GGeoXml(
			"http://www.sjdowntownparking.com.php5-13.websitetestlink.com/garages.kml.html&kml=1&zoom="
			+ data.zoom + "&v=" + kml_version
			+ "&programs=" + escape(programs));
	}
	
	overlays.push(data.garage_kml[programs]);
	
	set_overlays(overlays);
}

function show_overlay_type ( type ) {
	if ( ! overlays_on ) {
		overlays_on = {};
	}
	
	overlays_on[type] = true;
	
	update_overlays();
}

function hide_overlay_type ( type ) {
	var i, found;
	
	if ( overlays_on ) {
		delete overlays_on[type];
		
		found = false;
		for ( i in overlays_on ) {
			found = true;
			break;
		}
		
		if ( ! found ) {
			overlays_on = null;
		}
	}
	
	update_overlays();
}

function toggle_overlay(sidebarNum, overlayType) {
	if ( ! overlays_on ) {
		overlays_on = {};
	}
	
	if ( overlays_on[overlayType] ) {
		hide_overlay_type(overlayType);

		getElement('side_bar_'+sidebarNum).src
			= 'assets/templates/sjdp/parking_map/side_bar_'+sidebarNum+'.png';
	} else {
		show_overlay_type(overlayType);
		
		getElement('side_bar_'+sidebarNum).src
			= 'assets/templates/sjdp/parking_map/side_bar_'+sidebarNum+'_over.png';
	}
}

function array_contains(ary, value) {
  var i;
  for (i = 0; i < ary.length; i++) {
    if (ary[i] == value) return true;
  }
  return false;
}

function clear_overlays() {
	var i;
	
	for ( i = 0 ; i < current_overlays.length ; i++ ) {
		map.removeOverlay(current_overlays[i]);
	}
	
	current_overlays = [];
}

function getElement(element) {
  if (typeof element == 'string')
    element = document.getElementById(element);
  return element;
}

function toggle_poi(a, poiNum) {
	if ( poiMarkers[poiNum] ) {
		// Marker is on; turn it off.
		$(a).up("li").removeClassName("on");
		
		map.removeOverlay(poiMarkers[poiNum]);
		poiMarkers[poiNum] = null;
	} else {
		// Marker is off; turn it on.
		$(a).up("li").addClassName("on");
		
		var icon = new GIcon(poiIcon);
		icon.image = 'assets/templates/sjdp/parking_map/green_marker_'+poiNum+'.png';
		poiMarkers[poiNum] = new GMarker(poiLocations[poiNum], icon);
		map.addOverlay(poiMarkers[poiNum]);
	}
}

function concatObject(obj) {
  str='';
  for(prop in obj)
  {
    str+=prop + " value :"+ obj[prop]+"\n";
  }
  return(str);
}


function map_click ( marker, latlng,point ) {
	var i;
//	alert(concatObject(marker));
//	alert(latlng);
//	alert(point);

	if ( latlng || !marker.C ) {
		// This seems to happen when a balloon's close box is clicked.
		return;
	}
	for ( i = 0 ; i < data.garages.length ; i++ ) {
		if ( data.garages[i].points.length > 2
				&& in_poly(point, data.garages[i].points) ) {
			open_garage_info_window(data.garages[i], point);

		return;
		}
	}
	
	for ( i = 0 ; i < data.moto_lots.length ; i++ ) {
		if ( data.moto_lots[i].click_polygon_points
				&& in_poly(point, data.moto_lots[i].click_polygon_points) ) {
			open_moto_info_window(data.moto_lots[i], point);
			return;
		}
	}
}

function map_zoomend ( old_zoom, new_zoom ) {
	var i;
	
	if ( old_zoom == new_zoom ) {
		return;
	}
//	alert(old_zoom + " old zoom "+ new_zoom + " new zoom");
	if ( zoomed_data[new_zoom] ) {
		switch_zoomed(new_zoom);
	} else {
		load_zoom(new_zoom);
	}
}

function switch_zoomed ( new_zoom ) {
	data = zoomed_data[new_zoom];
	
	update_overlays();
}

function load_zoom ( zoom ) {
	clear_overlays();
	
	new Ajax.Request('data.html&json=1&zoom=' + zoom,
		{
			method : 'get',
			onSuccess : load_data_from_transport,
			onFailure : function () {
				throw "Error getting data from server.";
			}
		});
}

function load_data_from_transport ( transport ) {
	var new_data;
	
	try {
		if ( ! transport.responseText ) {
			throw "No data returned";
		}
		
		// Using true to "sanitize" the data crashes Safari. A straight eval()
		// causes an error in Firefox.
		new_data = transport.responseText.evalJSON(false);
		
		if ( new_data ) {
			zoomed_data[new_data.zoom] = new_data;
			
			init_garages(zoomed_data[new_data.zoom]);
			init_moto_lots(zoomed_data[new_data.zoom]);
			
			if ( map.getZoom() == new_data.zoom ) {
				switch_zoomed(new_data.zoom);
			}
		} else {
			throw "\n\n" + transport.responseText;
		}
	} catch ( e ) {
		alert("Error getting data from server: " + e);
	}
}

function add_table_row ( tbody, header, value ) {
	var tr, e;
	
	tr = document.createElement("TR");
	tbody.appendChild(tr);
	
	e = document.createElement("TH");
	e.appendChild(document.createTextNode(header));
	tr.appendChild(e);
	
	e = document.createElement("TD");
	tr.appendChild(e);
	
	if ( typeof(value) == "string" ) {
		e.appendChild(document.createTextNode(value));
	} else {
		e.appendChild(value);
	}
	
	return tr;
}

function add_table_icons(tbody, garage) {
	if ((garage.programsIdx['free'] != 1) && (garage.programsIdx['validated'] != 1) && (garage.programsIdx['dash'] != 1))
		return;

	var tr = document.createElement("TR");
	tbody.appendChild(tr);

	var td = document.createElement("TD");
	tr.appendChild(td);
	td.colSpan = 2;
	td.style.textAlign = 'center';
	td.innerHTML = '';

	if (garage.programsIdx['validated'] == 1)
		td.innerHTML += ' <img src="assets/images/images/validatedtiny.png"> ';
	if (garage.programsIdx['dash'] == 1)
		td.innerHTML += ' <img src="assets/images/images/dashtiny.png"> ';
}

function open_moto_info_window ( moto_lot, point ) {
	var div, table, tbody, e;
	
	point = point || moto_lot.point_a;
	
	div = document.createElement("DIV")
	div.className = "moto_info";
	
	e = document.createElement("H3");
	e.appendChild(document.createTextNode(
		"Motorcycle parking with " + moto_lot.spaces + " spaces"));
	div.appendChild(e);
	
	table = document.createElement("TABLE");
	div.appendChild(table);
	
	tbody = document.createElement("TBODY");
	table.appendChild(tbody);
	
	add_table_row(tbody, "Address", moto_lot.address);
	add_table_row(tbody, "Spaces", moto_lot.spaces);
	add_table_row(tbody, "Hours", moto_lot.hours);
	
	map.openInfoWindow(point, div);
}

function open_garage_info_window ( garage, point ) {
	var div, table, tbody, e, tr, address, html;
	
	point = point || garage.points[0];
	
	div = document.createElement("DIV")
	div.className = "garage_info";
	
	e = document.createElement("H3");
	e.appendChild(document.createTextNode(garage.name));
	div.appendChild(e);
	
	table = document.createElement("TABLE");
        table.style.textAlign = 'left';
	div.appendChild(table);
	
	tbody = document.createElement("TBODY");
	table.appendChild(tbody);
	
	address = document.createElement("SPAN");
	address.appendChild(document.createTextNode(garage.address));
	
	if ( garage.directions_link ) {
		address.appendChild(document.createTextNode(" "));
		
		e = document.createElement("A");
		e.href = garage.directions_link;
		e.target = "_blank";
		e.innerHTML = "(driving&nbsp;directions)";
		address.appendChild(e);
	}
	
	tr = add_table_row(tbody, "Address", address);
	tr.vAlign = 'top';
	
	if ( garage.has_thumbnail ) {
		html = '<img src="thumbnail.html&id=' + garage.id
			+ '" alt="Garage Entrance Photo" width="90" height="110"'
			+ ' border="0" />';
		
		if ( garage.has_image ) {
			html = '<a href="#" onclick="open_garage_photo_window(&quot;'
					+ point.lat() + '&quot;,&quot;' + point.lng()
					+ '&quot;,&quot;image.html&id='
					+ garage.id + '&quot;);return false">'
				+ html
				+ '<br /><div style="font-size: 9px; text-align: center">'
				+ 'enlarge photo</div></a>';
		}
		
		e = document.createElement("TD");
		e.rowSpan = 5;
		e.innerHTML = html;
		tr.appendChild(e);
	}

	add_table_row(tbody, "Phone", garage.phone).vAlign='top';
	add_table_row(tbody, "Hours", garage.hours).vAlign='top';
	add_table_row(tbody, "Rates", garage.rates).vAlign='top';
	add_table_row(tbody, "Discounts", garage.discounts).vAlign='top';
//	add_table_row(tbody, "Live parking Data", "Test information goes here").vAlign='top';
	add_table_icons(tbody, garage);
	map.openInfoWindow(point, div);
//	infowindow.open(point,div);
//var infowindow = new google.maps.InfoWindow({
//  content: div
//});
//infowindow.open();
}

function open_garage_photo_window(lat, lon, img) {
    div = document.createElement("DIV");

    div.innerHTML = "<img src=\""+img+"\" alt=\"Garage Entrance\" width=\"420\" height=\"280\" />";

    map.openInfoWindow(new GLatLng(lat, lon), div);
}

// this is for the Grand Prix window launch; place in html holding Flash map
function openNewWindow(URLtoOpen, windowName, windowFeatures) { 
	features = 'top=150,left=150,height=500,width=380,toolbar=no,scrollbars=no';
	newWindow=window.open(URLtoOpen,windowName,features); 
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function maximizeWin() {
	if (navigator.appName == "Netscape" & navigator.appVersion.indexOf("Mac") != -1) {
		window.innerWidth = screen.width;
		window.innerHeight = screen.height;
		window.screenX = 0;
		window.screenY = 0;
	}
	else {
		var aw = screen.availWidth;
		var ah = screen.availHeight;
		window.moveTo(0, 0);
		window.resizeTo(aw, ah);
	}
}

