//
// kmaps stuff
// --------------------------------------------------
// Globals
var ZOOM_TO_LEVEL = 8;
var ZOOM_TO_LEVEL_FOR_ADDING = 8;
var map;
var SHOW_MINIMAP = false;

// saving state
var retCenter;
var retLon;
var retLat;
var retZoom;

// constants
var SHADOW_WIDTH = 37;
var SHADOW_HEIGHT = 34;
var ICON_WIDTH = 20;
var ICON_HEIGHT = 34;

var zoomAfterClick = false;

// var DEBUG: this is inserted with php in head.php

var ids2markers = new Array();

var click;
var baseIcon;
var map;

/**
 * Maintain a map (id -> 1) of the markers that need updating before
 * displaying html
 *
 * TODO: this will grow enormous if we aren't smart
 */
var ids2html = new Array();

function online() {
	return KATHYMAPS_ONLINE;
}

function kmapGetDims(lon,lat) {
	//
	// need to decide on the sql statement
	// this was adapted from the ruby code at:
	// 
	//  http://www.geocodeamerica.com/home/proximity
	//
	//
	var b = getSpanLatLng();
	//
	// add a little extra which is about the size of a shadow
	// so we need to translate pixels to latitude and longitude
	// the map width is constant and is written in head.php
	//
	var lonPerPixel;
	var latPerPixe;
	var lonNudge;
	var latNudge;

	lonPerPixel = b.width  / MAP_WIDTH;   // constant
	latPerPixel=  b.height / MAP_HEIGHT;  // constant
	lonNudge = 2*SHADOW_WIDTH  * lonPerPixel; // constant
	latNudge = 2*SHADOW_HEIGHT * latPerPixel; // constant

	var dy = 0.5*b.height + latNudge; 
	var dx = 0.5*b.width  + lonNudge; 

	return new Array(dy,dx);
}

function kmapOnMap(lon,lat) {
	var ds = kmapGetDims();
	return kmapOnMapFromArray(ds,lon,lat);
}

function kmapGetMinMaxs(lon,lat) {
	var ds = kmapGetDims();
	var dy = ds[0];
	var dx = ds[1];

	var minLon = trimCoord(parseFloat(lon) - dx);
	var maxLon = trimCoord(parseFloat(lon) + dx);
	var minLat = trimCoord(parseFloat(lat) - dy);
	var maxLat = trimCoord(parseFloat(lat) + dy);

	return [minLon,maxLon,minLat,maxLat];
}

function kmapOnMapFromArray(ds,lon,lat) {

	var dy = ds[0];
	var dx = ds[1];

	function trimCoord(f) {
		// this is bad
		var ss = (""+f).split(".");
		var a = ss[0];
		var b = ss[1];
		var len = b.length;
		var N = 1000;
		if (len > N) b = b.substring(0,N);
		return a + "." + b;
	}

	var minLon = trimCoord(parseFloat(lon) - dx);
	var maxLon = trimCoord(parseFloat(lon) + dx);
	var minLat = trimCoord(parseFloat(lat) - dy);
	var maxLat = trimCoord(parseFloat(lat) + dy);

	return lat >= minLat && lat <= maxLat
		&&   lon >= minLon && lon <= maxLon;
}

/**
 * Performs an Ajax call using GXmlHttp that will query the db for te
 * points within the vicinity of zoom + lat/lon and return by calling
 * processPoints with the XML result
 */
function googleAjax(zoom, lat, lon) {
	var where;
	var zl = zoom;
	if (false && zl > 10) {
		where = "1";
	} else {

		var mm = kmapGetMinMaxs(lon,lat);

		var minLon = mm[0];
		var maxLon = mm[1];
		var minLat = mm[2];
		var maxLat = mm[3];

		where = "`lat` >= " + minLat + " AND `lat` <= " + maxLat
			+     " AND "
			+     "`lon` >= " + minLon + " AND `lon` <= " + maxLon
			;
	}
	var reqURL = fullPath("db.php") +
		"?where=" + where +
		"&spud=trooper" +
		"&title=kspot" +
		"&db=kmaps" +
		"";
	/**
	 * This is called on every move of the map.
	 *
	 * Something like the following is returned:
	 *
	 * kspots     = query username logged_in kspot+
	 * query      = String
	 * username   = String
	 * logged_in  = 1 | 0
	 s * kspot      = id lat lon ...
	*/
	function processPoints(res) {   
		//
		// sanity check
		//
		if (!res || res=='') {
			note("invalid response");
			return;
		}
		//
		// find the new markers to place on the map
		//
		var info = res.getElementsByTagName("info")[0];
		//
		// these are for every query
		//
		var username = info.getAttribute("username");
		var query = info.getAttribute("query");
		var logged_in = info.getAttribute("logged_in");
		//
		// the main XML element
		//
		var kspots = res.getElementsByTagName("kspot");
		//
		// for caching markers
		//
		var newMarkers = new Array();
		var ids2one = new Array(); // maps ids to 1 if there, 0 if not
		//
		// keep track of what we did for debugging
		//
		var added=0;
		var stayed=0;
		var deleted=0;
		var newOnes=kspots.length;

		for (var i=0; i<kspots.length; i++) {
			var s = kspots[i];
			var id = s.getAttribute("id");
			ids2one[id] = 1;
			//
			// don't make a marker if we already have this id on the map
			//
			var m = ids2markers[id];
			if (emptyMarker(m)) {
				newMarkers[id] = createMarkerFromDomElement(s, username, logged_in, id);
			} else {
				stayed++;
			}
		}
		//
		// remove all those markers on the map that aren't in the new set of IDs
		//
		var total=0;
		for (id in ids2markers) {
			if (ids2one[id] != 1) {
				var m = ids2markers[id];
				removeOverlay(m);
				delete ids2markers[id];// = 0; // mark for deletion
				deleted++;
			} else {
				total++;
			}
		}
		//
		// add all those markers not already on the map
		//
		for (id in newMarkers) {
			var m = newMarkers[id];
			ids2markers[id] = m;
			added++;
		}

		if (DEBUG) {

			function coord(s) {
				s = ""+s;
				var N=10;
				if (s.length>N) s=s.substring(0,N-1);
				return s;
			}

/* 			debug('addedspan',added); */
/* 			debug('stayedspan',stayed); */
/* 			debug('deletedspan',deleted); */
/* 			debug('newonesspan',newOnes); */
/* 			debug('totalspan',total); */

/* 			var center = getCenterLatLng(); */
/* 			var bounds = getBoundsLatLng(); */

/* 			debug('centerspan', center); */
/* 			debug('centerxspan', coord(center.x)); */
/* 			debug('centeryspan', coord(center.y)); */
/* 			debug('lonspan',coord(bounds.maxX-bounds.minX)); */
/* 			debug('latspan',coord(bounds.maxY-bounds.minY)); */
/* 			debug('minxspan',coord(bounds.minX)); */
/* 			debug('maxxspan',coord(bounds.maxX)); */
/* 			debug('minyspan',coord(bounds.minY)); */
/* 			debug('maxyspan',coord(bounds.maxY)); */
/* 			debug('zoomspan',getZoomLevel()); */
/* 			debug('spanspan',getSpanLatLng()); */
/* 			debug('boundsspan',getBoundsLatLng()); */
/* 			debug('numaddedspan',numAdded); */
/* 			debug('numremovedspan',numRemoved); */
		}
	}
	ajaxXML(reqURL, processPoints);
}

