// jhm_pedometer.js   V4
// Implements a dydnamic pedometer on Google Maps
// Part of the JH Map system
// Requires Google Maps  (V2)
// 5/10/09 added onmousemove and display
// 10/12/09 Fixed for Degree symbol in input
// 11/1/09 Added "Delete" processing
// 12/17/09 fixed for lng before lat -- from XTide

// Copyright 2007, 2009, Jeff Hennick jhm_system AT jeff-h.com
// See jhm_inc.php for GPL license details.

//////  Pedometer  //////
//var Hped_iframe = false;
//var Hped_doc = document;

var HPedIfrm = '';
var HPedTot = 0;
var HPedReset = 0;
var HEPoly = new Array();
var HEPolyAll = new Array();

function HAddElement(t,p) {  // add a DOM node
 var nel = document.createElement(t);
 for (var i = 2; i < arguments.length; i+=2) {
  nel.setAttribute(arguments[i],arguments[i+1]);
 }
 var pn = document.getElementById(p);
 pn.appendChild (nel);
}

function HAddTextNode(p,t) { // add a text node
 var t = document.createTextNode(t);
 var p = document.getElementById(p);
 p.appendChild(t);
}

function HonLoadPed(HToAddress) {

 var ped_div = document.getElementById('Hpedometer');

 var aclass= '';
   // preloading images for speed
 var data =
   "\n<div>"
   + "\n<img src='icons/x-hair.cur' style='display:none'>"
   + "\n<img src='icons/edit_marker_end.png' style='display:none'>"
   + "\n<img src='icons/edit_marker_mid.png' style='display:none'>"
   + "\n<button id='HEditBut' onclick='HtogEditMode()' title='Click on a Trail'"
   + ">Edit</button>"
//   + "\n<button id='HthisBut' onclick='HEdit(-1)' title='Edit the trail below'"
//   + "class='HthisBut'>This</button>"
   + "\n<button id='HDrawN' onclick='HDraw()' title='Create your own trail or track'"
   + ">Draw New</button>"
   + "\n<button onclick='HAddElevs()' title='Add elevations to the trail info below.'>Elev</button>"
   + "\n<button onclick='HShowGraph()'"
   + " title='Click to create a graph with this and other information.'>Draw Profile<\/button>"
   + "\n<button onclick='HReverse()' title='Reverse the trail below.'>Rev</button>"

   + "\n<br><span class='HgroupOption'> &nbsp; Show: "
   + "\n<input id='HTogLLCb' type='checkbox' onchange='HTogLL()' title='Show Lat/Lons'>LLs"
   + "\n<input id='HTogWpCb' type='checkbox' onchange='HTogWp()' title='Show non waypoint points'>nonWPs"
   + "\n &nbsp; </span>"
   + "\n &nbsp; <span class='HgroupOption'> &nbsp; Units: "
   + "<span  title='Display in metric units.'><input type='radio' name='Hu' onclick='HKmMi(.001)'>Km</span>"
   + "\n<span title='Display in \"English\" units.'>"
   + "<input type='radio' id='HMiles' name='Hu' checked='checked' onclick='HKmMi(0.000621371192)'>Mi</span>"
   + "\n &nbsp; </span>"
   + "\n</div>"

   + "\n<iframe id='detail_if' style='width:100%;height:70%' ></iframe>"
   + "\n<span style='border:solid 1px; padding:4px'>"
   + "\n<button id='HOutBut' onclick='HToText()' title='Lat-Lons to text'>Out</button> "
   + "<input type='checkbox' id='HWithWP' checked='checked'/>With WPs "
   + "<input type='checkbox' id='HWithWPq'/>With &quot;"
   + "</span>"
   + " &nbsp; <button onclick='HToEmail(\"" + HToAddress + "\")'"
   + " title='Click to create an email with this and other information.'>Email Path<\/button>"
   + "\n<br /><textarea rows='6' cols='20' id='HToTextId' style='background-color:#ddddff'></textarea>"
   + "\n<button id='HInBut' onclick='HToLL()' title='Lat-Lon Text to trail line'>In</button> "
   + "\n<div id='HEmailResp' style='background-color:pink;display:none'>Email Response: <div id='HMailResponse'></div></div>"
   + "\n<div id='HEmail' class='HHide' style='z-index:5'>"
   + "\n<div id='HMailDiv'></div></div>";

 ped_div.innerHTML = data;

 data =
   "<table id='pedTable' class='detail_table HnoLL'>"
   + "\n<thead>"
   + "\n<tr><th class='HLaLo'>Lat</th><th class='HLaLo'>Lng</th><th>Alt</th><th>Seg</th><th>Tot</th><th>WayPt</th></tr>"
   + "\n</thead>"
   + "\n<tbody id='detail_table' class='HHideNWp'></tbody></table><span id='HtableTemp' style='visibility:hidden'></span>";
 HPedIfrm = document.getElementById('detail_if');
 if (HPedIfrm.nodeName == 'IFRAME') {
   Hped_iframe = true;
   HPedIfrm = (HPedIfrm.contentWindow)
        ? HPedIfrm.contentWindow
        : (HPedIfrm.contentDocument.document)
          ? HPedIfrm.contentDocument.document
          : HPedIfrm.contentDocument;
   var doc = "<!DOCTYPE HTML><html><head>"
     + "\n<style type='text/css'>\n.righted{text-align:right}\n.detail_table td{padding-left:1em}"
     + "\n.HnoLL .HLaLo{display:none}"
     + "\n.HHideNWp .HnoWp{display:none}"
     + "\n.HShowNWp .HyesWp{display:none}"
     + "\n</style>"
     + "\n<script type='text/javascript'>"
     + "var HWalkMark = '';"
     + "function HWalkMarker(lat, lng) {"
     + "var opts = {"
     + "position : new parent.google.maps.LatLng(lat,lng),"
     + "map : parent.map,"
     + "zIndex : 99"
     + "};"
     + "HWalkMark = new parent.google.maps.Marker(opts);"
     + "}"
     + "function HWalkMarkerOff(){"
     + "HWalkMark.setMap(null);"
     + "HWalkMark = '';"
     + "}"
     + "function HDispLLf(lat, lng) {"
     + "parent.document.getElementById('HToTextId').innerHTML = lat + ',' + lng;"
     + "}"
     + "\n</script>"
     + "\n</head>\n<body>"
   HPedIfrm.document.open();
   HPedIfrm.document.write(doc);
   HPedIfrm.document.write(data + "</body></html>");
   HPedIfrm.document.close();
   var frameObj = document.getElementById("detail_if");
   var fdoc = frameObj.contentDocument;
   var tObj = fdoc.getElementById("detail_table");
 }
 else var parentvar = "";
}


