/*
 * © 2006 MyOutdoors.net
 */
var map;
var mgr;
var journal;
var connObj;
var callback;
var args = [];
var polyline;
var points;
var flags;
var mapMode = "nav";
var flagType = "waypoint";
var saved = true;
var dragMarker;
var zoomMarker;
var dlg;
var entryCount = 0;
var tt; // tooltip
var dirty;
var pendingSave = false;
var deleteIDs = [];
var noWarnDel = false;
var noWarnPub = false;
var timeout = 0;
var elevDown = false;
document.oncontextmenu = function (evt) {
  return false;
};

var baseIcon = new GIcon();
baseIcon.image = "images/flagBlue.png";
//baseIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
baseIcon.iconSize = new GSize(23, 29);
//baseIcon.shadowSize = new GSize(23, 29);
baseIcon.iconAnchor = new GPoint(0, 29);
baseIcon.infoWindowAnchor = new GPoint(5, 1);

var noMarkIcon = new GIcon();
noMarkIcon.image = "images/invisible_marker.png";
noMarkIcon.iconSize = new GSize(9,9);
noMarkIcon.iconAnchor = new GPoint(5,5);
noMarkIcon.infoWindowAnchor = new GPoint(5, 1);
var warnIcon = new GIcon();
warnIcon.image = "images/warn_16.png";
warnIcon.iconSize = new GSize(16,16);
warnIcon.iconAnchor = new GPoint(8,8);
warnIcon.infoWindowAnchor = new GPoint(5, 1);
var infoIcon = new GIcon();
infoIcon.image = "images/info16_1.gif";
infoIcon.iconSize = new GSize(16,16);
infoIcon.iconAnchor = new GPoint(8,8);
infoIcon.infoWindowAnchor = new GPoint(5, 1);
var campIcon = new GIcon();
campIcon.image = "images/campground_16.png";
campIcon.iconSize = new GSize(16,16);
campIcon.iconAnchor = new GPoint(8,8);
campIcon.infoWindowAnchor = new GPoint(5, 1);

var invIcon = new GIcon();
invIcon.image = "images/blank.png";
invIcon.iconSize = new GSize(6,6);
invIcon.iconAnchor = new GPoint(3,3);
invIcon.infoWindowAnchor = new GPoint(5, 1);

var greenIcon = new GIcon(baseIcon);
greenIcon.image = "images/flagGreen.png";
var redIcon = new GIcon(baseIcon);
redIcon.image = "images/flagRed.png";
var yellowIcon = new GIcon(baseIcon);
yellowIcon.image = "images/flagYellow.png";

function initDisplay()
{
	initMap();
	if (journalid > 0){
		//loadJournal(journalid);
		var text = $("JournalJSON").innerHTML.replace(/\r|\n/g, '');
		journal = text.parseJSON();
		if (journal && journal.id > 0){
			switch(journal.maptype)
			{
				case "M": map.setMapType(G_NORMAL_MAP);break;
				case "H": map.setMapType(G_HYBRID_MAP);break;
				case "S": map.setMapType(G_SATELLITE_MAP);break;
			}
			mapJournal();
		}else
		{
			loadJournal(journalid);
		}
	}
}
function initEdit(){
	initMap();
	if (journalid > 0){
		loadJournal(journalid);
	}else
	{
		journal = {id:"0",title:"New Journal",category:"1",categoryname:"none",description:"", status:"1",parentid:"0", type:"journal",entries:[]};	
		mapJournal();
		//$("JournalTitle").innerHTML = journal.title;
		//$("JournalCategory").innerHTML = journal.categoryname;
		alert2("Add points by selecting 'Add Points' and clicking on the map. You can add, delete, insert, edit, change icons, drag icons, find addresses, import data and more all from various buttons on this page.", "Create New Journal", function(){editEntry(-1);});
		//editEntry(-1);
	}
	setMode("nav");
}
function editUnload(){if (!saved){return "There are unsaved edits, if you leave this page your edits will be lost";}}
function MOUnload()
{
	journal = null;
	flags = null;
	points = null;
	mgr = null;
	map = null;
	polyline = null;
	dlg = null;
	dragMarker = null;
	zoomMarker  = null;
	args = null;
	callback = null;
	connObj = null;
}
function initMap()
{
	if (edit === true){
		map = new GMap2($("MapWindow"), {draggableCursor: 'crosshair'});
		map.addControl(new GLargeMapControl ());
	}else{
		map = new GMap2($("MapWindow"));
		map.addControl(new GLargeMapControl ());
	}
	map.setCenter(new GLatLng(60.044437, -95.84375), 3);
	//map.setCenter(new GLatLng(45.044437, -95.84375), 3);
	map.enableContinuousZoom(); 
	map.enableDoubleClickZoom();
	map.addControl(new GOverviewMapControl());
	map.addControl(new GMapTypeControl());
	map.setMapType(G_NORMAL_MAP);
	resizeMap();
	map.checkResize();
	//add on custom map controls
	if (edit === true){
		map.addControl(new ToolsControl());
		map.addControl(new TopControl());
		map.addControl(new FlagTypeControl());
		GEvent.addListener(map, "click", onMapClick);
		//GEvent.addListener(map, "zoomend", zoomEnd);
	}
	mgr = new GMarkerManager(map, {trackMarkers: true});
}
function zoomEnd(){
	//redrawPolyline();
}
function newJournal()
{
	alert("new Journal");
}
var loadJournalComplete = function (o)
{
	var text = o.responseText.replace(/\r|\n/g, '');
	journal = text.parseJSON();
	switch(journal.maptype)
	{
		case "M": map.setMapType(G_NORMAL_MAP);break;
		case "H": map.setMapType(G_HYBRID_MAP);break;
		case "S": map.setMapType(G_SATELLITE_MAP);break;
	}
	mapJournal();
	if (edit === true){
		$("JournalCategorySelect").selectedIndex = parseInt(journal.category)-1;
		if (journal.status == "2")
		{
			$("PublishJournal").innerHTML = "Unpublish Journal";
		}
	}
};
function loadJournal(id)
{
	callback = {
		success:loadJournalComplete,
		failure:responseFailure,
		argument:args 
	};
	connObj = $C.asyncRequest("POST", LOAD_JOURNAL_URL, callback, "id=" + id);
}
var saveJournalComplete = function(o)
{
	hideDlg();	
	try
	{
	var res = o.responseText.parseJSON();
	if (res.status == "not_logged_in")
	{
		loginCreateUser("both");
	}else
	{
		for(var i = 0; i < dirty.length; i++){
			journal.entries[dirty[i].journalindex].dirty = false;
			journal.entries[dirty[i].journalindex].id = res.ids[i];
		}
		dirty = [];
		if (journalid > 0){
			alert2("Journal Saved");
		}else 
		{
			pendingSave = false;
			saved = true;
			document.location = document.location + "?id=" + journal.id;
		}
	}
	pendingSave = false;
	saved = true;
	}
	catch (e) {
		//GLog.write(o.responseText);
		//GLog.write(e.message);
	}
};