function processNewMapZoom(oldZoom,newZoom) {
	refreshMap();
}

function refreshMap() {
	saveState();
	processNewMapMovement();
}

function processNewMapMovement() {
	saveState();
	var zoom = getZoomLevel();
	//if (zoom <= 10) 
	// skip this now
	processMapMovement(zoom);
}

// --------------------------------------------------
// debugging
// --------------------------------------------------

function clearNote() {
	note("");
}

function replaceAll( str, from, to ) {
	//
	// http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_20977681.html
	//
	var idx = str.indexOf( from );
	while ( idx > -1 ) {
		str = str.replace( from, to );
		idx = str.indexOf( from );
	}
	return str;
}

function processMapMovement(zoom) {
	if (zoom >= 10) return;
	var centerPoint = getCenterLatLng();
	var lon = centerPoint.x;
	var lat = centerPoint.y;
	googleAjax(zoom, lat, lon);
}

function loadRating(id) {
	var reqURL = fullPath("do_load_rating_js.php") +
		"?id=" + id +
		"&spud=trooper" +
		"";
	var tagRating = "ratedDiv"+id;
	var tagVotes = "votesDiv"+id;
	var tagYours = "yourRatingDiv"+id;
	var tagViews = "viewsDiv"+id;
	function processLoadRating(res) {
		var theRating = "??";
		var theYours = "??";
		var theViews = "??";
		setInnerHTML(tagRating, theRating);
		setInnerHTML(tagYours, theYours);
		if (res) {
			var info = res.getElementsByTagName("info")[0];
			var suc = info.getAttribute("success");	
			var rating = info.getAttribute("rating");
			var yours = info.getAttribute("yours");
			var votes = info.getAttribute("votes");
			var views = info.getAttribute("views");
			if (suc == "true") {
				if (rating)	theRating = rating;
				if (yours) theYours = yours;
				if (votes) theVotes = votes;
				if (views) theViews = views;
				if (votes && votes==0) theRating="none";
			}
		}
		setInnerHTML(tagRating, formatRating(theRating));
		setInnerHTML(tagVotes, theVotes);
		//setInnerHTML(tagViews, theViews);
		//
		// Now update 'your' rating of this spot
		//
		var yoursHTML;
		if (theYours == -1) {
			yoursHTML = "<em>none</em>";
		} else {
			//yoursHTML = number2stars(theYours);
			yoursHTML = theYours;
		}
		setInnerHTML(tagYours, yoursHTML);
	}
	ajaxXML(reqURL, processLoadRating, counters([tagRating,tagYours,tagVotes]));
}

function saveRating(id) {
	var reqURL = fullPath("do_save_rating_js.php") +
		"?id=" + id +
		"&spud=trooper" +
		"";
	var tagRating = "ratedDiv"+id;
	var tagVotes = "votesDiv"+id;
	var tagYours = "yourRatingDiv"+id;
	function processLoadRating(res) {
		var theRating = "??";
		var theYours = "??";
		setInnerHTML(tagRating, theRating);
		setInnerHTML(tagYours, theYours);
		if (res) {
			var info = res.getElementsByTagName("info")[0];
			var suc = info.getAttribute("success");	
			var rating = info.getAttribute("rating");
			var yours = info.getAttribute("yours");
			var votes = info.getAttribute("votes");
			if (suc == "true") {
				if (rating)	theRating = rating;
				if (yours) theYours = yours;
				if (votes) theVotes = votes;
			}
		}
		setInnerHTML(tagRating, formatRating(theRating));
		setInnerHTML(tagVotes, theVotes);
		//
		// Now update 'your' rating of this spot
		//
		var yoursHTML;
		if (theYours == -1) {
			yoursHTML = "<em>none</em>";
		} else {
			//yoursHTML = number2stars(theYours);
			yoursHTML = theYours;
		}
		setInnerHTML(tagYours, yoursHTML);
	}
	ajaxXML(reqURL, processLoadRating, counters([tagRating,tagYours,tagVotes]));
}

function number2stars(n) {
	s = "";
	//
	// don't want to deal with floats
	//
	var ss = (""+n).split('.');
	var fst,lst;
	if (ss.length == 1) {
		fst = ss[0];
		lst = 0;
	} else {
		fst = ss[0];
		lst = ss[1];
	}
	if (lst.length>1) lst=lst.substring(0,1);
	for (var i=0; i<fst; i++) s += "<img src=images/star_icon.png border=0 />";
	var next = fst;
	if (lst != 0) {
		s += "<img src=images/star_0" + lst + ".png border=0 />";
		next++;
	}
	for (var i=next; i<5; i++) s += "<img src=images/graystar_icon.png border=0 />";
	return s;
}


function recordView(id,views) {
	var reqURL = fullPath("do_record_view_js.php") +
		"?id=" + id +
		"&views=" + views +
		"&spud=trooper" +
		"";
	var tag = "viewsDiv"+id;
	function processRecordView(res) {
		var info = res.getElementsByTagName("info")[0];
		var suc = info.getAttribute("success");
		var newViews = info.getAttribute("views");
		setInnerHTML(tag, newViews);
	}
	ajaxXML(reqURL, processRecordView, counter(tag));
}


function showKSpot(id,lon,lat) {

	if (!online()) return;
	
	var marker = createMarker(id,lon,lat,true);
	var lon = markerLon(marker);
	var lat = markerLat(marker);
	
	centerMap(lon,lat);	
	
}

function markerLon(marker) {
	return marker.getPoint().x;
}

function markerLat(marker) {
	return marker.getPoint().y;
}