//HOnLoadJ('HonLoadPed');

HPedDisp = 0; // It is not yet displayed.

var HWPD = 0;
var HWPNum = 1;
var HWPNumMk = [];
var HEMark;
var HWPMk = [];

var HTDist = '';
var HWPN = '';

var HPList = [];
var HPLpt = 1;
var HPedSeg = [];
    HPedSeg[0] = 0;
var HTDistMv = 0;
var HWPList = [];  // indexed by points. sparce. value: waypoint number
var HWPDist = [];
    HWPDist[0] = 0;

var HRecord = 0;
var HWPRecord = 0;

var HMFac = 0.000621371192;
var HShowDetails = 0;
var HShowElevation = 0;
var HFDeg = 0;  // 0: D 1: DM 2: DMS

var HElId = 0;
var HRId = 0;
var Hfirstwp = 'Start';

var HAJAXn = 0;
var HTMark = '';
var HMoveN;
var HMoveS;

var HMWPm;
var HMWPp = 1;

var HLastWP = '';

var Hpp = new google.maps.Point(0,0);
var Hzero = Hpp;
var Htotd = 0;
var Hddd = 0;

//var Helement_being_edited;

function HTMOver(num, rid) {
 HTMOut(rid);
 if (HPList[num]) {
  HTMark = new google.maps.Marker(HPList[num], HWPMarker);
  map.addOverlay(HTMark);
 }
 document.getElementById(rid).style.color = 'red';
 var d = document.getElementById('HPwpDispData');
 var dd = document.getElementById(rid).firstChild.innerHTML.replace(' ', '');
 if (dd == '') dd = '-';
 if (d) d.innerHTML = dd;
}

function HTMOut(rid){
 map.removeOverlay(HTMark);
 document.getElementById(rid).style.color = 'black';
}

function HmouseMove(p) {
var distbox = document.getElementById('Hddd');
  if (Hpp == Hzero) {
  }
  else {
   Hddd = HMFac * Hpp.distanceFrom(p) * .001;
   distbox.innerHTML = Hddd.toFixed(4)  + 'mi (' + parseInt(Hddd * 5280, 10) + "'), " + (Htotd + Hddd).toFixed(4);
  }
}

function HChangeWP(rn) {
 var col = (HShowDetails) ? 4 : 0
 var rid = parseInt(rn, 10);
 rid = 'R' + rid
 var row = document.getElementById(rid);
 var cn = row.getElementsByTagName('td');
 HWPList[rn] = cn[col].firstChild.value;
}

function HReverse() {
 var revarray = new Array();
 var HPedTot = 0;
 var HPedDist = 0;

 HPedIfrm.document.getElementById('detail_table').innerHTML = '';

 for (var i = HEPolyAll.length - 1; i > -1; i--) {
  var j = HEPolyAll.length - 1 - i;
  revarray[j] = HEPolyAll[i];
 }
 HEPolyAll = revarray;
 HPedTDisp();
}

function HTogWp(v) {
  var cn = HPedIfrm.document.getElementById('detail_table').className;
  cn = cn.replace('HHideNWp', '');
  cn = cn.replace('HShowNWp', '');
  if (document.getElementById('HTogWpCb').checked == true || v == 1) {
//   cn = cn.replace('HHideNWp', 'HShowNWp');
   cn += " HShowNWp";
   document.getElementById('HTogWpCb').checked = true;
  }
  else {
//   cn = cn.replace('HShowNWp', 'HHideNWp');
   cn += " HHideNWp";
   document.getElementById('HTogWpCb').checked = false;
  }
  HPedIfrm.document.getElementById('detail_table').className = cn;
}

function HTogLL() {
  var cn = HPedIfrm.document.getElementById('pedTable').className;
  var p = cn.indexOf('HnoLL');
  if (p > -1) {
   cn = cn.substr(0,p) + cn.substr(p+5);
   document.getElementById('HTogLLCb').checked = true;
  }
  else {
   cn += ' HnoLL';
   document.getElementById('HTogLLCb').checked = false;
  }
  HPedIfrm.document.getElementById('pedTable').className = cn;
}

/*
function v3HDelWP(n) {
 n = parseInt(n);
//GLog.write('260 ' + n + ', ' + HPList.length);
// if(n == HPList.length - 2) return;   // workaround becuse can't remove the last listener ???
//GLog.write('258 n = ' + n + ', HPList[n] = ' + HPList[n] + ', HPList[n+1] = ' + HPList[n+1]);
 Helement_being_edited.deleteVertex(n);
 HPList[n+1] = null;
 var rnum = n + 1;
 var rid = 'R' + rnum;
 document.getElementById(0 + rid).innerHTML = '';
 document.getElementById(4 + rid).innerHTML = '';
 document.getElementById(4 + rid).removeEventListener('onclick',HDelWP,false);
 document.getElementById('HPwpDispData').innerHTML = '-';
}
*/
function HEndAdd() {
 HOverlayList[HsegNum] = new google.maps.Polyline(HPList, "#FF0000", 5);
 map.addOverlay(HOverlayList[HsegNum]);
 google.maps.event.addListener(HOverlayList[HsegNum], "click", function(point) {HTrailClick(point,HsegNum,'')})
 HsegNum++;
 if (HEMark) map.removeOverlay(HEMark);
 if (HPList.length > 0) {
  HEMark = HCreateNumMarker(HPList[HPLpt-1],HWPNum);
  map.addOverlay(HEMark);
 }
 var col = (HShowDetails) ? 4 : 0;
 var pr = HPLpt - 1;
 if (document.getElementById("R" + pr)) {
  var tds = document.getElementById("R" + pr).childNodes;
  var inp = tds[col].childNodes;
  if (inp[0].value == 'E') inp[0].value = (HLastWP == '') ? 'End' : HLastWP;
  if (HShowDetails) {
//   tds[5].removeEventListener('onclick',HDelWP,false);
//GLog.write('289 ' + (4 + "R" + pr));
// document.getElementById(4 + "R" + pr).removeEventListener('onclick',HDelWP,false);
//   tds[5].innerHTML = '';
  }
 }
}