function deletePoints()
{
	if (deleteIDs.length > 0){
	callback = {
		success:null,
		failure:responseFailure,
		argument:args 
	};
	connObj = $C.asyncRequest("POST", DELETE_POINT_URL, callback, "ids=" + escape(json.ObjToJSONString(deleteIDs)));
	deleteIDs = [];
	}
}
function saveParentComplete(o)
{
	var res = o.responseText.parseJSON();
	if (res.status == "success")
	{
		journal.id = res.ids[0];
		for(var i = 0; i < journal.entries.length; i++){
			journal.entries[i].parentid = journal.id;
		}
		timeout = 0;
		saveEntries();
	}else
	{
		if (res.status == "not_logged_in")
		{
			loginCreateUser("both");
		}
		else
		{
			//GLog.write("ERROR" + o.responseText);
		}
	}
}
function saveEntries()
{
	callback = {
		success:saveJournalComplete,
		failure:responseFailure,
		argument:args 
	};
	dirty = [];
	var indexes = [];
	for(var i = 0; i < journal.entries.length; i++)
	{
		if (journal.entries[i].dirtyElev === true && timeout < 10000){
			setTimeout(function(){timeout = timeout+1000;saveEntries();}, 1000);
			return;	
		}
		journal.entries[i].journalindex = i;
		if (journal.entries[i].dirty){dirty.push(journal.entries[i]);}
		if (journal.entries[i].id > 0){indexes.push([i,journal.entries[i].id]);}
	}
	connObj = $C.asyncRequest("POST", SAVE_JOURNAL_URL, callback, "journal=" + escape(json.ObjToJSONString(dirty)) +
		"&indexes=" + escape(json.ObjToJSONString(indexes)));
}
function pubAndSave(){
	setStatus("2");
	doSave();
}
function doSave(){
	if ($("warnpub") && $("warnpub").checked){noWarnPub = true;}
	working();
	pendingSave = true;
	callback = {
		success:saveParentComplete,
		failure:responseFailure,
		argument:args 
	};
	var now = new Date();
	var c = map.getCenter();
	var mtype = map.getCurrentMapType().getName().charAt(0);
	var jrn = [{id:journal.id,userid:userid,title: journal.title,category:journal.category,description: journal.description, status:journal.status,parentid:"0", type:"journal",latitude:c.lat(), longitude:c.lng(), zoomlevel: map.getZoom(), elevation:0, maptype : mtype, imagefile: journal.imagefile}];
	connObj = $C.asyncRequest("POST", SAVE_JOURNAL_URL, callback, "journal=" + escape(json.ObjToJSONString(jrn)));
	deletePoints();
}
function saveJournal()
{
	if (journal.status == 1 && !noWarnPub){
		
		confirm2("Would you like to publish this journal?<br /><br /><center><input type=checkbox id=warnpub />&nbsp;Don't show me this again.</center>", pubAndSave, doSave, "Save and Publish?");
		return;
	}
	doSave();
}
function setStatus()
{
	switch (journal.status)
	{
		case "2":$("PublishJournal").innerHTML = "Publish Journal";
				journal.status = "1";break;
		case "1":$("PublishJournal").innerHTML = "Unpublish Journal";
				journal.status = "2";break;
	}
	saved = false;
}
function mapJournal()
{
	if (journal.latitude){try{map.setCenter(new GLatLng(journal.latitude, journal.longitude), parseInt(journal.zoomlevel));}catch(e){}}
	points = [];
	flags = [];
	entryCount = 0;
	var list = $("JournalEntryViewer");
	var lc = "";
	if (list !== null){
		lc = lc + makeEntryDisplay(journal, "text");
		//list.appendChild(makeEntryDisplay(journal));
	}
	for(var i = 0; i < journal.entries.length; i++)
	{
		var ent = journal.entries[i];
		var p = new GLatLng(parseFloat(ent.latitude), parseFloat(ent.longitude));
		var m;
		switch (ent.type)
		{
			case "waypoint":xIcon = baseIcon;break;
			case "nomark":if (edit === true){xIcon = noMarkIcon;}else {xIcon = invIcon;}break;
			case "warn" : xIcon = warnIcon;break;
			case "info" : xIcon = infoIcon;break;
			case "camp" : xIcon = campIcon;break;
		}
		if (i === 0){xIcon = greenIcon;ent.distance = 0.0;}
		else {
			ent.distance = journal.entries[i-1].distance + p.distanceFrom(points[i-1]);
		}
		if (i == journal.entries.length-1 && edit != true){xIcon = redIcon;}
		m = new GMarker(p, {icon:xIcon, draggable: edit});
		 
		m.title = KMtoMile(ent.distance / 1000.0) + " Mi";
		m.journalindex = i;
		GEvent.bind(m, "mouseover", m, onMarkerOver);
		GEvent.bind(m, "mouseout", m, onMarkerOut);
		if (edit === true){
			GEvent.bind(m, "drag", m, onMarkerDrag);
			GEvent.bind(m, "dragend", m, onMarkerDragEnd);
			m.enableDragging();	
		}else
		{
			GEvent.bind(m, "click", m, onMarkerClick);
		}
		points.push(p);
		flags.push(m);
		if (list){
			if (edit){
				lc = lc + makeEntryDisplay(ent, "text");
				entryCount = entryCount+1;
				//list.appendChild(makeEntryDisplay(ent));
			}else
			{
				if (ent.title.length > 1 || ent.description.length > 0 || ent.imagefile.length > 0){
					entryCount = entryCount+1;
					lc = lc + makeEntryDisplay(ent, "text");
					//list.appendChild(makeEntryDisplay(ent));
				}
			}		
			list.innerHTML = lc;
		}
		journal.entries[i] = ent;	
	}
	if (points.length > 0){
		redrawPolyline();
		if ($("Distance")){$("Distance").innerHTML = "Distance: " + KMtoMile(journal.entries[journal.entries.length-1].distance / 1000.0).toFixed(2) + " miles";}
		$("JournalCategory").innerHTML = journal.categoryname;
		$("JournalCategory").href = "index.php?sport=" + journal.category;
		$("JournalTitle").innerHTML = journal.title;
		$("JournalTitle").href = "entry.php?id=" + journal.id;
		$("JournalAuthor").innerHTML = journal.username;
		$("JournalAuthor").href = "user.php?user=" + journal.userid;
		$("JournalDate").innerHTML = getJSDate(journal.creation_date).toLocaleString();
		if ($("Nearby")) { $("Nearby").href = "location.php?lat=" + journal.latitude + "&lng=" + journal.longitude + "&distance=150"; }
		if (journal.userid == userid && $("EditJournalButton")){$("EditJournalButton").style.display = "";}
	}
	var dms = [];
	for(var j = 0; j < flags.length; j++){
		var ent = journal.entries[j];
		if (ent.type != "nomark" || edit === true || ent.title.length > 1 || ent.description.length > 0 || ent.imagefile.length > 0){
		//map.addOverlay(flags[j]);
		dms.push(flags[j]);
		}
	}
	mgr.addMarkers(dms, 0);
	mgr.refresh();
}
function getJSDate(date) {
	datestring = date;
	daystring = date.substring(0, 10);
	timestring = date.substring(11, 19);
	
	year = (daystring.substring(0, 4));
	month = (daystring.substring(5, 7));
	day = (daystring.substring(8, 10));
	
	hour = (timestring.substring(0, 2));
	minute = (timestring.substring(3, 5));
	second = (timestring.substring(6, 8));
	
	thedate = new Date();
	thedate.setTime(Date.parse(month + "/" + day + "/" + year + " " + hour + ":" + minute + ":" + second));
	return thedate; 
}
function onMarkerOver()
{
	onMarkerOut();
	var xy = $E.getXY($E.getEvent());
	/*var cxy = map.fromLatLngToDivPixel(map.getCenter());
	var dxy = map.fromLatLngToDivPixel(this.getPoint());
	var mwh = map.getSize();
	var xyp = new GPoint(dxy.x-cxy.x+(mwh.width) , dxy.y-cxy.y+(mwh.height));
	var xy = [x.x, y.y];*/
	var distance = KMtoMile(journal.entries[this.journalindex].distance / 1000.0); 
	tt = new $W.Overlay("tooltip", {x : xy[0]+10, y : xy[1]+10});
	tt.setBody("<div class=\"button\">" + distance.toFixed(2) + " mi.</div>");
	tt.render(document.body);
	tt.show();
}
function onMarkerOut()
{
	if (tt){tt.hide();}
}
function clickMarker(i)
{
	if (i >= 0){GEvent.trigger(flags[i], "click");}
	else{popupEntryrInfo(i);}
}
function popupEntryrInfo(i)
{
	var e;
	if (i >= 0){e = journal.entries[parseInt(i)];}
	else{ e = journal;}
	hideDlg();
	dlg = new $W.Panel("entryinfo", {modal:true,width:"500px",draggable:true,constraintoviewport:true});
	var h = "<div style=\"overflow:auto;height:200px;\">";
	if (e.imagefile && e.imagefile.length > 0){
		h = h + "<a class=\"imglink\" href=\"IMGSRC\" target=\"_blank\" ><img src=\"IMGSRC\" width=150 /></a>";
		h = h.replace(/IMGSRC/g, e.imagefile);
	}
	h = h + "DESCR</div>";
	h = h.replace("DESCR", e.description);
	dlg.setBody(h);
	dlg.setHeader(e.title);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function onMarkerClick()
{
	var entry = journal.entries[parseInt(this.journalindex)];
	var d = entry.description;
	if (!d || d.length === 0){d = "no description";}
	var descr = "<div style=\"overflow:auto;height:200px;\">";
	if (entry.imagefile && entry.imagefile.length > 0){
		descr = descr + "<a class=\"imglink\" href=\"IMGSRC\" target=\"_blank\" ><img src=\"IMGSRC\" width=150 /></a>";
		descr = descr.replace(/IMGSRC/g, entry.imagefile);
	}
	descr = descr + "<b>TITLE</b><br>DESCR</div>";
	descr = descr.replace("DESCR", d);
	descr = descr.replace("TITLE", entry.title);
	var tab1 = new GInfoWindowTab((parseInt(this.journalindex)+1), descr);
	var tab2 = new GInfoWindowTab("Lat,Lng", "<table><tr><td>Latitude:&nbsp;</td><td>" + this.getPoint().lat() + "</td></tr><tr><td>Longitude:&nbsp;</td><td>" + this.getPoint().lng() + "</td></tr><tr><td>Elevation:&nbsp;</td><td>" + parseInt(entry.elevation) + " ft</td></tr></table>");
	var infoTabs = [tab1, tab2];
	this.openInfoWindowTabsHtml(infoTabs, {maxWidth:350});
}
function setCat()
{
	var s = $("JournalCategorySelect");
	journal.category = s.options[s.selectedIndex].value;
}
function KMtoMile(km)
{
    return parseFloat(km) / 1.609;
}
function onMarkerDrag()
{
	points[this.journalindex] = this.getPoint();
	//map.removeOverlay(polyline);
	//polyline = new GPolyline(points, "#FE0094", 6);
	//map.addOverlay(polyline);
}
function onMarkerDragEnd()
{
	journal.entries[this.journalindex].longitude = this.getPoint().lng();
	journal.entries[this.journalindex].latitude = this.getPoint().lat();
	journal.entries[this.journalindex].dirty = "true";
	points[this.journalindex] = this.getPoint();
	redrawPolyline();
	getElevation(this.journalindex, this.getPoint().lat(), this.getPoint().lng()); 
	saved = false;
	calculateDistances();
}
function onMapClick(overlay, point)
{
	if (overlay){
		switch(mapMode)
		{
			case "nav":
				editEntry(overlay.journalindex);
				break;
			case "addpoint":
				editEntry(overlay.journalindex);
				break;
			case "delpoint":
				dragMarker = overlay;
				if (!noWarnDel){
					confirm2("Delete this point?<br /><br /><center><input type=checkbox id=warndelete />&nbsp;Don't show me this again.</center>", deletePoint, hideDlg, "Warning!");
				}
				else{deletePoint();}
				break;
			case "inspoint":
				dragMarker = overlay;
				insertPoint();
		}
	}
	else if (point){
		switch(mapMode)
		{
			case "nav":break;
			case "addpoint":
				addPoint(point);
				break;
		}
	}
}
function deleteJournal(){
	if (confirm("Are you sure you want to delete this journal?\n This operation cannot be reversed."))
	{
	callback = {
		success:deleteJournalComplete,
		failure:responseFailure,
		argument:args 
	};
	connObj = $C.asyncRequest("POST", DELETE_JOURNAL_URL, callback, "id=" + journal.id);
	}
}
function deleteJournalComplete(o){
	var r = o.responseText.parseJSON();
	if (r.status == "success"){
		alert("Journal Deleted");
		document.location = "user.php";
	}else
	{
		alert2("Failed to delete journal");
	}
}
function deletePoint()
{
	m = dragMarker;
	if ($("warndelete").checked){noWarnDel = true;}
	hideDlg();
	if (journal.entries[m.journalindex].id > 0){deleteIDs.push(journal.entries[m.journalindex].id);}
	points.splice(m.journalindex,1);
	journal.entries.splice(m.journalindex, 1);
	flags.splice(m.journalindex, 1);
	map.removeOverlay(m);
	redrawPolyline();
	//run through journal entries and markers to update their journal indexes
	for (var i = 0; i < flags.length; i++)
	{
		flags[i].journalindex = i;
		journal.entries[i].journalindex = i;
	}
	saved = false;
	redrawIndex();
}
function redrawPolyline(){
	if (polyline){
		map.removeOverlay(polyline);
	}
	if (points && points.length > 0){
		polyline = new GPolyline(points, "#FE0094", 6);
		map.addOverlay(polyline);
	}
}
function importGPX()
{
	hideDlg();
	dlg = new $W.Panel("gpx", {modal:true,width:"400px", height:"200px",draggable:true,constraintoviewport:true});
	var html = "GPX import is experimental at this point. We are still working out the kinks. We decided to make it available in this limited form because it is such a useful function.... when it works.<br /><br />Enter GPX file:<iframe src=\"ws/parseGPX.php\" class=\"importGPX\"></iframe>";
	dlg.setBody(html);
	dlg.setHeader("Import Data");
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function addGPXdata(data)
{
	//hideDlg();
	setFlagType("nomark");
	map.removeOverlay(polyline);
	var d = eval(data);
	var list = $CE("div");
	var iterate = 1;
	if (d.length > 200){iterate = 2;}
	if (d.length > 300){iterate = 3;}
	if (d.length > 400){iterate = 4;}
	if (d.length > 500){iterate = 5;}
	for (var i = 0; i < d.length; i = i + iterate)
	{
		var p = new GLatLng(d[i].lat, d[i].lng);
		var m = new GMarker(p, {icon:noMarkIcon, draggable: true});
		map.addOverlay(m);
		m.journalindex = journal.entries.length;
		GEvent.bind(m, "drag", m, onMarkerDrag);
		GEvent.bind(m, "mouseover", m, onMarkerOver);
		GEvent.bind(m, "mouseout", m, onMarkerOut);
		GEvent.bind(m, "dragend", m, onMarkerDragEnd);
		m.enableDragging();
		flags.push(m);
		list.appendChild(addEntryToJournal(p, true));
		saved = false;
		journal.entries[m.journalindex].elevation = parseInt(d[i].elev);
		points.push(p);
	}
	var jv = $("JournalEntryViewer");
	jv.appendChild(list);
	jv.scrollTop = jv.scrollHeight;
	redrawPolyline();
	hideDlg();
	map.setCenter(points[points.length-1], 13);
}
function getElevationComplete(o)
{
	var elev = o.responseText.parseJSON().elevation;
	journal.entries[parseInt(o.argument)].elevation = parseInt(elev);
	journal.entries[parseInt(o.argument)].dirtyElev = false;
}
function getElevationFailure(o)
{
	elevDown = true;
	journal.entries[parseInt(o.argument)].elevation = -999999;
	journal.entries[parseInt(o.argument)].dirtyElev = false;
}
function getElevation(index, lat, lng)
{
	args = [index];
	callback = {
		success:getElevationComplete,
		failure:getElevationFailure,
		argument:args,
		timeout:2000
	};
	var url = ELEV_URL + "?lng=" + lng + "&lat=" + lat;
	if (!elevDown){
		journal.entries[index].dirtyElev = true;
		connObj = $C.asyncRequest('GET', url, callback, null);
	}
}
function addPoint(point, elev)
{
	hideDlg();
	var m;
	switch (flagType)
	{
		case "waypoint" : m = new GMarker(point, {icon:baseIcon, draggable: true});break;
		case "nomark" : m = new GMarker(point, {icon:noMarkIcon, draggable: true});break;
		case "warn" : m = new GMarker(point, {icon:warnIcon, draggable: true});break;
		case "info" : m = new GMarker(point, {icon:infoIcon, draggable: true});break;
		case "camp" : m = new GMarker(point, {icon:campIcon, draggable: true});break;
	}
	map.addOverlay(m);
	m.journalindex = journal.entries.length;
	GEvent.bind(m, "drag", m, onMarkerDrag);
	GEvent.bind(m, "mouseover", m, onMarkerOver);
	GEvent.bind(m, "mouseout", m, onMarkerOut);
	GEvent.bind(m, "dragend", m, onMarkerDragEnd);
	m.enableDragging();
	points.push(point);
	flags.push(m);
	redrawPolyline();
	addEntryToJournal(point);
	saved = false;
	if (!elev)
	{
		getElevation(m.journalindex, point.lat(), point.lng());
	}else
	{
		journal.entries[m.journalindex].elevation = parseInt(elev);
	}
}
function insertPoint(){
	var d = dragMarker;
	if (d.journalindex < journal.entries.length-1)
	{
		var n = flags[d.journalindex+1];
		var la = (parseFloat(d.getPoint().lat()) + parseFloat(n.getPoint().lat()))/2.0;
		var lo = (parseFloat(d.getPoint().lng()) + parseFloat(n.getPoint().lng()))/2.0;
		var point = new GLatLng(la, lo);
		var m;
		switch (flagType)
		{
			case "waypoint" : m = new GMarker(point, {icon:baseIcon, draggable: true});break;
			case "nomark" : m = new GMarker(point, {icon:noMarkIcon, draggable: true});break;
			case "warn" : m = new GMarker(point, {icon:warnIcon, draggable: true});break;
			case "info" : m = new GMarker(point, {icon:infoIcon, draggable: true});break;
			case "camp" : m = new GMarker(point, {icon:campIcon, draggable: true});break;
		}
		m.journalindex = journal.entries.length;
		GEvent.bind(m, "drag", m, onMarkerDrag);
		GEvent.bind(m, "mouseover", m, onMarkerOver);
		GEvent.bind(m, "mouseout", m, onMarkerOut);
		GEvent.bind(m, "dragend", m, onMarkerDragEnd);
		m.enableDragging();
		points.splice(n.journalindex, 0, point);
		flags.splice(n.journalindex, 0, m);
		var now = new Date();
		var newEntry = {title : "-",category: journal.category, 
			description : "", creation_date : now.getTime(),parentid : journal.id, 
			type : flagType, latitude : point.lat(), longitude : point.lng(), zoomlevel : journal.zoomlevel,
			journalindex : 0, maptype : journal.maptype, imagefile : "", dirty:true, id:0, elevation:-999999};
		journal.entries.splice(n.journalindex, 0, newEntry);
		map.addOverlay(m);
		redrawPolyline();
		saved = false;
		for(var i = 0; i < journal.entries.length;i++){
			flags[i].journalindex = i;
			journal.entries[i].journalindex = i;
		}
		getElevation(m.journalindex, point.lat(), point.lng());
		redrawIndex();
		calculateDistances();
	}
}
function zoomToPoint(point, zoomLevel)
{
	hideDlg();
	var marker = new GMarker(point);
	map.panTo(point);
	map.addOverlay(marker);
}
function addEntryToJournal(point, noDisplay)
{
	var now = new Date();
	var newEntry = {title : "-",category: journal.category, 
		description : "", creation_date : now.getTime(),parentid : journal.id, 
		type : flagType, latitude : point.y, longitude : point.x, zoomlevel : journal.zoomlevel,
		journalindex : (journal.entries.length), maptype : journal.maptype, imagefile : "", elevation: -999999, dirty:true};
	if (journal.entries.length > 0){
		newEntry.distance = journal.entries[journal.entries.length-1].distance + point.distanceFrom(points[journal.entries.length-1]);
	}else {newEntry.distance = 0;}
	journal.entries.push(newEntry);
	var jv = $("JournalEntryViewer");
	if (noDisplay === true) {return makeEntryDisplay(newEntry);}
	jv.appendChild(makeEntryDisplay(newEntry));
	jv.scrollTop = jv.scrollHeight;
}
function calculateDistances(){
	for (var i = 0; i < journal.entries.length; i++){
		var e = journal.entries[i];
		if (i == 0){e.distance = 0.0;continue;}
		var pe = journal.entries[i-1];
		var p = new GLatLng(e.latitude, e.longitude);
		var pp = new GLatLng(pe.latitude, pe.longitude); 
		e.distance = pe.distance + p.distanceFrom(pp);
	}
}
function redrawIndex()
{
	entryCount = 0;
	var list = $("JournalEntryViewer");
	list.innerHTML = "";
	list.appendChild(makeEntryDisplay(journal));
	for(var i = 0; i < journal.entries.length; i++)
	{
		list.appendChild(makeEntryDisplay(journal.entries[i]));
	}
	$("JournalTitle").innerHTML = journal.title;
}
function makeEntryDisplay(entry, mode)
{
	var html = "<table width=99%><tr><td class=\"etitle\">TITLE</td><td align=right >IMGICON&nbsp;";
	if (edit){
		html = html + "<a style=\"cursor:pointer;\" onclick=\"editEntry(INDEX);\" ><img src=\"images/page_white_edit.png\" style=\"display:inline;padding-top:2px;\" /></a>";
	}else
	{
		html = html + "<a style=\"cursor:pointer;\" onclick=\"clickMarker(INDEX);\" ><img src=\"images/magnifier.png\" style=\"display:inline;padding-top:2px;\" /></a>";	
	}
	html = html + "</td></tr><tr><td colspan=2><div>TEXT</div></td></tr></table>";
	if (entry.type != "journal"){
		html = html.replace("TITLE", (entryCount) + ". " + entry.title);
		html = html.replace("INDEX", entry.journalindex);
	}else 
	{
		html = html.replace("TITLE", entry.title);
		html = html.replace("INDEX", "-1");
	}
	html = html.replace("TEXT", entry.description);
	var img = "";
	if (entry.imagefile && entry.imagefile.length > 0){img = "<img src=\"images/camera.png\" style=\"display:inline;\" />";}
	html = html.replace("IMGICON", img);
	if (mode && mode == "text")
	{
		return '<div class="entryDisplay">'+html+'</div>';
		entryCount++;
	}else{
		var div = $CE("div");
		div.innerHTML = html;
		div.className = "entryDisplay";
		entryCount++;
		return div;
	}
}

function showHelp(){
	callback = {
		success:showHelpComplete,
		failure:responseFailure,
		argument:args
	};
	connObj = $C.asyncRequest('GET', HELP_URL, callback, null);
}
function showHelpComplete(o)
{
	dlg = new $W.SimpleDialog("alert",{modal:true,width:"480px",draggable:false,fixedcenter:true}); 
	dlg.cfg.queueProperty("buttons", [{text:"OK", handler:hideDlg, isDefault:true}]);
	dlg.setBody(o.responseText);
	dlg.setHeader("Help");
	dlg.render(document.body);
	dlg.show();
}

function addMode(){mapMode = "addpoint";$("AddButton").className = "activeMode";}
function delMode(){mapMode = "delpoint";$("DelButton").className = "activeMode";}
function navMode(){mapMode = "nav";$("NavButton").className = "activeMode";}
function insMode(){mapMode = "inspoint";$("InsButton").className = "activeMode";}
function setMode(m){
	mapMode = m;
	var as = $GTN($("ToolsControl"), "a");
	for (var i = 0; i < as.length; i++)
	{
		as[i].className = "";
	}
	switch(m)
	{
		case "addpoint": $("AddButton").className = "activeMode";break;
		case "delpoint": $("DelButton").className = "activeMode";break;
		case "nav": $("NavButton").className = "activeMode";break;
		case "inspoint": $("InsButton").className = "activeMode";break;
	}
}
function setFlagType(t)
{
	if (mapMode == "nav"){setMode("addpoint");}
	flagType = t;
	var as = $GTN($("FlagTypec"), "a");
	for (var i = 0; i < as.length; i++)
	{
		as[i].className = "";
	}
	switch(t)
	{
		case "waypoint": $("flagTypeBlue").className = "flagTypeSelected";break;
		case "nomark": $("flagTypeBlank").className = "flagTypeSelected";break;
		case "warn": $("flagTypeWarn").className = "flagTypeSelected";break;
		case "info": $("flagTypeInfo").className = "flagTypeSelected";break;
		case "camp": $("flagTypeCamp").className = "flagTypeSelected";break;
	}
}

//custom map controlsfunction FlagTypeControl() {}
function FlagTypeControl() {}
FlagTypeControl.prototype = new GControl();
FlagTypeControl.prototype.initialize = function(map) {
  	var c = $CE("div");
	c.className = "flagTypeControl";
	c.setAttribute("id", "FlagTypec");
	var html = "Type<br /><a id=flagTypeBlue class=\"flagTypeSelected\" onclick=\"setFlagType('waypoint');\"><img src=\"images/flagBlue.png\" height=20 /></a><a id=flagTypeWarn onclick=\"setFlagType('warn');\"><img src=\"images/warn_16.png\" /></a><a id=flagTypeCamp onclick=\"setFlagType('camp');\"><img src=\"images/campground_16.png\" /></a><a id=flagTypeInfo onclick=\"setFlagType('info');\" ><img src=\"images/info16_1.gif\" /></a><a id=flagTypeBlank onclick=\"setFlagType('nomark');\" ><img src=\"images/invisible_marker.png\" /></a>";
	c.innerHTML = html;
 	map.getContainer().appendChild(c);
  	return c;
};
FlagTypeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(70, 7));
};
function ToolsControl() {}
ToolsControl.prototype = new GControl();
ToolsControl.prototype.initialize = function(map) {
  var c = $CE("div");
  c.className = "toolControl";
  c.setAttribute("id", "ToolsControl");
  var newJ = $CE("a");
  c.appendChild(newJ);
  newJ.appendChild($CTN("Save Journal"));
  GEvent.addDomListener(newJ, "click", saveJournal);
    
  newJ = $CE("a");
  c.appendChild(newJ);
  newJ.appendChild($CTN("Publish Journal"));
  newJ.setAttribute("id", "PublishJournal");
  GEvent.addDomListener(newJ, "click", setStatus);
    
  newJ = $CE("a");
  c.appendChild(newJ);
  newJ.appendChild($CTN("Delete Journal"));
  GEvent.addDomListener(newJ, "click", deleteJournal);
    
  newJ = $CE("a");
  c.appendChild(newJ);
  newJ.appendChild($CTN("Help"));
  GEvent.addDomListener(newJ, "click", showHelp);
  
  c.appendChild($CE("br"));
  
  d = $CE("div");
  
  d.innerHTML = "<a id=\"NavButton\" onclick=\"setMode('nav');\">Navigate Map</a><a id=\"AddButton\" onclick=\"setMode('addpoint');\">Add Points</a><a id=\"InsButton\" onclick=\"setMode('inspoint');\">Insert Points</a><a id=\"DelButton\" onclick=\"setMode('delpoint');\">Delete Points</a>";
  c.appendChild(d);
  
  map.getContainer().appendChild(c);
  return c;
};
ToolsControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(8, 40));
};
function TopControl() {}
TopControl.prototype = new GControl();
TopControl.prototype.initialize = function(map) {
  var c = $CE("div");
  c.className = "topControl";
  
  var newJ = $CE("a");
  c.appendChild(newJ);
  newJ.appendChild($CTN("Find Address"));
  GEvent.addDomListener(newJ, "click", findAddress);
    
  newJ = $CE("a");
  c.appendChild(newJ);
  newJ.appendChild($CTN("Import GPX"));
  GEvent.addDomListener(newJ, "click", importGPX);
  
  map.getContainer().appendChild(c);
  return c;
};
TopControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(120, 7));
};
/*
Utility functions
*/
var responseFailure = function(o){alert2("server error", "Error");};
var showResponse = function(o){GLog.write(o.responseText);};
function checkConnStatus(){alert(YAHOO.util.Connect.isCallInProgress(connObj));}
function resizeMap() {
    var offset = 0;
    offset = $D.getY($("MapWindow"));
    var windowHeight = $D.getViewportHeight();
    var windowWidth = $D.getViewportWidth();
    var height = windowHeight - offset;
	if (edit === true){height= height - 20;}else{height = height - 70;}
    if (height >= 0) {
        $("MapWindow").style.height = height + "px";
		if ($("JournalEntryViewer")){
	        $("JournalEntryViewer").style.height = (height-143) + "px";
		}
    }
	if (map){map.checkResize();}
}
function working()
{
	hideDlg();
	dlg = new $W.Panel("working", {modal:true,width:"150px",draggable:false,fixedcenter:true,underlay:"shadow"});
	var html = "<center><img src=\"images/indicator.gif\" /></center>";
	dlg.setBody(html);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function hideDlg(){if (dlg){dlg.hide();}}
function alert2(atext, atitle, callback)
{
	dlg = new $W.SimpleDialog("alert",{modal:true,width:"300px",draggable:false,fixedcenter:true, visible:false}); 
	dlg.cfg.queueProperty("icon",$W.SimpleDialog.ICON_INFO);
	if (callback)
	{
		dlg.cfg.queueProperty("buttons", [{text:"OK", handler:function(){hideDlg();callback();}, isDefault:true}]);
	}else{
		dlg.cfg.queueProperty("buttons", [{text:"OK", handler:hideDlg, isDefault:true}]);
	}
	dlg.setBody(atext);
	if (!atitle){atitle = "&nbsp;";}
	dlg.setHeader(atitle);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function confirm2(text, yescallback, nocallback, title)
{
	dlg = new $W.SimpleDialog("confirm",{modal:true,width:"20em",draggable:false,fixedcenter:true, visible:false}); 
	dlg.cfg.queueProperty("buttons", [{text:"YES", handler:yescallback, isDefault:true},{ text:"NO",handler:nocallback}]);
	dlg.cfg.queueProperty("icon",$W.SimpleDialog.ICON_BLOCK);
	dlg.setBody(text);
	if (!title){title = "&nbsp;";}
	dlg.setHeader(title);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function findAddress(){
	hideDlg();
	dlg = new $W.Panel("geocode", {modal:true,width:"400px",draggable:true,constraintoviewport:true, visible:false});
	var html = "<table width=100%><tr><td><input type=textbox id=geo_address />&nbsp;&nbsp;&nbsp;&nbsp;<a onclick=\"geocode();\">Search</a></td></tr></table></div>";
	dlg.setBody(html);
	dlg.setHeader("Enter Address");
	dlg.render(document.body);
	dlg.center();
	dlg.show();
	var el =  new $U.KeyListener("geo_address", {keys:[13]}, geocode);
	el.enable();
}
function geocode()
{
	var geocoder = new GClientGeocoder();
	geocoder.getLocations($("geo_address").value, geocodeComplete);
}
function geocodeComplete(res)
{
	hideDlg();
	dlg = new $W.Panel("search_results", {modal:true,width:"400px",draggable:true,constraintoviewport:true, visible:false});
	if (res.Status.code == "200")
	{
	var h = "<table>";
	var t = "<tr><td>[A]</td><td style=\"padding-left:4px;\" ><a onclick=\"zoomToPoint(new GLatLng('LAT','LNG'), ZLEVEL);\"><img src=\"images/magnifier.png\" /></a></td></tr>";
	for (var i = 0; i < res.Placemark.length; i++)
	{
		h = h + t.replace("[A]", res.Placemark[i].address);
		h =  h.replace(/LAT/g, res.Placemark[i].Point.coordinates[1]);
		h =  h.replace(/LNG/g, res.Placemark[i].Point.coordinates[0]);
		h =  h.replace(/ZLEVEL/g, res.Placemark[i].Point.coordinates[2]);
	}
	h = h + "</table>";
	dlg.setBody(h);
	}
	else
	{
		dlg.setBody("Sorry, I couldn't find anything for <b>" + res.name + "</b>&nbsp;<a onclick=\"findAddress()\" >Search Again</a>");
	}
	
	dlg.setHeader("Address Search Results");
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function viewElevation()
{
	hideDlg();
	dlg = new $W.Panel("Elevation", {modal:true,width:"700px",height:"400px",draggable:true,constraintoviewport:true,visible:false});
	var h = "<img src=\"images/elevation.php?id=" + journal.id + "\" />";
	dlg.setBody(h);
	dlg.setHeader("Elevation");
	dlg.render(document.body);
	dlg.center();
	dlg.show();
}
function editEntry(i)
{
	var j = journal;
	if (i >= 0){j = journal.entries[i];}
	var h = "<div id=editwaypoint_html ><table width=100% ><tr><td>Title:</td><td width=100% ><input type=text id=e_title /><br /></td></tr><tr><td>Description:</td><td><textarea id=e_desc ></textarea></td></tr><tr><td>Image URL (Optional):</td><td><input type=textbox id=e_image /><br /></td></tr><tr><td></td><td><a onclick=\"saveEdits();\" >Save</a></td></tr></table><input type=hidden id=e_index /></div>";
	dlg = new $W.Panel("edit_item", {modal:true,width:"500px",height:"410px",draggable:true,constraintoviewport:true,visible:false});
	
	dlg.setBody(h);
	dlg.setHeader("Edit");
	dlg.render(document.body);
	dlg.center();
	dlg.show();
	$("e_title").value = j.title;
	$("e_index").value = i;
	$("e_desc").value = j.description;
	if (j.imagefile){$("e_image").value = j.imagefile;}
}
function saveEdits()
{
	var i = parseInt($("e_index").value);
	if (i < 0){
		journal.title = $("e_title").value;
		journal.description = $("e_desc").value.replace(/\r|\n|\t/g, '');
		journal.imagefile = $("e_image").value;
	}
	else {
		journal.entries[i].title = $("e_title").value;
		journal.entries[i].description = $("e_desc").value.replace(/\r|\n|\t/g, '');
		journal.entries[i].imagefile = $("e_image").value;
		journal.entries[i].dirty = true;
	}
	saved = false;
	redrawIndex();
	hideDlg();
}
function loginCreateUser(type)
{
	hideDlg();
	if (!dlg || dlg.id != "logincreate"){
	dlg = new $W.Panel("logincreateuser", {visible:false,modal:true,width:"300px",draggable:true,constraintoviewport:true});
	var html = "";
	if (type == "login"){
		html = "<table width=100%><tr><td><label for=firstname>Username:</label></td><td><input type=textbox name=username id=username /><br /></td></tr><tr><td>Password:</td><td><input type=password name=password id=password /></td></tr><tr><td></td><td><input type=checkbox id=remember /> Remember Me</td></tr><tr><td></td><td style=\"padding-top:4px;\"><a onclick=\"login();\">Login</a></td></tr></table>";
	dlg.setBody(html);
	dlg.setHeader("Login");
	}else
	{
		html = "<table width=100%><tr><td><label for=firstname>Username:</label></td><td><input type=textbox name=username id=username /><br /></td></tr><tr><td>Password:</td><td><input type=password name=password id=password /></td></tr><tr><td></td><td><input type=checkbox id=remember /> Remember Me</td></tr><tr><td></td><td style=\"padding-top:4px;\"><a onclick=\"login();\">Login</a></td></tr><tr><td colspan=2><hr /><br /></td></tr><tr><td>Username:</td><td><input type=textbox name=newusername id=newusername /><br /></td></tr><tr><td>Email:</td><td><input type=textbox name=newemail id=newemail /><br /></td></tr><tr><td>Password:</td><td><input type=password name=newpassword id=newpassword /></td></tr><tr><td></td><td id=\"termsWarn\"><input type=checkbox id=agreeterms /> I agree to the <a href=\"terms.php\" target=_blank >terms and conditions</a></td></tr><tr><td></td><td style=\"padding-top:4px;\"><a onclick=\"createUser();\">Create User</a></td></tr><tr><td class=loginerror id=login_error colspan=2></td></tr></table>";
	dlg.setBody(html);
	dlg.setHeader("Login or Create User");
	}
	dlg.render(document.body);
	}
	dlg.center();
	dlg.show();
	var el =  new $U.KeyListener("password", {keys:[13]}, login);
	el.enable();
	el =  new $U.KeyListener("newpassword", {keys:[13]}, createUser);
	el.enable();
}
function createUser(){
	if ($("agreeterms").checked){
	if ($("newemail").value.length > 0){
	callback = {
		success:loginComplete,
		failure:responseFailure,
		argument:args 
	};
	connObj = $C.asyncRequest("POST", CREATE_USER_URL, callback, "username=" + $("newusername").value + "&password=" + $("newpassword").value + "&email=" + $("newemail").value);
	}else{
		$("login_error").innerHTML = "Please enter an email";
	}
	}
	else
	{
		$("termsWarn").style.backgroundColor = "red";
	}
}
function loginComplete(o)
{
	var res = o.responseText.parseJSON();
	if (res.auth)
	{
		$("SignIn").style.display = "none";
		$("SignOut").style.display = "";
		$("myjournals").style.display = "";
		dlg.hide();
		userid = res.userid;
		username = res.username;
		email = res.email;
		if (pendingSave === true)
		{
			saveJournal();
		}
		alert2("You have been logged in.", "Logged In");
	}
	else
	{
		$("login_error").innerHTML = o.responseText;
	}
}
function login(){
	callback = {
		success:loginComplete,
		failure:responseFailure,
		argument:args 
	};
	var rem = 0;
	if ($("remember").checked)
	{rem = 1;}
	connObj = $C.asyncRequest("POST", LOGIN_URL, callback, "username=" + $("username").value + "&password=" + $("password").value + "&remember=" + rem);
}
function logout(){
	callback = {
		success:null,
		failure:responseFailure,
		argument:args 
	};
	connObj = $C.asyncRequest("POST", LOGOUT_URL, callback, "");
	$("SignIn").style.display = "";
	$("SignOut").style.display = "none";
	$("myjournals").style.display = "none";
	alert2("You have been logged out.", "Logged Out");
}
function addComment(){
	if (userid > 0)
	{
		hideDlg();
		var h = "<table><tr><td vAlign=top >Comment:</td><td><textarea id=NewComment></textarea></td></tr><tr><td></td><td><a onclick=\"saveComment();\" >Save</a></td></tr></table>";
		dlg = new $W.Panel("addComment", {visible:false,width:"300px",draggable:true,constraintoviewport:true});
		dlg.setHeader("Add Comment");
		dlg.setBody(h);
		dlg.render(document.body);
		dlg.center();
		dlg.show();
	}else
	{
		loginCreateUser();
	}
}
function saveComment()
{
	working();
	callback = {
		success:saveCommentComplete,
		failure:responseFailure,
		argument:args 
	};
	var c = escape($("NewComment").value);
	connObj = $C.asyncRequest("POST", SAVE_COMMENT_URL, callback, "id="+journal.id + "&text=" + c);
		
}
function saveCommentComplete(o)
{
	hideDlg();
	var res = o.responseText.parseJSON();
	if (res.comment){
	var h = "<SPAN style=\"float: left;\"><A href=\"user.php?user=USERID\">AUTHOR</A> says:  </SPAN><SPAN style=\"float: right;\">TIMESTAMP</SPAN><BR/><SPAN style=\"padding-left: 20px;\">COMMENT</SPAN><HR/>";
	h = h.replace("USERID", res.authorid);
	h = h.replace("AUTHOR", res.author);
	h = h.replace("TIMESTAMP", unescape(res.time).replace(/\+/g, " "));
	h = h.replace("COMMENT", unescape(res.comment).replace(/\+/g, " "));
	var d = $CE("div");
	d.innerHTML = h;
	$("CommentsHeader").appendChild(d);
	}
	
}
function forgotPass()
{
	hideDlg();	
	dlg = new $W.Panel("forgotPass", {visible:false,width:"300px",draggable:true,constraintoviewport:true,modal:true});	
	var h = "<table><tr><td>Email:</td><input type=text id=resetemail name=email /></td></tr><tr><td></td><td><a onclick=\"resetPass();\">Reset Password</a></td></tr></table>";
	dlg.setHeader("Reset Password");
	dlg.setBody(h);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
		
}
function resetPass()
{
	working();
	callback = {
		success:resetPassComplete,
		failure:responseFailure,
		argument:args 
	};
	var c = escape($("resetemail").value);
	connObj = $C.asyncRequest("POST", RESET_PASS_URL, callback, "email=" + c);
}
function resetPassComplete(o){
	var r = o.responseText.parseJSON();
	if (r.status == "success")
	{
	hideDlg();	
	dlg = new $W.Panel("forgotPass", {visible:false,width:"300px",draggable:true,constraintoviewport:true,modal:true});	
	var h = "Your password has been reset and has been emailed to you. Please check your email.";
	dlg.setHeader("Reset Password");
	dlg.setBody(h);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
	}
}
function changePass()
{
	if (userid > 0){
	hideDlg();	
	dlg = new $W.Panel("changePass", {visible:false,width:"300px",draggable:true,constraintoviewport:true,modal:true});	
	var h = "<table><tr><td>Old Password:</td><td><input type=password id=oldpass name=email /></td></tr>";
	h = h + "<tr><td>New Password:</td><td><input type=password id=newpass name=email /></td></tr>";
	h = h + "<tr><td>Confirm Password:</td><td><input type=password id=confirmpass name=email /></td></tr>";
	h = h + "<tr><td></td><td><br /><a onclick=\"changePassRQ();\">Change Password</a></td></tr></table>";
	dlg.setHeader("Reset Password");
	dlg.setBody(h);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
	}else{loginCreateUser("both");}	
}
function changePassRQ()
{
	var a = escape($("oldpass").value);
	var b = escape($("newpass").value);
	var c = escape($("confirmpass").value);
	if (c != b){
		alert("passwords do not match");
		return;
	}
	working();
	callback = {
		success:changePassComplete,
		failure:responseFailure,
		argument:args 
	};
	connObj = $C.asyncRequest("POST", CHANGE_PASS_URL, callback, "old=" + a + "&new=" + b);
}
function changePassComplete(o){
	var r = o.responseText.parseJSON();
	if (r.status == "success")
	{
	hideDlg();	
	dlg = new $W.Panel("changePass", {visible:false,width:"300px",draggable:true,constraintoviewport:true,modal:true});	
	var h = "Your password has been changed.";
	dlg.setHeader("Change Password");
	dlg.setBody(h);
	dlg.render(document.body);
	dlg.center();
	dlg.show();
	}else
	{
		alert(r.status);
	}
}

function displayJournalHelp() {
	alert2('The main journal entry section contains high-level information about the journal entry being displayed.  Each element other than the date is clickable.<br><br><b>Header Links</b><br>Clicking on the title will take you to a separate page where you can view details about the journal entry, including individual waypoints.  Clicking on the activity will take you to a separate page where you can view journal entries of the same type.  Clicking on the username will take you to a separate page where you can view all journal entries for that user.<br><br><b>Footer Links</b><br>Clicking on the comments link will also take you to a separate page containing the journal entry details.  Clicking on either the sparkline or the elevation link will display a pop-up containing a graph of the elevation data for the journal entry.', 'Journal Display Help');
}

function displayTopJournalsHelp() {
	alert2('Clicking on the journal entry link will take you to a separate detail page for the journal entry.<br><br>The parentheses after the journal entry link indicate the number of views for the journal entry.', 'Top Journal Entries Help');
}

function displayRecentJournalsHelp() {
	alert2('Clicking on the journal entry link will take you to a separate detail page for the journal entry.<br><br>The parentheses after the journal entry link indicate first the amount of time since the journal entry was created, and second the number of views for the journal entry.  For the amount of time, abbreviations are used as follows: s for seconds; m for minutes; h for hours; d for days; and mo for months.', 'Recent Journal Entries Help');

}

function displaySearchHelp() {
	alert2('You can use the search by entering your search criteria in the text box and pressing enter or clicking on the search button.  You will then be taken to a separate page showing the matching journal entries for your search.', 'Search Help');
}

function displaySearchPageHelp() {
	alert2('You can use the search by entering your search criteria in the text box and pressing enter or clicking on the search button.  Optionally, you may also refine your search based on a particular activity by using the dropdown box.<br><br>Search results will be dynamically displayed below the text box, allowing you to navigate among the results.  You may view a particular journal entry by clicking on the title.', 'Search Help');
}

function displayLocationHelp() {
	alert2('You can user the search by entering the location you wish to search for in the text box and pressing enter or clicking on the search button.  You will then be taken to a separate page showing the matching journal entries for your search.<br><br>Currently, the location search on the Browse page uses a default distance of 15 miles.  You can change this value on the search results page.', 'Location Search Help');
}

function displayLocationPageHelp() {
	alert2('You can use the search by entering the location you wish to search for in the text box and pressing enter or clicking on the search button.  You will then be taken to a separate page showing the matching journal entries for your search.<br><br>You may enter partial addresses in the text box, such as a zip code, a city, a state, etc.  You can even enter latitude and longitude by separating them with a comma (latitude first).<br><br>Optionally, you may also refine your search based on a particular activity by using the activity dropdown box, and specify the radius to search using the distance dropdown box.<br><br>Search results will be dynamically displayed below the text box, allowing you to navigate among the results.  You may view a particular journal entry by clicking on the title.', 'Location Search Help');
}

function displayBrowseHelp() {
	alert2('Clicking on the link for a particular activity will take you to a separate page where you can view all journal entries for that activity.', 'Browse by Activity Help');
}

function displayRSSHelp() {
	alert2('The main RSS Feed provides the ten most recent journal entries that have been created on MyOutdoors.net.  For individual activity RSS Feeds, see the links at the bottom of the page.', 'RSS Feed Help');
}

function displayRSSBySportHelp() {
	alert2('Each individual activity link provides the ten most recent journal entries that have been created for that particular activity.', 'RSS Feeds by Sport Help');
}

function displaySupportHelp() {
	alert2('The support page allows you to change your password or retrieve a new password in case you have lost yours using the appropriate links.  You can also contact us at <a href=\'mailto:myoutdoors@myoutdoors.net\'>myoutdoors@myoutdoors.net</a> if you should have any other problems.', 'Support Help');
}
function displayDownloadHelp() {
	alert2('Download GPX files to upload to your portable GPS unit or mapping software.<br /><br />Download KML files to view in <a href=\"http://earth.google.com\" target=_blank >Google Earth</a>', 'GPX');
}