function createHTMLFromIdIntoDiv(id,div,marker) {

	var res = '';

	function processId(res) {   
		note("processId("+id+")");
		//
		// sanity check
		//
		if (!res || res=='') {
			note("invalid response");
			return;
		}
		//
		// find the new markers to place on the map
		//
		var info = res.getElementsByTagName("info")[0];
		//
		// the main XML element
		//
		var kspots = res.getElementsByTagName("kspot");

		var kspot = kspots[0];
		//var username = info.getAttribute("username");
		var username = theUsername;
		var html = createHTML(kspot, username, loggedIn);
		
		closeInfoWindow();

		if (!marker) {
			var id = kspot.getAttribute("id");
			var lat = kspot.getAttribute("lat");
			var lon = kspot.getAttribute("lon");
			marker = newMarker(id,lon,lat);
		}
		marker.openInfoWindowHtml(html);
		res = marker;
	}

	var reqURL = fullPath("do_load_kspot_js.php") +
		"?id=" + id +
		"&spud=trooper" +
		"";
	if (marker) {
		ajaxXML(reqURL, processId, counter(div));
	} else {
		ajax(reqURL, {f: processId, counter: div, asynch: false});
	}
	return res;
}

/**
 * We always will have access to the username and title
 * so create the into pane here
 *
 * username: person logged in
 * uname: owner of this spot
 */
function createMarker(id,lon,lat,showIt,username,uname,title) {
	var marker = ids2markers[id];
	if (marker) {
		if (showIt) openMarker(marker,id);
		return marker;
	}

	//
	// if we don't have the lat and lon we need to get it now
	//
	if (!lon || !lat) {
		//
		// we are showing this marker anyway so we can immediately
		// open the html and make sure that next time it looks it up again
		//

		//TODO: Need to create into html here

		var div = 'marker_' + id;
		marker = createHTMLFromIdIntoDiv(id,div);
	} else {
		marker = newMarker(id,lon,lat);
		addListenerToMarker(marker,id,username,uname,title);
		if (showIt) openMarker(marker,id);
	}
	return marker;
}

// remember the marker over which we are (haha!)
var markerOnWhichTheMouseIs;

function mouseOutMarker(marker) {
	//closeInfoWindow();
	//markerOnWhichTheMouseIs=0;
}

/**
 * username: person logged in
 * uname: owner of this spot
 */
function mouseOverMarker(marker,id,username,uname,title) {
	
	// already showing
	if (markerOnWhichTheMouseIs == marker) return;

	var dom = htmlStartDOM(id);
	var a;
	var div;
	var em;
	
	a = $n('a',dom);
	a.style.fontSize = "1.2em";
	a.appendChild($t(title));
	a.href= 'javascript:showKSpot("' + id  + '");';
	
	dom.appendChild($t(' by '));
	a = $n('a',dom);
	a.href= userLinkString(username,uname);
	em = $n('em',a);
	em.appendChild($t(username==uname ? "you" : uname));
	
	dom.appendChild($n('br'));
	
	div = $n('small',dom);
	a = $n('a',div);
	a.appendChild($t('zoom'));
	a.href= 'javascript:zoomTo(' + markerLon(marker) + ',' + markerLat(marker) + ');';

	marker.openInfoWindow(dom);

	markerOnWhichTheMouseIs = marker;
	
}

function openMarker(marker,id) {

	//
	// Create the initial html
	//
	var div = 'marker_' + id;
	var html = htmlStart(id,true);
	html += '<div id="' + div + '"></div>';
	html += htmlEnd();
	//
	// open it
	//
	marker.openInfoWindowHtml(html);
	//
	// now populate the html with some goods
	//
	createHTMLFromIdIntoDiv(id,div,marker);
	afterLoading(id);
}

/**
 * username: person logged in
 * uname: owner of this spot
 */
function addListenerToMarker(marker,id,username,uname,title) {
	GEvent.addListener(marker, 'click', function() {openMarker(marker,id);});
	GEvent.addListener(marker, 'mouseover', function() {mouseOverMarker(marker,id,username,uname,title);});
	GEvent.addListener(marker, 'mouseout', function() {mouseOutMarker(marker);});
}

function newPoint(lon,lat) {
	//return new GPoint(lon,lat);
	return new GLatLng(lat,lon);
}

function newMarker(id,lon,lat) {
	//var point = new GPoint(lon,lat);
	var point = newPoint(lon,lat);
	var icon = new GIcon(baseIcon);
	icon.image = "mapicons/iconb.png";
	var marker = new GMarker(point, icon);
	ids2markers[id] = marker;
	addOverlay(marker);
	return marker;
}

//interface
function createMarkerFromDomElement(s, username, logged_in, id) {

	if (!online()) return;

	var lon = s.getAttribute("lon");
	var lat = s.getAttribute("lat");
	var uname = s.getAttribute("username");
	var title = s.getAttribute("title");

	var marker = createMarker(id,lon,lat,false,username,uname,title);
	
	return marker;
};

function afterLoading(id) {
	//recordView(id);
	//loadRating(id);
	//loadComments(id);
}

/**
 * Does no caching, but will create an html element from
 * the info element
 */