function HAddElevs() {
  if (typeof(HEPolyAll) == 'undefined' || HEPoly == '') return;
  var length = HEPolyAll.length;
  var b = HPedIfrm.document.getElementById('detail_table');
  var rows = b.childNodes;
  for (var i = 0; i < length; i++){
    var curLatLng = HEPolyAll[i];
    var cells = rows[i].childNodes;
    if ( cells[2].innerHTML == '') HGetElevation(curLatLng.lat(),curLatLng.lng(), 'R' + i + 'A');
 }
}

function HAddWayPoint(n,line) {
 if (n) while (n[0] == ' ') n = n.substr(1);
 else n = '';
 if (n[0] == '"' || n[0] == "'") {
  if (n[n.length-1] == n[0]) {
   n = n.substr(1,n.length - 2);
  }
 }
 if (line) var rid = 'R' + line;
 else var rid = 'R' + HRId;

 HWPList[HPLpt-1] = n;
 if (typeof(HPList[HPLpt-1]) != 'undefined'){
  HWPNumMk[HWPNum] = new google.maps.LatLng(HPList[HPLpt-1].lat(),HPList[HPLpt-1].lng());
  HWPMk[HWPNum] = HCreateNumMarker(HPList[HPLpt-1],HWPNum);
  if (HEMark) map.removeOverlay(HEMark);
  map.addOverlay(HWPMk[HWPNum]);
  HWPDist[HWPNum] = HMFac*HTDistMv;

  if (HShowDetails) {
   var tds = document.getElementById("R" + HRId).childNodes;
   tds[4].childNodes[0].value = n
  }
  else { //! HShowDetails
   var tds = document.getElementById("R" + HRId).childNodes;
   tds[0].childNodes[0].value = n
  }
  HWPD = 0;
  HWPNum++;
 }
}

function HMakeHeadRow() {
 var hr = document.createElement('tr');
 for (var i = 0; i < arguments.length; i++) {
  var h = document.createElement('th');
  var t = document.createTextNode(arguments[i]);
  h.style.textAlign = 'center';
  h.appendChild (t);
  hr.appendChild (h);
 }
 var p = document.getElementById('Hrec_tab');
 if (p) {
  var th = p.firstChild;
  th.appendChild(hr);
 }
}

function HShowGraph() {
  var x = '';
  var y = '';
  var wpd = ''
  var wpn = ''
  if (typeof(HEPolyAll) == 'undefined' || HEPolyAll == '') return;
  var length = HEPolyAll.length;
  var b = HPedIfrm.document.getElementById('detail_table');
  var rows = b.childNodes;

  var pres = 2;
  var tot = HEPolyAll[length-1].dist;
  if (tot <= 1) pres = 4;
  else if (tot <= 10) pres = 3;

  var prev = '';
  var prevname = '';

  for (var i = 0; i < length; i++){
    var curLatLng = HEPolyAll[i];
    var px = curLatLng.dist.toFixed(pres);
    var cells = rows[i].childNodes;
    var py = cells[2].innerHTML;
    var pp = x + ' ' + py;
    if (pp == prev) continue; // dup
    x += "," + px;
    y += "," + py;
//  var c = 0;
    if (typeof(curLatLng.WPName) != 'undefined' && curLatLng.WPName != '' && curLatLng.WPName != prevname){
     wpd += "," + curLatLng.dist.toFixed(pres);
     wpn += "," + curLatLng.WPName.replace(/,/g,'&#44;');
     prevname = curLatLng.WPName;
//    c++;

   }
   prev = pp;
  }

  x = x.substr(1);
  y = y.substr(1);
  wpd = wpd.substr(1);
  wpn = wpn.substr(1);
  wpd = wpd.replace(/ */g,'');

  var w = 0;
  var h = 0;
  var d = document.getElementById('HPImg');
  if (d) {
   w = d.width;
   h = d.height;
  }

  if (typeof(w) == 'undefined' || !w ||  w == 0) w = 900;
  if (typeof(h) == 'undefined' || !h ||  h == 0) h = 450;

  var url = 'jhm_draw_graph.php';

  // Remove old graph
  ne = document.getElementById('HPImg_i');
  if (ne) ne.parentNode.removeChild(ne);

  // Create new image element
  var jsel = document.createElement('IMG');
  jsel.type = 'image/gif';
  jsel.type = 'text/html';
  jsel.height = h;
  jsel.width = w;
//  jsel.onload = "window.scrollTo(0, document.getElementById('HPImg_i').offsetTop)";
  jsel.id = 'HPImg_i';
  jsel.src = url  + '?x=' + x + '&y=' + y + '&wpd=' + wpd
           + '&wpn=' + encodeURIComponent(wpn)
           + '&h=' + h + '&w=' + w;
  jsel.alt = "Graph of Elevations";

  // Append JS element (therefore executing the 'AJAX' call for the graph)
  d.appendChild (jsel);

//alert(document.getElementById('HPImg').offsetTop);
//alert(document.getElementById('HPImg').parentNode.offsetTop);
//alert(document.getElementById('HPImg').parentNode.parentNode.offsetTop);
  window.scrollTo(0, document.getElementById('HPImg').parentNode.parentNode.offsetTop);
 }


function HTogRecord(button) {
 if (button == 'HRecBut') {
  HRecord = !HRecord;
  HClickProc = !HClickProc;
 }
 var rb = document.getElementById(button);
 if (HRecord) rb.innerHTML = 'Stop';
 else rb.innerHTML = 'Start';
}

function HGetWayPoints() {
  var wpl = [];
  var t = document.getElementById('HTB');
  var ra = t.getElementsByTagName('tr');
  for (var i = 0; i<ra.length;i++) {
   var cn = ra[i].getElementsByTagName('td');
   if (cn[4] && cn[4].firstChild.value != '') {
    wpl[i] = cn[4].firstChild.value;
   }
  }
  return wpl;
}

function HToText(email) {  // V4
 var o = '';
 var fsep = ',';
 var ssep = ', ';

 var wwp = document.getElementById('HWithWP').checked;
 var wwpq = document.getElementById('HWithWPq').checked;
 if (wwpq) wwp = false;

 if (typeof(HEPolyAll) != 'undefined') {
  for(var i=0;i < HEPolyAll.length; i++) {
   var curLatLng = HEPolyAll[i];
//    // if del is checked, go to next one
//   if (typeof(curLatLng.del) != 'undefined' && curLatLng.del) continue;
   var y = trim(curLatLng.lat().toFixed(6),'0');
   var x = trim(curLatLng.lng().toFixed(6),'0');

   o += (email) ? y + ',' + x : HDeg2DMS(y) + fsep + HDeg2DMS(x);

   var name = (typeof(curLatLng.WPName) == 'undefined') ? '' : curLatLng.WPName;

   if (name != '') {
    if (i == 0) {
     o += (wwpq) ? ',"' + name.replace('"', '\\"') + '"': '';
     o = (wwp) ? "'" + name.replace("'", "\\'") + "'," + o : o;
    }
    else {
     o += (wwpq) ? ',"' + name.replace('"', '\\"') + '"': '';
     o += (wwp) ? ",'" + name.replace("'", "\\'") + "'": '';
    }
   }
   o += ssep;
  }
 }
 o = trim(o);
 o = trim(o, ',');
// o = o.substr(0,o.length-2);
 if (email) return o;
 else {
  var b = document.getElementById("HToTextId");
  b.value = o;
 }
}

/*  v4
function HCloseEmail() {
 var b = document.getElementById('HMailBox');
 var p = b.parentNode;
 p.removeChild(b);
}
*/

function HToEmail(toadr) {
 if (!toadr) toadr = '';
 var latlon = HToText(1);
 var o =
 "<br /><div id='HMailBox' style='border:solid red 1px;background-color:#ccccff'>"
 +  "\n<span class='centered'>Email Selected Path</span>";
 if (latlon.length == 0) o += "\n<div style='color:red'>Select a path by clicking \"Draw New\" then clicking on the map. Then click \"Email Path\" again.</div>";
 o +=  "\n<input type='hidden' id='Hlatlon' name='Hlatlon' value=\"" + latlon + "\">"
 +  "\n<input type='hidden' id='Hhtmlreturn' name='Hhtmlreturn' value=\"" + MapFile + "\">"
 +  "\n<br />To: <input type='text' id='Hto' name='Hto' size='50' maxlength='200' value=" + toadr + ">"
 +  "\n<br />(Full email address(es), separated by commas.)"
 +  "\n<br />From: <input type='tex't id='Hfrom' name='Hfrom' size='50' maxlength='200'>"
 +  "\n<br />(Your email address for CC.)"
 +  "\n<br />Subject: <input type='text' id='Hsubject' name='Hsubjec't size='50' maxlength='200' value='Request for map update'>"
 +  "\n<br /><br />Group:";

 o += "\n<select id='Hgroup' name='Hgroup'>\n<option selected>Other (use comments)</option>";
 for(var tname in trails) {
  o += "\n<option>" + tname + "</option>";;
 }
 o += "\n</select>";

 o += "\n<br/ >Trail Name:"
 +  "<input type='text' id='Htrailname' name='Htrailname'>"
 +  "\n<br /><br /><label>Color:"
 +  "<select id='Hcolor' name='Hcolor'>"
 +  "\n<option value='other' selected>Other (use comments)</option>"
 +  "<option value='#000000'>Black</option>"
 +  "<option value='#804000'>Brown</option>"
 +  "<option value='#ff0000'>Red</option>"
 +  "<option value='#ff8040'>Orange</option>"
 +  "<option value='#ffff00'>Yellow</option>"
 +  "<option value='#00ff00'>Green</option>"
 +  "<option value='#0000ff'>Blue</option>"
 +  "<option value='#800080'>Violet</option>"
 +  "<option value='#808080'>Grey</option>"
 +  "<option value='#ffffff'>White</option>"
 +  "\n</select></label>"
 +  "\n<br />Transparency: "
 +  "\n<select id='Hopacity' name='Hopacity'>"
 +  "\n<option value='.1'>10% (very faint)</option>"
 +  "<option value='.2'>20%</option>"
 +  "<option value='.3'>30%</option>"
 +  "<option value='.4'>40%</option>"
 +  "<option value='.5'>50%</option>"
 +  "<option value='.6'>60%</option>"
 +  "<option value='.7' selected>70%</option>"
 +  "<option value='.8'>80%</option>"
 +  "<option value='.9'>90%</option>"
 +  "<option value='1'>100% (covers anything)</option>"
 +  "\n</select>"
 +  "\n<br>Width (pixels): "
 +  "\n<select id='Hwidth' name='Hwidth'>"
 +  "\n<option value='1'>1</option>"
 +  "<option value='2'>2</option>"
 +  "<option value='3' selected>3 (footpath)</option>"
 +  "<option value='4'>4</option>"
 +  "<option value='5'>5</option>"
 +  "<option value='6'>6</option>"
 +  "<option value='7'>7</option>"
 +  "<option value='8'>8</option>"
 +  "<option value='9'>9 (improved multiuse)</option>"
 +  "\n</select>"
 +  "\n<br /><br />InfoWindow (Shown when trail is clicked. Optional):"
 +  "<br /><textarea id='HinfoWindow' name='HinfoWindow' rows='5' cols='40'></textarea>"
 +  "\n<br /><br />Comments: <textarea id='Hcomments' name='Hcomments' rows='5' cols='40'></textarea>"
 +  "\n<br />Your Name:"
 +  "\n<input type='text' id='Hsender' name='Hsender' size='50'>"
 +  "\n<br /><button name='button' onclick='HAjaxPost(\"jhm_mailsender.php\","
 +  "\"Hlatlon\",\"Hhtmlreturn\",\"Hto\",\"Hfrom\",\"Hsubject\",\"Hgroup\",\"Htrailname\",\"Hcolor\","
 +  "\"Hopacity\",\"Hwidth\",\"HinfoWindow\",\"Hcomments\",\"Hsender\");HEmailCan();'>"
 +  "\nSend</button>"
 +  "\n &nbsp; <button onclick='HEmailCan()'>Cancel</button>"
 +  "\n</div><br />";

 var ms = document.getElementById('HMailDiv');
 if (ms) ms.innerHTML = o;
 ms = document.getElementById('HEmail');
 ms.className = 'HShow';
 document.getElementById('HEmail').scrollIntoView();

}

function HEmailCan() {
 ms = document.getElementById('HEmail');
 ms.className = 'HHide';
}