function createHTML(e, username, logged_in) {

	var id = e.getAttribute("id");

	note("Creating html for " + id);

	var title = e.getAttribute("title");
	var desc = e.getAttribute("desc");
	var lat = e.getAttribute("lat");
	var lon = e.getAttribute("lon");
	var uname = e.getAttribute("username");
	var dateadded = e.getAttribute("dateadded");
	var tags = e.getAttribute("tags");
	var address = e.getAttribute("address");
	var type = e.getAttribute("type");
	var views = e.getAttribute("views");
	var rated = e.getAttribute("rating"); //"?"; //TODO e.getAttribute("rated");
	var votes = e.getAttribute("votes"); //"?"; //TODO e.getAttribute("rated");
	var cat = e.getAttribute("category");
	var yours = e.getAttribute("yourrating");

	var numComments = e.getAttribute('num_comments');
	var comments = e.getElementsByTagName("comment");

	// clean up the fields
	if (!views || views==null || views=='') views=0;

	// should we allow this person to edit
	var isMine = uname == username;
	var editable = isMine;

	var newDesc = wrapString(desc);
	
	var s = '<div id="mainInfoDiv' + id + '" style="max-width: 400; padding: 2px; white-space: nowrap;">';
	var show_top = true;
	if (show_top) {
		//
		// This is the logo, sms, etc... mainly bullshit right now
		//
		var top = '';
		top += '<table border=0 cellpadding=0 cellspacing=0 width=100%>';
		top += '<tr width=100%>';
		top += '<td>' + image('kathymaps_logo-small.jpg') + '</td>';
		top += '<td style="font-weight: normal; font-size: 8pt;">';
		top +=       linkPrint(id);
		top += ' ' + linkEmail(id);
		top += ' ' + linkSMS(id);
		top += '</td>';
		top += '</tr>';
		top += '</table>';
		s += top;
	}
	s += addTitleEtc(title, address, type, id, editable);

	s += '<table border=0 cellpadding=0 cellspacing=0 width=100%>';
	s += '<tr><td valign=middle>';
	s += '<span style="vertical-align: top; font-weight: normal; font-size: 9pt;">';
	s += 'submitted by ' + userLink(username,uname,false) + ' on ' + formatDate(dateadded);
	s += '<br/>tags:';
	if (tags != null && tags != "") {
		var arr = tags.split(" ");
		$A(arr).each(function(n) {s += linkTag(n);});
	} else {
		s += " <em>none</em>";
	}
	s += '</span>';
	s += '</td><td valign=top align=center>';
	var catImage =  categoryImage(cat);
	s += catImage;
	s += '</td></tr>';
	s += '<tr><td colspan=2 align=right class=secondary>';

	rated = formatRating(rated);
	var title_rest = 'rated: <span class=inputvalue><span id="ratedDiv' + id + '">' +  rated + '</span>/5</span>'
    +              '&nbsp;'
		+              'votes: <span id="votesDiv' + id + '" class=inputvalue>'       +  votes + '</span>'
    +              '&nbsp;'
		+              'views: <span id="viewsDiv' + id + '" class=inputvalue>'       +  views + '</span>';
	s += title_rest;
	s += '</td></tr></table>';
	s += '<p>'	
	+ '<div style="font-weight: normal; font-size: .95em;">' 
		+ (editable ? createTextAreaToggleField("desc",newDesc,5,40,id) : newDesc)
		+ '<p>';
	//
	// the zoom, comment, rate, etc options
	//
	s += '<br/>';
	s += '<table width=100% border=0 cellpadding=0 cellspacing=0>';
	s += '<tr>';
	if (!isMine) {
		var yours = formatRating(yours);
		s += '<td style="text-align: left;" class=secondary>';
		s += '<b>Your rating: </b>';
		s += '<span valign=middle>';
		s += '<span valign=middle class=inputvalue id=yourRatingDiv'+id+ '>';
		s += yours;
		s += '</span><span class=inputvalue>/5</span>';
		s += ' [<span id=ratingLink' + id + ' >' +  changeRatingLink(id) + '</span>]';
		s += '</span>';
		s += '</td>';
	}
	s += '<td style="text-align: right;" class=secondary>';
	s += linkZoom(lon,lat) + ' ';
	if (logged_in == 0) {
		s += '<i>' + linkLogin() + ' to post comments</i>';
	} else {
	
	// remove (maybe)
		if (username == uname) {
			var removeLink = "javascript:showRemoveConfirmScreen("
				+ " \"" + id      + "\""
				+ ");";
		s += '<a href=\'' + removeLink + '\'>remove</a> ';

		}

		// comment
		var commentLink = "javascript:showCommentScreen("
			+ " \"" + id      + "\""
			+ ");";
		s += '<a  id=commentLink' + id + ' href=\'' + commentLink + '\'>comment</a>';

	}
	s += '</td></tr></table>';
	//
	// Put all the comments
	//
	s += '<span id=commentHeadingDiv style="font-weight: bold;" class=secondary>Comments</span>';
	s += "<div  style=\"max-width: 300px; \" id=commentsDiv" + id + " >";
	s += loadCommentsHTML(comments,numComments,username);
	s += "</div>";

	s += '<div id=commentDiv' + id + ' style="font-weight: normal; font-size: 10pt;"></div>';
	s += '</div>';	
	s += htmlEnd();
	return s;
}

function loadComments(id) {
	//
	// because of stupid javascript we have to save this
	// because we declared another id below
	//
	var theID = id;
	setCommentsHtml("<em>loading...</em>",theID);
	var where = "`spotId` = " + q(id);
	var reqURL = fullPath("db.php") +
		"?where=" + where +
		"&spud=trooper" +
		"&title=comment" +
		"&db=comments" +
		"";
	function processComments(res) {
		var username = res.getElementsByTagName("info")[0].getAttribute("username");
		var comments = res.getElementsByTagName("comment");
		var html = loadCommentsHTML(comments,comments.length,username);
		setCommentsHtml(html, id);
	}
	ajaxXML(reqURL, processComments, counter("commentsDiv" + id));
}

function loadCommentsHTML(comments,numComments,username) {
		var html;
		if (!comments) {
			//todo
			html = "error";
		} else if (comments.length == 0) {
			html = "<em>none</em>";
		} else {
			s = "<ol>";
			//for (var i=0; i<comments.length; i++) {
			$A(comments).each(function(c) {
													//var c = comments[i];
				var uname = c.getAttribute("username");
				var id = c.getAttribute("spotId");
				var dateadded = c.getAttribute("dateadded");
				s += "<li class=small>";
				s += c.getAttribute("comment");
				s += "<br/>&nbsp;&nbsp;<em>by " + userLink(username,uname,false);
				s += " -- " + formatDate(dateadded) + "</em>";
				if (username == uname) {
					var js = "removeComment(\"" + id + "\",\"" + dateadded + "\")";
					s += " [<a href=\"" + VOIDLINK + "\" onClick='javascript:" + js + "'>remove</a>]";
				}
				s += "</li>";
											 });
			s += "</ol>";
			html = s;
		}
		return html;
}

function removeComment(id,dateadded) {
	var reqURL = fullPath("do_remove_comment_js.php") +
		"?spotId=" + id +
		"&dateadded=" + dateadded +
		"&spud=trooper" +
		"";
	function processRemoveComment(res) {
		var info = res.getElementsByTagName("info")[0];
		if (!info) {
			//todo
		}
		var suc = info.getAttribute("removed");
		var comment = info.getAttribute("comment");
		var dateadded = info.getAttribute("dateadded");
		if (suc && suc == "true") {
			var id = info.getAttribute("spotId");
			loadComments(id);
		} else {
			//todo
			alert("unable to remove comment");
		}
	}
	ajaxXML(reqURL, processRemoveComment);
}

function setCommentsHtml(s,id) {
	var e = document.getElementById("commentsDiv" + id);
	if (e) e.innerHTML = s;
}

function changeRatingLink(id) {
	var changeRatingLink = "javascript:showRatingScreen(\"" + id + "\");";
	return '<a href=\'' +  changeRatingLink + '\'>change</a>';
}

function showRatingScreen(id) {

	// get the rating
	var rating = e("yourRatingDiv"+id).innerHTML;

	var html = "";
	
	html += "<form id=ratingForm"+id+" style='display:inline; font-size: 8pt;' action=\"\">";
	html += "<input type=hidden name=theId value='" + id + "'>";
	html += "<input type=hidden name=oldRating value='" + rating + "'>";
	html += "<select id=newRating class=inputvalue style='font-size: 8pt;' >";
	for (var i=0; i<=5; i++) {
		html += "<option ";
		if (i==rating) html += "selected ";
		html += "class=inputvalue style='font-size: 8pt' value='" + i + "'>" + i;
	}
	html += "</select>";
	html += "</form>";

	var saveLink = 'javascript:rateKSpot("'+id+'","'+rating+'");';
	var cancLink = 'javascript:hideRatingScreen("'+id+'","' + rating + '");';

	setInnerHTML("yourRatingDiv" + id, html);

	var saveHref = "<a " + voidHref() + " onClick='" + saveLink + "' class=savelink >save</a>";
	var cancHref = "<a " + voidHref() + " onClick='" + cancLink + "' class=cancellink >cancel</a>";

	setInnerHTML("ratingLink" +id, saveHref + " " + cancHref);
}

function hideRatingScreen(id,rating) {
	theRating = rating ? rating : 0;
	setInnerHTML("yourRatingDiv" + id, rating);
	setInnerHTML("ratingLink"+id, changeRatingLink(id));
}

function rateKSpot(id,oldRating) {
	//var id = f.theId.value;
	//var oldRating = f.oldRating.value;
	//var newRating = f.newRating.value;
	var newRating = e("ratingForm"+id).newRating.value;
	//
	// If they are the same do nothing
	//
	if (newRating && oldRating && newRating == oldRating) {
		hideRatingScreen(id,newRating);
		return;
	}
	var url = fullPath("do_rate_kmap_js.php")
		+ "?id=" + id
		+ "&rating=" + newRating
		+ "&spud=trooper"
		;
	function processRateKSpot(res) {
		var info = res.getElementsByTagName("info")[0];
		if (!info) {
			//todo
		}
		var suc = info.getAttribute("rated");
		var newRating2 = info.getAttribute("rating");
		var action = info.getAttribute("action");
		if (suc && suc == "true" && newRating2) {
			var id = info.getAttribute("id");
			hideRatingScreen(id,newRating2);
			saveRating(id);
		} else {
			//todo
			hideRatingScreen(id,oldRating);
		}
	}
	ajaxXML(url,processRateKSpot);
	return false;
}


function showCommentScreen(id) {

	var html = "";
	
	html += "<br/>Post new comments";
	html += "<form action=\"\" onSubmit=\"return commentKSpot(this);\">";
	html += "<input type=hidden name=spotId value=" + id + ">";
	html += "<input type=hidden name=retlat value=" + retLat + ">";
	html += "<input type=hidden name=retlon value=" + retLon + ">";
	html += "<input type=hidden name=retzoom value=" + retZoom + ">";
	html += "<textarea class=formfieldToggle  name=comment rows=5 cols=50 id=comment ></textarea>";
	html += "<br/>";
	html += "<input class=formsubmit type=submit value=Comment>";
	html += "</form>";

	setInnerHTML("commentDiv" + id, html);

	
	var a = document.getElementById("commentLink" + id);
	var commentLink = "javascript:hideCommentScreen(\"" + id + "\");";
	a.href = commentLink;
	a.innerHTML = "hide";
	a.setAttribute("class", "cancellink");
}

function hideCommentScreen(id) {

	setInnerHTML("commentDiv" + id, "");

	var a = document.getElementById("commentLink" + id);
	var commentLink = "javascript:showCommentScreen(\"" + id + "\");";
	a.href = commentLink;
	a.innerHTML = "comment";
	a.setAttribute("class", "editlink");
}

function commentKSpot(f) {
	//todo: grab the fields
	var id = f.spotId.value;
	var comment = f.comment.value;
	var url = fullPath("do_comment_kmap_js.php")
		+ "?spotId=" + id
		+ "&comment=" + urlencode(comment)
		+ "&spud=trooper"
		;
	function processCommentKSpot(res) {
		var info = res.getElementsByTagName("info")[0];
		if (!info) {
			//todo
		}
		var suc = info.getAttribute("added");
		var comment = info.getAttribute("comment");
		var dateadded = info.getAttribute("dateadded");
		if (suc && suc == "true") {
			var id = info.getAttribute("spotId");
			hideCommentScreen(id);
			loadComments(id);
		} else {
			//todo
		}
	}
	ajaxXML(url,processCommentKSpot);
	return false;
}


//todo: have a callback
function showRemoveConfirmScreen(id) {
	
	var html = "";
	html += htmlStart(id);
	html += "Are you sure you want to remove this point?";
	html += "<center>";
	html += "<br/>";

	var jsRemove = "removeKSpot("+ id + ");";
	html += "<input type=submit class=formsubmit value=Yes name=Remove onClick=\"" 
		+ jsRemove + "\">";

	html += " ";

	var jsCancel = "closeInfoWindow();";
	html += "<input type=submit class=formsubmit value=No name=Cancel onClick=\""
		+ jsCancel + "\">";

	html += "</center>";
	html += htmlEnd();
	

	setInnerHTML("mainInfoDiv" + id, html);
}

function removeKSpot(id) {
	var url = fullPath("do_remove_kmap_js.php")
		+ "?id=" + id
		+ "&spud=trooper"
		;
	function processRemoveKSpot(res) {
		var info = res.getElementsByTagName("info")[0];
		if (!info) {
			//todo
		}
		var suc = info.getAttribute("removed");
		if (suc && suc == "true") {
			closeInfoWindow();
			refreshMap();
			var marker = ids2markers[id];
			if (marker) {
				removeOverlay(marker);
				ids2markers[id] = 0;
				delete ids2markers[id];
				//
				// notify all listeners
				//	
				theEvents.notifyListeners('delete', {id: id, info: info});
			}
		} else {
			// todo
		}
	}
	ajaxXML(url,processRemoveKSpot);
	return false;
}


/****************************** MAP INTERACTION ******************************/

function kmapOnMap(lon,lat) {

}

function markDirty(id,info) {
	note("markDirty("+id+")");
	ids2html[id] = 1;
	//createHTMLFromId(id,"");
	theEvents.notifyListeners('edit', {id: id, info: info});
}

function markAllDirty(event) {
	var ids = [];
	for (var id in ids2html) {delete ids2html[id]; ids[ids.length] = id; }
	for (var id in ids2markers) {delete ids2markers[id]; ids[ids.length] = id;}
	theEvents.notifyListeners(event, ids);
}

function saveState() {
	retCenter = getCenterLatLng();
	retLon = retCenter.x;
	retLat = retCenter.y;
	retZoom = getZoomLevel();
}