function HToLL(o,wp) {   // Text to LatLon
 var pts_supplied = 0;

 var k = 0; // output index
 var px = '';
 var py = '';
 var dx = '';
 var dy = '';
 var d2 = '';
 var ppx = '';
 var ppy = '';
 var m = '';
 var mp = '';
 var ta = new Array();
 var eliminated = 0;
 var wpname = '';

 if(typeof(HEPolyAll) == 'undefined') HEPolyAll = new Array();

 if (typeof(o) == 'undefined' || o == '') {
  var b = document.getElementById("HToTextId");
  var o = b.value;
//  o = o.toLowerCase();
  o = o.replace(/,?\n/g,", ");
 }
 else pts_supplied = 1;

 var tempa = new Array(o);

 var temp = o.split(",");
 var wpnames = new Array();

 if(typeof(temp[1]) != 'undefined') {
  var num_pm = temp[1].split("+").length + temp[1].split("-").length;
  if(num_pm > 4) {  // compressed format
   var t0 = trim(temp[0],'"');
   var t1 = trim(trim(temp[1]),'"');
   var t2a = temp.slice(2).join(',')
   var t2b = trim(trim(t2a),'"');
    t2b = trim(trim(t2b),'{');
    t2b = trim(trim(t2b),'}');
    t2b = trim(trim(t2b),'"');
   var t2c = t2b.split('","')
   for(var i=0; i<t2c.length; i++) {
    var temp3 = t2c[i].split('":"');
    wpnames[temp3[0]] = temp3[1];
   }
   var temp2 = HexpandCompressed(
    t0,
    t1,
    wpnames);
   o = temp2.join(',').replace(/[\(\)]/g,'');
  }
 }

 if(o.indexOf('<gpx ') > 0) { // GPX format
  var gpx1 = o.match(/<trkpt (.*?)>/g);
  var gpx = '';
  for(var i = 0; i < gpx1.length; i++) {
   var ll = gpx1[i].match(/"(.*?)".*?"(.*?)"/);
   gpx += ',' + ll[1] + ',' + ll[2];
  }
  o = gpx.substr(1);
 }

  if (HPedIfrm.document.getElementById('detail_table').innerHTML != '') {
   HPedReset = (confirm ("Clear Existing?")) ? true : false;
  }

  if (HPedReset) {
    HEPolyAll = new Array();
    HPedIfrm.document.getElementById('detail_table').innerHTML = '';
  }

 var hrec = HRecord;
 HRecord = 1;

 var wpa = new Array();
 if(wp) {
  for(;wp != '';) {
   var pc = wp.indexOf(',');
   if (pc == -1) break;
   var y = wp.substr(0, pc);
   wp = wp.substr(pc+1);
   pc = wp.indexOf(',');
   if (pc == -1) {
    var x = wp;
    wp = '';
   }
   else {
    var x = wp.substr(0, pc);
    wp = wp.substr(pc+1);
   }
   x = x.replace(/[+ ]g/, '');
   y = y.replace(/[+ ]g/, '');
   wpa.push(new google.maps.LatLng(y,x));
  }
 }

 var wpname = '""'; // first waypoint name

    var polyOptions = {
     strokeColor: '#BEF73E',
     strokeOpacity: 1.0,
     strokeWeight: 3,
     title: 'In'
    }

    HEPoly = new google.maps.Polyline(polyOptions);
    HEPoly.setMap(map);

  HPedDist = 0;
  if (HPedReset) HPedTot = 0;
  var prevLatLng = '';

 for (var i=0; o != ''; i++) {
//GLog.write('734 i = ' + i);
  o = trim(o);
  pc = o.indexOf(',');
  if (pc == -1) pc = o.indexOf("\t");
//  if (pc == -1) {pc = o.indexOf("\n");alert("714 " + pc);}
  if (pc == -1) {
   var fc = o.substr(0,1).toLowerCase().indexOf('w');
   if (fc > -1) {
    if (!isNaN(o.substr(1))) { // W number
     o = 0 - o.substr(1);
     pc = o.length;
    }
   }
  }
//   if (o.indexOf("w") > 1) pc = o.indexOf("w") - 1;  // needs generalization, but works for today's input  // ??
   else if (o.indexOf("X:") == 0) {    // OnCOR data
    var px = 0;
    var py = o.indexOf("Y:");
    if (py > -1) {
     if (py > px) {
      var lat = o.substr(py + 3);
      var pct = lat.indexOf(',');
      if (pct > -1) lat = lat.substr(0, pct);
      var lon = o.substring(px + 3, Math.min(pc,py));
      pc = (o + ' ').indexOf(' ',py + 3);
      var osub = o.substr(pc + 1);
      o = lat + ',' + lon + ',' + osub;
      pc = o.indexOf(',');
     }
    }
   }
//  if (pc == -1) pc = o.indexOf(' ');
  if (pc == -1) {
   if (o != '') {
    var fc = o.substr(0,1);
    if (fc != "'" && fc != '"') fc = ' ';
    var namo = trim(o, fc).replace(/'/g, "&#39;");
    HEPolyAll[i - 1].WPName = namo;
//    HinsertWp(namo);
   }
   break;
  }

  var first = o.substr(0, pc);

  var fc = first.substr(0,1);
  var lc = first.substr(first.length - 1);
  var fl = (fc + lc).toLowerCase();
  if (fl.indexOf("w") > -1 || fl.indexOf("e") > -1 ) { // lng (x) is first
   o = o.substr(pc+1);
   pc = o.indexOf(',');
   if (pc == -1) pc = o.indexOf("\n");
   if (pc == -1) pc = o.indexOf("\t");
   if (pc == -1) {
    var pn = o.indexOf('n');
    if (pn < 1) pc = o.indexOf(" ");
   }
   var sec = o.substr(0, pc);
   if (sec == '') {
    sec = o;
    o = '';
   }
   o = o.substr(pc+1);
   o = (o == '') ? sec + ',' + first : sec + ',' + first + ',' + o;
   first = sec;
   pc = o.indexOf(',');
  }

  y = HLL(first);
  o = o.substr(pc+1);
  if (isNaN(y)) {
   var fc = y.substring(0,1);
   if (fc != y.substring(y.length -1)){ // have comma in wp name
    var posq = -1;
    while(1) {
     posq = o.indexOf(fc, posq + 1) // closing quote
     var tc = o.substr(posq -1, 1);
     if (o.substr(posq -1, 1) != "\\") break;
    }
    y += ',' + o.substring(0, posq + 1);
    o = o.substring(posq + 2);
   }
   if (fc == "'") y = y.substring(1,y.length-1);
   if (i == 0) wpname = "'" + y.replace(/'/g, "&#39;") + "'";
   else {
//    HinsertWp(y);
    HEPolyAll[i - 1].WPName = trim(y.replace(/'/g, "&#39;"), fc);
   }
   i--;
   continue;
  }
  else { // y is num
   var pc = o.indexOf(',');
   if (pc == -1) {
    x = HLL(o);
    o = '';
   }
   else {
    x = HLL(o.substr(0, pc));
    o = o.substr(pc+1);
   }
   if(!isNaN(x)) { // x is num
    // add it
    var point = new google.maps.LatLng(y,x);      //////// rather than do this now, make an array, later process the arrya
    ta[i] = point;

//     var m = HCreateNumMarker(point,i);
//     m.setMap(map);

    HEPolyAll.push(point);
    if (wpname != '""') {
     HEPolyAll[0].WPName = wpname.slice(1,-1);;
     wpname = '""';
    }
   }
  }
 }  // i

  for(var i in wpnames) {
   HEPolyAll[i].WPName = wpnames[i];
  }

 document.getElementById('HTogWpCb').checked = true;
 HPedTDisp();
 HEdit(-1);
 HtogEditMode();

 if (HLastWP[0] == "'") HLastWP = HLastWP.substr(1);
 if (HLastWP[HLastWP.length-1] == "'") HLastWP = HLastWP.substr(0,HLastWP.length-1);
// HEndAdd();
 HRecord = hrec;
}

function trim (str, char) {   // http://blog.stevenlevithan.com/archives/faster-trim-javascript
 str = str.toString();
 if (typeof(char) == 'undefined') char = ' ';
 if (char == '"') char = '\\"';
 return eval("str.replace(/^" + char + char + "*/, '').replace(/" + char + char + "*$/, '');");
 eval("var str = str.replace(/^" + char + char + "s*/, '');");
 eval("var ws = /" + char + "/;");
 var i = str.length;
 while (ws.test(str.charAt(--i)));
 return str.slice(0, i + 1);
}


function HLL(n) {    // converts a DMS to DecimalDegrees
 var qp = /^\s*(['"]?)/; // begin with a quote?
 var q = n.match(qp);
 if (q[1] != '') return n;  // get right out

 n = n.replace(/^[+\s]*/, '');  // remove and ignore leading "+" and blanks
 n = n.replace(/\u00B0/g, 'd');  // degree sign

 var d = /\s*([\.\d\-\s'"do]*)([NESW]?)([\.\d\-\s'"d]*)/i; // have a direction letter?
 var f = n.match(d);
                                           //GLog.write('763 f = ' + f);
 var c = f[2].toLowerCase();
 n = f[1] + ' ' + f[3];       // take it out
 var sng = (c == 's' || c == 'w') ? -1 : 1;  // get the +/-

 var m = /([^\-]*)(\-?)(.*)/;   // have a minus sign?
 var ms = n.match(m);
 sng = (ms[2] == '-') ? -sng : sng;   // adjust for it
 n = ms[1] + ' ' + ms[3];        // take it out

 var dms = /\s*([\d\.]*)[\sodO\u00B0]*([\d\.]*)[\s'\u8217]*([\d\.]*)[\s"\u8221]*/  // break into degrees minutes seconds
 var t = n.match(dms);
 var s = (t[3] != '') ? parseFloat(t[3])/3600 : 0;  // convert to degrees
 var m = (t[2] != '') ? parseFloat(t[2])/60 : 0;
 var d = (t[1] != '') ? parseFloat(t[1]) : 0;
 var a = d + m + s;   // add them back to just degrees
 return sng * a;      // put the minus on if needed
}

function HLLm() {    // converts an array of DMS to DecimalDegrees
 var ret = new Array();
 for(var i=0; i<arguments.length; i++)
   ret[i] = HLL(arguments[i]);
 return ret;
}

function HKmMi(n) {
 HMFac = n;
 HEndEdit(1);
// HReshow(1);
}

function HDeg2DMS(d,mark) {
 var mk = "\u00B0";
 if (HFDeg == 0) return parseFloat(d).toFixed(5);
 var sg = d / Math.abs(d);
 var sng = (sg == 1) ? "": "-";
 d = Math.abs(d);
 var deg = Math.floor(d);
 var f = d - deg;
 var m  = f * 60;
 if (HFDeg == 1) {
  m = m.toFixed(4);
  return sng + deg + mk + " " + m  + "&#39;"
 }
 var min  = Math.floor(m);
 f = m - min;
 var sec = (f * 60).toFixed(3);
 return sng + deg + mk + " " + min + "&#39; " + sec + '&quot;';
}

/*
function HDetail(n) {
 var oHSD = HShowDetails;
 if (n==-1)HShowDetails = !HShowDetails;
 else HShowDetails = n;
 var hdet = document.getElementById('HDet')
 document.getElementById('HDet').checked = HShowDetails;
 if (oHSD != HShowDetails) {
  if (HShowDetails) {
    var t = document.getElementById('HTB');
    var ra = t.getElementsByTagName('tr');
    for (var i = 0; i<ra.length;i++) {
     var cn = ra[i].getElementsByTagName('td');
     if (cn[4] && cn[4].firstChild.value != '') {
      HWPList[i] = cn[4].firstChild.value;
     }
    }
   }
  }
  HReshow();
}
*/

function HDMS(n) {
 var oHFDeg = HFDeg;
 HFDeg = n;
// if (oHFDeg != HFDeg) HReshow();
}

function HPedTog() {
 if (parseInt(document.getElementById('HPedCon').style.width) == 0) HPedShow();
 else HPedHide();
}

function HPedShow() {
 Hjscss('remove',document.getElementById("Hpedometer"),'HHide');
// Hjscss('add',document.getElementById("HPedBut"),'HHide');
 var cent = map.getCenter();
 document.getElementById('HPedCon').style.width = '22em';
 document.getElementById('SizeP').src = 'icons/triangle_right.gif';
 document.getElementById('SizeP').title = 'Hide Pedometer';
 HsetMapWidth();
 map.setCenter(cent);
 window.scrollTo(0, document.getElementById('main').parentNode.offsetTop);
}

function HPedHide() {
 Hjscss('add',document.getElementById("Hpedometer"),'HHide');
// Hjscss('remove',document.getElementById("HPedBut"),'HHide');
// controlDiv.style.width = '';
 var cent = map.getCenter();
 document.getElementById('HPedCon').style.width = '0px';
 document.getElementById('SizeP').src = 'icons/triangle_left.gif';
 document.getElementById('SizeP').title = 'Show Pedometer';
 HsetMapWidth();
 map.setCenter(cent);
}

function HGetElevation(y,x,id,n){
 HShowElevation = 1;
//Q: What is the average vertical accuracy of NED?
//
//A: The vertical accuracy is basically +/- 7 to 15 meters. It all depends on the original source DEM and if it was level 1, level 2, or 10m resolution.
 if(n==null) n = id;
 var u = (HMFac == 1) ? 'METERS' : 'FEET';
 var p = (HMFac == 1) ? 1 : 0;

 var url = 'jhm_ll_to_el.php';

 // Create new JS element
 var jsel = HPedIfrm.document.createElement('SCRIPT');
 jsel.setAttribute("type","text/javascript");
 jsel.setAttribute("id","AJAX" + (HAJAXn++));
 jsel.setAttribute("src",url + '?x=' + parseFloat(x).toFixed(5) + '&y=' + parseFloat(y).toFixed(5) + '&i=' + id + '&n=' + n + '&u=' + u + '&p=' + p);

 // Append JS element (therefore executing the 'AJAX' call for the elevation)

 sp2 = HPedIfrm.document.body.firstChild;
 HPedIfrm.document.body.insertBefore(jsel, sp2);
}

function HMWP(d) {
 if (d == 0) {
  if (HMWPm) {
   map.removeOverlay(HMWPm);
   HMWPm = null;
   document.getElementById('R' + HMWPp).style.color = null;
  }
  else if (HPList[1]) {
   HMWPm = new google.maps.Marker(HPList[1], HWPMarker);
   map.addOverlay(HMWPm);
   document.getElementById('R1').style.color = 'red';
   HMWPp = 1;
   document.getElementById('HMWPcbd').disabled = false;
   document.getElementById('HMWPcbu').disabled = false;
  }
 }
 else if (HMWPm) {
  document.getElementById('R' + HMWPp).style.color = null;
//GLog.write('start ' + HMWPp + ':' + HPList[HMWPp] + ' :: ' + HPList[HMWPp+1]);
  do {HMWPp += d;} while (HPList[HMWPp] == null && HMWPp > 0 && HMWPp < HPList.length);
//GLog.write('out: ' + HMWPp + ':' + HPList[HMWPp]);
  if (HMWPp < 1) HMWPp = 1;
  if (HMWPp > HPList.length - 1) HMWPp = HPList.length - 1;
  HMWPm.setLatLng(HPList[HMWPp])
  document.getElementById('R' + HMWPp).style.color = 'red';
  var dd = document.getElementById('R' + HMWPp).firstChild.innerHTML.replace(' ', '');
  if (dd == '') dd = ' ';
  document.getElementById('HPwpDispData').innerHTML = dd;
 }
// document.getElementById('HMWPcb').innerHTML = HMWPp;
}

var HDPoly = '';

function HDraw() {
 HInEditing(true);
 Hz_index_being_edited = 0;
 var b = document.getElementById('HDrawN');
 var n = b.innerHTML == 'Draw New';
 if (n) {
  HDPoly = null;

  HDPoly = new EditablePolyline({
    strokeColor: "#FF0000",
    strokeWeight: 3,
    zIndex: 9999
  });
  HDPoly.setMap(map);
  HDPoly.startDrawing();
  b.innerHTML = 'End Draw';
 }
 else {
  var newNumber = 0;
  HDPoly.endDrawing();

  var path = HDPoly.getPath();
  var length = path.length;

  if (length > 0) {
   var x = new Array();
   var y = new Array();
   var n = new Array();
   for (var j=0; j<length; j++) {
    x[j] = path.getAt(j).lat();
    y[j] = path.getAt(j).lng();
   }

   var name = ['_new','' + newNumber];

   HMakeTrailInfoJ('New Draw ' + newNumber);

   Hseg(name, y, x, n, 3, "00ff00", 1, 1);
  }
  HDPoly.setMap(null);
  HDPoly = null;
//  HInEditing(false);
  b.innerHTML = 'Draw New';
  if (length > 0) {
   HtogEditMode();
   HTogWp(1);
   HEdit(HsegNo);
  }
 }
}

function HInEditing(tf) {
  var able = !tf;
  for(var iseg in HsegListener) {
    HsegListener[iseg].setOptions({clickable: able})
  }
  for(var iseg in HmarkListener) {
    HmarkListener[iseg].setOptions({clickable: able})
  }
}

function HtogEditMode() {
  if (HeditTr == false) {
    HeditTr = true;
    document.getElementById('HEditBut').innerHTML = 'End Edit';
//    document.getElementById('HthisBut').style.display = 'inline';
  }
  else {
    HeditTr = false;
    document.getElementById('HEditBut').innerHTML = 'Edit';
//    document.getElementById('HthisBut').style.display = 'none';
    HEndEdit();
  }
}

function HList() {
 HEdit(0);
 HMoveEnd();
}

function HMove(n) {
//GLog.write('1010 HMove(' + n + '), HeditTr = ' + HeditTr);
 if (HeditTr && n) {
  var marker = HOverlayList[n];
  HMoveN = n;
  HMoveS = marker.getLatLng();
  marker.enableDragging();
  marker.dragCrossMove = false;
 }
}

function HMouseOutMk(n){
 if (HMoveN) HOverlayList[HMoveN].disableDragging();
}

function HMoveEnd() {
//GLog.write('1023 HMoveEnd start');
 HOverlayList[HMoveN].disableDragging();
 HRecord = true;
 HAddSegPoint(HMoveS);
 HAddSegPoint(HOverlayList[HMoveN].getLatLng());
 HEndAdd();
 HMoveS = null;
 HRecord = false;
//GLog.write('1023 HMoveEnd end');
}

function HEndEdit(n) {  //v4
  if(typeof(Helement_being_edited.style) != 'undefined')
    Helement_being_edited.style.zIndex = Hz_index_being_edited;
  Helement_being_edited = "";
  if (n == '' && typeof(HEPoly) == 'undefined' || HEPoly == '') return;
  HEPoly.disableEditing();

  if (HPedIfrm.document.getElementById('detail_table').innerHTML != '') {
   HPedReset = (confirm ("Clear Existing?")) ? true : false;
  }

  if (HPedReset) {
   HEPolyAll = new Array();
   HPedIfrm.document.getElementById('detail_table').innerHTML = '';
   HPedTot = 0;
  }

  var length = HEPoly.getPath().getLength();

  for (var i = 0; i < length; i++) {
   HEPolyAll.push(HEPoly.getPath().getAt(i));
  }

  HPedTDisp();

  HInEditing(false);
}

function HPedTDisp() {
// if (a == null) a = HEPolyAll;
 var o = '';
 var prevLatLng = 0;
 var wpclass;
 var dw = 0;
 var dd = 0;
 var dt = 0;

  if (HPedIfrm.document.getElementById('detail_table').innerHTML != '') {
   if(confirm ("Clear Existing?")) {
    HPedIfrm.document.getElementById('detail_table').innerHTML = '';
    HPedTot = 0;
   }
   else {
    prevLatLng = new google.maps.LatLng(HEPolyAll[HEPolyAll.length -1].lat(),HEPolyAll[HEPolyAll.length -1].lng());
   }
  }

 for (var i = 0; i < HEPolyAll.length; i++) {
   var name = '';
   var lat = trim(HEPolyAll[i].lat().toFixed(6),'0');
   var lng = trim(HEPolyAll[i].lng().toFixed(6),'0');
   var wp = HEPolyAll[i].WPName;
   if(typeof wp == 'undefined') wp = '';

    var curLatLng = new google.maps.LatLng(lat,lng);
    if (prevLatLng != 0) {
     HPedDist = HMFac * google.maps.geometry.spherical.computeDistanceBetween(curLatLng, prevLatLng);
     HPedTot += HPedDist;
     dd = (.001 * Math.round(1000 * HPedDist)).toFixed(3);
    }

    dt = (.001 * Math.round(1000 * HPedTot)).toFixed(3);
    HEPolyAll[i].dist = parseFloat(dt);

    if (wp == '' && !(i == 0 || i == HEPolyAll.length - 1)) {
     dw += parseFloat(dd);
     wpclass = " class='HnoWp'";
    }
    else {
     dw = (.001 * Math.round(1000 * (dw + parseFloat(dd)))).toFixed(3);
     dd = "<span class='HnoWp'>" + dd + "</span> <span class='HyesWp'>" + dw + "</span>";
     dw = 0;
     wpclass = '';
    }

    o += "<tr" + wpclass
      + " onclick='HDispLLf(" + lat + "," + lng + ")'"
      + " onmouseover='HWalkMarker(" + lat + "," + lng + ");this.style.backgroundColor = \"#ddddff\"'"
      + " onmouseout='HWalkMarkerOff();this.style.backgroundColor = \"\"'>"
      + "<td id='R" + i + "T' class='HLaLo'>" + lat  + "</td>"
      + "<td id='R" + i + "N' class='HLaLo'>" + lng + "</td>"
      + "<td id='R" + i + "A' class='righted'></td>"
      + "<td class='righted'>" + dd + "</td><td class='righted'>" + dt + "</td>"
      + "<td><input id='R" + i + "I' type='text' value='" + wp
      + "' onchange='parent.HWpChange(" + i + ", this)' /></td>"
//      + "<td><input type='checkbox' id='R" + i + "D' title='Mark for non-output"
//      + " onchange='parent.HDelChange(" + i + ")'/></tr>";
      + "</tr>";
   prevLatLng = curLatLng;
 }

  var temp = HPedIfrm.document.getElementById('HtableTemp');
  var tempClass = (document.getElementById('HTogWpCb').checked) ? " class='HShowNWp'" : " class='HHideNWp'";
  if (HPedReset)  temp.innerHTML = "<table><tbody id='detail_table'" + tempClass + ">" + o;
  else temp.innerHTML = "<table><tbody id='detail_table'" + tempClass + ">" + HPedIfrm.document.getElementById('detail_table').innerHTML + o;
  var tb = HPedIfrm.document.getElementById('detail_table');
  tb.parentNode.replaceChild(temp.firstChild.firstChild, tb);
}

function HWpChange(i, el) {
//var j = i;
 var wpn = HPedIfrm.document.getElementById('R' + i + 'I');
 HEPolyAll[i].WPName = wpn.value;
var test = el.parentNode.parentNode.className;
 el.parentNode.parentNode.className = (wpn.value == '') ? 'HnoWp' : '';
// HEPoly.getPath().getAt(i).WPName = wpn.value;
}
/*
function HDelChange(i) {
 var del = HPedIfrm.document.getElementById('R' + i + 'D');
 HEPolyAll[i].del = del.checked;
// HEPoly.getPath().getAt(i).del = del.checked;
}
*/

function HEdit(n) { //v4
  HInEditing(true);

  if (n == -1) {
   Helement_being_edited = HEPoly;
//   document.getElementById('HthisBut').style.display = 'none';
  }
  else if (n != 0) Helement_being_edited = HTrails[n];

  if (n != 0) {
    if(HEPoly) {
     HEPoly.setMap = null;
     HEPoly = null;
    }
    var epopt = {
     strokeColor: '#FF00FF',
    }
    HEPoly = new EditablePolyline(epopt); // (elist, "#00ffff",5,.50);
    if (n == -1) HEPoly.setPath(HEPolyAll);
    else HEPoly.setPath(HTrails[n]);
    HEPoly.setMap(map);
    HEPoly.enableEditing();
    if (n == -1) HEPoly.title = 'In0';
    google.maps.event.addListener(HEPoly, 'click', function() {
      if (this.isEditing()) {
       this.disableEditing();
      }
      else {
        this.enableEditing();
      };
    }
    );
    if (n == -1) {
     var label = new Label({
       map: map,
       text: 'New Path'
     });

     google.maps.event.addListener(HEPoly, 'mouseover', function(event) {
       var point = event.latLng;
       label.Position = point;
       label.setMap(map);
     });
     google.maps.event.addListener(HEPoly, 'mouseout', function(event) {
       label.setMap(null);
     });
    }
  }
}