var ZOOM_TO = 4;
function zoomTo(lon,lat) {

	if (getZoomLevel() <= ZOOM_TO) {
		if (getZoomLevel() > 0) {
			centerAndZoom(lon,lat,getZoomLevel()-1);
		} else {
			centerMap(lon,lat);
		}
	} else {
		centerAndZoom(lon,lat,ZOOM_TO);
	}
}

function getSpanLatLng() {
	return map.getSpanLatLng();
}

function getBoundsLatLng() {
	return map.getBoundsLatLng();
}

function getCenterLatLng() {
	return map.getCenterLatLng();
}

function getZoomLevel() {
	return map.getZoomLevel();
}

function centerMap(lon,lat) {
	map.centerAtLatLng(newPoint(lon,lat));
}

function centerAndZoom(lon,lat,zoom) {
	map.centerAndZoom(newPoint(lon,lat), zoom);
}

function zoom(zoom) {
	map.centerAndZoom(getCenterLatLng(), zoom);
}

function centerOn(lon,lat) {
	var point = newPoint(lon,lat);
	var toZoom = getZoomLevel();
	map.centerAndZoom(point, toZoom)
		}

function openInfoWindowHtml(marker, html, removeOverlay) {
	_marker = marker;
	var onOpen2 = function() {
		GEvent.removeListener(map, "infowindowopen", onOpen2);
	};
	var onClose2 = function() {
		if (removeOverlay) removeOverlay(marker);
		GEvent.removeListener(map, "infowindowclose", onClose2);
	};
	GEvent.addListener(map, "infowindowopen", onOpen2);
	GEvent.addListener(map, "infowindowclose", onClose2);
	marker.openInfoWindowHtml(html);
}

var numAdded;
function addOverlay(marker) {
	try {
		map.addOverlay(marker);
		numAdded++;
	} catch (e) {handle(e);}
}

var numRemoved;
function removeOverlay(marker) {
	try {
		map.removeOverlay(marker);
		numRemoved++;
	} catch (e) {handle(e);}
}

function closeInfoWindow() {
	map.closeInfoWindow();
}

var handled = false;
function handle(e) {
	if (!handled) alert(e);
	handled = true;
}

/****************************** MISC ******************************/


/****************************** KEY PRESSES ******************************/

function getKey(e) {
	var evt=(e)?e:(window.event)?window.event:null;
	var key = "";
	if(evt){ 
		key=(evt.charCode)?evt.charCode: ((evt.keyCode)
																			?evt.keyCode:((evt.which)?evt.which:0));
	}
	return key;
}

function captureKeyPresses() {
	var nn=(document.layers)?true:false;
	var ie=(document.all)?true:false;

	function keyDown(e) { 	
		var k = getKey(e);
		if (k=="65") click='a'; // adding a point
		if (k=="88") click='x'; // zooming in
		if (k=="90") click='z'; // showing info
		
	}
	function keyUp(e) { 
		var k = getKey(e);
		if (k=="65") click=0;
		if (k=="88") click=0;
		if (k=="90") click=0;
	}
	document.onkeydown=keyDown;
	document.onkeyup=keyUp;
	if(nn) document.captureEvents(Event.KEYDOWN);
}

function click(overlay, point) {
	if (click == 'a') addPoint(overlay, point);
	if (click == 'z') showZoom(overlay, point);
	if (click == 'x') showInfo(overlay, point);
}

function showInfo(overlay, point) {
	var msg = point + "\n";
	msg += "Center: " + getCenterLatLng() + "\n";
	msg += "Bounds: " + getBoundsLatLng() + "\n";
	msg += "Span: " + getSpanLatLng() + "\n";
	var total =0;
	for (i in ids2markers) if (!emptyMarker(ids2markers[i])) total++;
	msg += "Total: " + total + "\n";
	alert(msg);
}


function showZoom(overlay, point) {
	map.showMapBlowup(point);
}

function addPoint(overlay, point) {
	//
	// want a single point of control for adding points
	// so we can do this through redirection
	//
	addPointByForce(overlay,point,"","","","");
}

function addTitle(title, id, editable, opts) {
	return addTitleEtc(title, "", "", id, editable, opts);
}

function addTitleEtc(title, address, addressType, id, editable, opts) {
	var variableWidth = false;
	if (opts) {
		variableWidth = opts['variableWidth'];
	}
	var style = "";
	if (!variableWidth) style += "min-width: 400px; width: 100%; ";
	style += "font-size: 14pt; font-weight: bold; border-bottom: solid 1px #000000;";

	//
	// is this editable
	//
	var html = "<div id=mainTitleDiv" + id + " style=\"" + style + "\">" 
		+ (editable ? createTextToggleField("title",title,20,id) : title)
		+ "</div>";
	html += "<div style=\"font-size: 10pt; border-bottom: none;\">" ;

	if (addressType == "url") {
		html += '<a href="';
		html += address;
		html += '">' + (editable ? createTextToggleField("address",address,40,id) : address) + '</a>';
	} else {
		html += (editable ? createTextToggleField("address",address,40,id) : address);
	}
	html += "</div>";
	return html;
}

var _overlay;
var _point;
var _address;
var _addressType;
var _reqTitle;
var _reqDesc;
var _marker;
var _onClose;

var _newHtml;

function addPointByForce3() {
	//
	// this is a *total* hack
	//
	//document.getElementById("addInner").innerHTML = _newHtml;
	map.closeInfoWindow();
	addOverlay(_marker);
	_marker.openInfoWindowHtml(_newHtml);
}


function searchForAddress(addr) {
	var url = "http://rpc.geocoder.us/service/rest?address=" + urlencode(addr);
	
}

function addKSpot(f) {
	var url = "add_kmap_js.php";
	url += "?new_lat=" + f.new_lat.value;
	url += "&new_lon=" + f.new_lon.value;
	url += "&new_address=" + urlencode(f.new_address.value);
	url += "&new_type=" + f.new_type.value;
	url += "&new_title=" + f.new_title.value;
	url += "&new_tags=" + f.new_tags.value;
	url += "&new_desc=" + urlencode(f.new_desc.value);
	url += "&new_category=" + f.new_category.value;
	url += "&retlon=" + f.retlon.value;
	url += "&retlat=" + f.retlat.value;
	url += "&retzoom=" + f.retzoom.value;
	url += "&spud=trooper";
	var ret = true;
	if (f.new_title.value == '') {
		document.getElementById("title_msg").innerHTML = "<font color=red>fill this in!</font>";
		ret = false;
	}
	if (f.new_desc.value == '') {
		document.getElementById("desc_msg").innerHTML = "<font color=red>fill this in!</font>";
		ret = false;
	}
	ajaxXML(url,processAddKSpot);
	return false;
}

function processAddKSpot(res) {
	var info = res.getElementsByTagName("info")[0];
	if (!info) {
		//todo
	}
	var suc = info.getAttribute("added");
	var id = info.getAttribute("id");
	if (suc && suc == "true") {
		if (_marker) removeOverlay(_marker);
		closeInfoWindow();
		_onClose = null;
		refreshMap();
		//
		// make sure that marker is shown
		//
		//showKSpot(id,-1,'',info,true);
		//
		// notify all listeners
		//
		theEvents.notifyListeners('add', {id: id, info: info});
	} else {
		// todo
	}
}

function gotoAddress(address) {
	//
	// first check for easter eggs
	//
	try {
		if (!processEasterEgg(address)) geocode(address);
	} catch (e) {alert(e);}
	return false;
}

/**
 * Called from the upper-right text box
 */
function geocode(address) {
	var start = "geocoder.php?address=";
	var url = start + urlencode(address);
	ajaxXML(url, function(res) {processGeocode(res,address);});
	return false;
}

function processGeocode(res,address) {
	if (res) {
		var des = address; //res.getElementsByTagName("description")[0].firstChild.data;
		var lat = text(res, "Latitude");
		var lon = text(res,"Longitude");
		var precision = res.getElementsByTagName("Result")[0].getAttribute("precision");
		if (precision == "address") {
			var newAddress = text(res,"Address") + " " 
				+              text(res,"City")    + ", " 
				+              text(res,"State")   + ", "
				+              text(res,"Country") + ", "
				+              text(res,"Zip");
			addNewKSpot(lon,lat,address,precision);
		} else {
			map.centerAndZoom(newPoint(lon,lat), 6);
		}
		document.getElementById("addressInput").value="";
	} else {
		alert("Couldn't find the address:\n\n   " + address);
	}
}

function addNewKSpot(lon,lat,address,precision) {
	var point = newPoint(lon,lat);
	addPointByForce(null,point,address,"address","","");
}

var count=0;
function addPointByForce(overlay, point, address, addressType, reqTitle, reqDesc) {
	//
	// sanity check
	//
	if (!point) return;
	//
	// capture the closure here
	//
	_overlay = overlay;
	_point = point;
	_address = address;
	_addressType = addressType;
	_reqTitle = reqTitle;
	_reqDesc = reqDesc;

	var icon = new GIcon(baseIcon);
	icon.image = "mapicons/icong.png";

	var marker = new GMarker(point, icon);

	addOverlay(marker);

	//skip this now
	//map.centerAtLatLng(point);
	if (zoomAfterClick) {		var wantZoom = 	loggedIn ? ZOOM_TO_LEVEL_FOR_ADDING : ZOOM_TO_LEVEL;
		var toZoom = getZoomLevel();
		if (toZoom >= wantZoom) toZoom = wantZoom;
		if (getZoomLevel() > ZOOM_TO_LEVEL_FOR_ADDING) map.zoomTo(ZOOM_TO_LEVEL_FOR_ADDING);
	}

	GEvent.addListener(marker, "infowindowclose", function() {
											 removeOverlay(marker);
										 });
	
	GEvent.addListener(marker, "click", 
										 function(overlay,pointForgetIt) {
											 
											 // this point (pointForgetIt) will be undefined

											 //skip it if (!overlay) return;
											 //
											 // this is the new html we'll shove in
											 //
											 var newHtml = htmlStart();
											 if (loggedIn) {
		
												 newHtml += addTitleEtc("Add a KathySpot", address, addressType,"", "");
												 newHtml += ""
													 + "<form name=form1 method=post action=add_kmap.php onSubmit=\"return addKSpot(this);\">"
													 + "<input type=hidden name=new_lat id=new_lat value=" + point.y + ">"
													 + "<input type=hidden name=new_lon id=new_lon value=" + point.x  + ">"
													 + "<input type=hidden name=new_address id=new_address value=\"" + address  + "\">"
													 + "<input type=hidden name=new_type id=new_type value=" + addressType  + ">"
													 + "<div style=\"font-size: 8pt\" >Title"
													 + " <span id=title_msg></span>"
													 + "</div>"
													 + "<input class=formfield  name=new_title type=text id=new_title size=50>"
													 + "<div style=\"font-size: 8pt\" >Tags</div>"
													 + "<input class=formfield  name=new_tags type=text id=new_tags size=50>"
													 + "<div style=\"font-size: 8pt\" >Description"
													 + " <span id=desc_msg></span>"
													 + "</div>"
													 + "<textarea class=formfield  name=new_desc rows=3 cols=50 id=new_desc >"
													 + "</textarea>"
													 + "<div style=\"font-size: 8pt\" >Category</div>"
													 + "<select name=new_category>"
													 + "<option value=\"1\">general driving info</option>"
													 + "<option value=\"2\">time-of-day hints</option>"
													 + "<option value=\"3\">weather watch-outs</option>"
													 + "<option value=\"4\">construction/roadwork</option>"
													 + "<option value=\"5\">authorities</option>"
													 + "<option value=\"6\">stories, history, folklore</option>"
													 + "</select>"
													 + "<input type=hidden name=retlon value=" + retLon + ">"
													 + "<input type=hidden name=retlat value=" + retLat + ">"
													 + "<input type=hidden name=retzoom value=" + retZoom + ">"
													 + "<div><input class= formsubmit type=submit name=Add value=Add></div>"
													 + "</form>";
			
											 } else {
												 newHtml += addTitle("Welcome","Welcome",'',{fulwidth: false});
												 newHtml +=  "<p>Please " + linkLogin('log in') + " or " 
													 + linkRegister('register') + " to add points.</p>";
											 }

											 newHtml += htmlEnd();

											 _newHtml = newHtml;

											 var js = "addPointByForce3();";
											 var whichmini = "minimap" + count++;


											 //
											 // add a green pushpin with a close up
											 //
											 var html = htmlStart("new");
	
											 html += "<div id=\"addInner\">";
											 html += addTitleEtc(randomHello(), "(<em>hello</em> in another language)", "", "Hello", "");
											 html += '<table border=0 cellpadding=0 cellspacing=0><tr>';
											 if (SHOW_MINIMAP){
												 html += '<div id="';
												 html += whichmini + '" style="width: 200px; height: 200px">';
												 html += '</div>';
											 } else {
												 html += '<br/><br/>';
											 }
											 html += "</td><td valign=top>";
											 html += "&nbsp;- <a href=\"javascript:" + js + "\">make</a> this location a KathySpot.";
											 html += "<br/>&nbsp;- " + linkZoom(point.x,point.y) + " to this location.";
											 html += "</tr></table>";
	
											 html += "</div>";

											 html += htmlEnd();
											 

											 openInfoWindowHtml(marker, html, true);
											 
											 if (SHOW_MINIMAP) {
												 var minimap = new GMap(document.getElementById(whichmini));
												 var newZoom = minimap.getZoomLevel()-6;
												 if (newZoom <= 0) newZoom = 2;
												 minimap.centerAndZoom(point,newZoom);
												 count++;
											 }
										 });
}

function htmlStartDOM(id,anyWidth) {
	var div = $n('div');
	div.style.padding = "2px";
	div.style.whiteSpace = "nowrap";
	var img = $n('img',div);
	img.alt = "main-small";
	img.src = "images/kathymaps_logo-small.jpg";
	img.border = "0px";
	div.appendChild($n('br'));
	return div;
}

function htmlStart(id,anyWidth) {
	var s = "<div id=\"mainInfoDiv" + id + "\" style=\"padding: 2px; white-space: nowrap; ";
	if (!anyWidth) s += "min-width: 400px";
	s += "\">";
	s += "<img alt='main-small' src='images/kathymaps_logo-small.jpg' border=0><br/>";
	return s;
}

function htmlEnd() {
	var s = "";
	/*s += "<div style=\"font-size: 7pt;\">";
	s += "<a href=\"javascript:window.close();\">close</a>";
	s += "</div>";
	*/
	s += "</div>";
	return s;
}

function kmapsMain() {
	//
	// first check if we are returning and have left
	// session variables around
	//

	var center = '';
	var zoom;

	var lastLon = _SESSION['lon'];
	var lastLat = _SESSION['lat'];
	var lastZoom = _SESSION['zoom'];
	if (lastLon && lastLat) center = newPoint(lastLon,lastLat);
	zoom = lastZoom ? lastZoom : defaultZoom();
	//zoom = defaultZoom();

	kmapsRealMain(center, zoom, false,"","","","","");
}

// addressType = url | address
function kmapsRealMain(center,zoom,addPointAutomatically,
											 address,addressType,title,desc,easterEgg) {
	try {
		kmapsRealMainHelper(center,zoom,addPointAutomatically,
												address,addressType,title,desc,easterEgg)
			} catch (e) {}
}

function kmapsRealMainHelper(center,zoom,addPointAutomatically,
														 address,addressType,title,desc,easterEgg) {
	
	if (!center) center = defaultCenter();
	//
	// set up the base icon
	//
	baseIcon = new GIcon();

	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";

	baseIcon.iconSize = new GSize(ICON_WIDTH, ICON_HEIGHT);
	baseIcon.shadowSize = new GSize(SHADOW_WIDTH, SHADOW_HEIGHT);

	baseIcon.iconAnchor = newPoint(9, 34);
	baseIcon.infoWindowAnchor = newPoint(9, 2);
	baseIcon.infoShadowAnchor = newPoint(18, 25);
	//
	// This will holds the markers on the map
	//
	ids2markers = new Array();
	//
	// This will hold the markers that need updating before creating html
	ids2html = new Array();
	//
	// Capture key presses
	//
	captureKeyPresses();
	//
	// Init the map
	//
	map = new GMap($("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());

	//
	// for debugging
	//
	numAdded=0;
	numRemoved=0;
	if (DEBUG) {
		debug('addedspan',0);
		debug('stayedspan',0);
		debug('deletedspan',0);
		debug('newonesspan',0);
		debug('totalspan',0);
		debug('numaddedspan',numAdded);
		debug('numremovedspan',numRemoved);
	}
	//
	// map clicks
	//
	GEvent.addListener(map, 'click', click);
	//GEvent.addListener(map, 'dblclick', addPoint);
	//
	// map moves
	//
	GEvent.addListener(map, 'moveend', processNewMapMovement);
	//
	// map zooms
	//
	GEvent.addListener(map, 'moveend', processNewMapZoom);
	//
	// go to the center, if center.x or center.y is really zero reset it
	//
	if (!center || center == '' || center.x==0 || center.y==0) {
		center = defaultCenter();
	}
	if (zoom <= 0) zoom = 4;
	map.centerAndZoom(center, zoom);
	saveState();
	//
	// Are we adding a point initially?
	//
	if (addPointAutomatically) addPointByForce(null, center,address,addressType,title,desc);
	//
	// Create the initial points
	//
	processMapMovement(getZoomLevel());
	//
	// easter egg
	//
	processEasterEgg(easterEgg);
}

function defaultCenter() {
	var p;
	if (user_start_lon && user_start_lat) {
		try {
			var lon = str2coord(user_start_lon);
			var lat = str2coord(user_start_lat);
			p = newPoint(lon,lat);
		} catch (e) {handle(e);}
	} else {
		p = newPoint(-94.926791,36.863917);
	}
	return p;
}

// delcare them so i don't get an error when we aren't logged in
var user_start_lon;
var user_start_lat;
function defaultZoom() {
	return (user_start_lon && user_start_lat ? 5 : 6);
}

/****************************** EASTER EGGS ******************************/

var EGGS = ['eva'];
function isEasterEgg(s) {
	for (var i=0; i<EGGS.length; i++) {
		if (s == EGGS[i]) return true;
	}
	return false;
}

function processEasterEgg(easterEgg) {
	if (easterEgg == "") return false;
	//
	// process the easter egg
	//
	var ZOOM = 4;
	if (easterEgg != "") {		
		var p = getEasterEggCenter(easterEgg);
		var h = getEasterEggHTML(easterEgg);
		if (p!=0 && h!='') {
			map.openInfoWindowHtml(p,h);
			return true;
		}
	}
	return false;
}

function getEasterEggCenter(easterEgg) {
	if (easterEgg == 'eva') {
		return newPoint(-73.82486343383789, 40.758505337427664);
	}
	return 0;
}

function getEasterEggHTML(easterEgg) {
	if (easterEgg == 'eva') {
		var html = htmlStart();
		html += addTitle("Baby bear!!!", "");
		html += "<center>";
		html += image("smiley.jpg");
		html += "</center>";
		html += htmlEnd();
		return html;
	}
	return "";
}

function jumpTo(link) {

	if (map) {
		
		var zoom = getZoomLevel();
		var lon = getCenterLatLng().x;
		var lat = getCenterLatLng().y;
		
		function processSaveSession(res) {
			document.location.href = link;
		}
		
		var reqURL = fullPath('do_session_store_js.php') +
			"?spud=trooper" +
			"&zoom=" + zoom +
			"&lon=" + lon +
			"&lat=" + lat +
			"";
		try {
			ajaxXML(reqURL, processSaveSession);
		} catch (e) {}
	}
	document.location.href = link;
}


