// Copyright 2006, 2007 Tim Flavin (Except whare otherwise noted.)
// $Id: j1.js,v 1.3 2009/08/18 00:50:02 timflavin Exp $

///*** Global Variables ***///

var centerLatitude = 45.686;
var centerLongitude = -69.5984;
var startZoom = 10;
var map;                  // The Gmap object
var pages = {};           // HTML text for pages in slideText div
var paths = {};           // Paths for pages that have a path
var lables = {};
var path_levels = {};     // Levels for paths
var paramDat = {};
var last_path_name;       // So we can delete it for next page.
var lastMarker = null;    // Set by &M=marker and "Create Marker"
                          // so we can clear it when we do an np()
// Todo: clean up map type code ?

var mapTypes              // array of map types so we can set arbitrary types
var mapType = 0;          // map type from &t=1 arg zero means default
var inPrintState = 0;
var user_info;            // Cookie data
var markerArg = null;     // page was loaded with &m=marker
var savedMTID    // Used by MarkerTable routines
var markerTableText = '';
var args;
var zoonName, oldZoom, oldCenter          // zooNName ........................bug?
var loggedIn = 0;           //  Logged in suers can edit.
var logoHeight = 95;
var buttonHeight = 19;
var latLngListener = 0;
var lastDisplayedMarkerType;

function loadWin(){
    get_markers();
    args = getArgs();

//// ** Cookie procesing  **  ///

   user_info = new Cookie(document, "user_info", 240, "/");
   loggedIn = 0
   if (user_info.load() && user_info.name) {
       loggedIn = 1;
       document.getElementById('editButtons').style.display="inline";
   } else {
       majorTypes.pop()    // "Other" Only visable to logged in users
   }

   resizeWin();

    map = new GMap2(document.getElementById("map")
, {draggableCursor: 'crosshair', draggingCursor: 'pointer'});
    map.addControl(new GLargeMapControl());
    map.addControl(new GScaleControl());
    map.addControl(new GMapTypeControl());

    // 1 is an ID number, 14 is min zoom  bounds is sw, ne
    var copyright = new GCopyright(1, 
         new GLatLngBounds(new GLatLng(45.1297, -70.07),
         new GLatLng(46.07320, -69.17816) ),
         17, "Moosehead Maps");

    var copyrightCollection = new GCopyrightCollection('Topo:');
         copyrightCollection.addCopyright(copyright);
// Topo

    var tilelayers = [new GTileLayer(copyrightCollection,10,16)];
    tilelayers[0].getTileUrl = getMapTile;
    var topomap = new GMapType(tilelayers, new GMercatorProjection(18), 
         "Topo", {shortName:"Topo"});
    map.addMapType(topomap);

// Aerial

    var atiles =  [new GTileLayer(copyrightCollection,10,16)];
    atiles[0].getTileUrl = getMapTile1;
    atiles.isPng=notpng;
    var amap = new GMapType(atiles, new GMercatorProjection(18), 
         "Aerial", {shortName:"Air"});
    map.addMapType(amap);

// Test tiles (topo)
//
//    var ttiles =  [new GTileLayer(copyrightCollection,14,17)];
//    ttiles[0].getTileUrl = getMapTile2;
//    ttiles.isPng=ispng;
//    var tmap = new GMapType(ttiles, new GMercatorProjection(18), 
//         "Test", {shortName:"Test"});
//    map.addMapType(tmap);

//  Overlay 
    if (args['r']){
        var oTiles = new GTileLayer(new GCopyrightCollection(''));
        oTiles.getTileUrl = getMapTile3;
        oTiles.isPng = function() {return true; }
        oTiles.getOpacity = function() { return 1.0; }
        xl = amap.getTileLayers();
        xl.push(oTiles);  
        xl = topomap.getTileLayers();
        xl.push(oTiles);
    }
/* Process arguments from URL, marker, zoom, lat, lng */
/* .../index.html?m=Lily%20Bay%20Road&z=10&t=1    */

    mName = args["m"]       // Marker m=house
    if (MK[mName]) {
        new_mk_GM(mName);
        markerArg = mName;
        centerLatitude = MK[mName][mk_lat];
        centerLongitude = MK[mName][mk_lng];
        startZoom = 14;
    }
    z = args.z - 0;         //    Zoom: z=10 
    if (z) {
        startZoom = z;
    }

    mapType = args.t - 0;     // Map type t=1
    if(mapType) {
          mapType = mapType - 1   // Index starts at 0, but 0 means no arg.
          mapTypes= map.getMapTypes();
    }
    zoomTest = args.zt
    la = args.la - 0;          // latitute: la=45.555
    lo = args.lo - 0;          // longitude ln=-69.444
    if (!(isNaN(la) || isNaN(lo))){
        centerLatitude = la;
        centerLongitude = lo;
    }
    testLevel=args.tl;          // Test level tl
    if (testLevel == 1){
    }
    map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom,
        topomap);
    if (testLevel) {
        GEvent.addListener(map, 'click', gotClick);
    }
    if(args.b){             // b=1 Draw boxes
        drawBoxes();
    }
    init2();
}
function lbox(n, s, e, w){
 map.addOverlay(new GPolyline([
 new GLatLng(n, e), new GLatLng(n,w),
 new GLatLng(s,w), new GLatLng(s,e),
 new GLatLng(n, e)   ], "#000000", 1, 1));
}
///*** Tile layer routines ***  ///



function copyRight(a,b) {
    return G_NORMAL_MAP.getTileLayers()[0].getCopyright(a,b);
    
}

//          ts        ts            drg
//       _______    ________    ________________
//       10   11    12    13    14     15     16
minx = [312, 625, 1250, 2501, 5002, 10005, 20011]
maxx = [315, 630, 1260, 2521, 5043, 10087, 20174]
miny = [364, 728, 1456, 2912, 5824, 11648, 23296]
maxy = [367, 735, 1471, 2942, 5885, 11770, 23541]
//minx = [312, 625, 1250, 2501, 5002, 10016, 20032]
//maxx = [315, 630, 1260, 2521, 5040, 10080, 20160]
//miny = [364, 728, 1456, 2912, 5824, 11648, 23296]
//maxy = [367, 735, 1471, 2942, 5872, 11744, 23488]

function getMapTile(tile, zoom){
    var n = zoom-10 
    if (minx[n] && tile.x >= minx[n] && tile.x <= maxx[n] & 
                   tile.y >= miny[n] && tile.y <= maxy[n]){
        return "map/tt" + tile.x + "y" + tile.y + "z" + zoom + ".jpg"
     } else {
        return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(tile,zoom);
     }
}

function getMapTile1(tile, zoom){  // Topo
    s = Math.pow(2,zoom-10);
    if (zoom >= 10 && zoom <=16 && tile.x >= s*312 && tile.x< s*315 && 
        tile.y >= s*364 && tile.y < s*368 ) {
        return "amap/tt" + tile.x + "y" + tile.y + "z" + zoom + ".jpg"
     } else {
        return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(tile,zoom);
     }
}
function getMapTile2(tile, zoom){  //Aerial
    s = Math.pow(2,zoom-10);
    if (zoom >= 10 && zoom <=18 && tile.x >= s*312 && tile.x< s*316 && 
        tile.y >= s*364 && tile.y < s*368 ) {
        return "tmap/tt" + tile.x + "y" + tile.y + "z" + zoom + ".png"
     } else {
        return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(tile,zoom);
     }
}

function getMapTile3(tile, zoom){  // Overlay Test

    var s = Math.pow(2,zoom-10);
    if (zoom >= 10 && zoom <=18 && tile.x >= s*312 && tile.x< s*316 && 
        tile.y >= s*364 && tile.y < s*368 ) {
        var t = "ov/o" + tile.x + "y" + tile.y + "x" + zoom + ".png"
        return t
     } else {
        return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(tile,zoom);
     }
}

function ispng(){
    return true;
}
function notpng() {
    return false;
}


/// *** map routines *** ///

function unloadWin(){

    GUnload();
    user_info.x='b'
    user_info.store();
}


///*** init2 ***///
function init2(){
// If logged in display editing buttons.  //
  
   if (loggedIn==1){
       document.getElementById('editButtons').display = "inline"
   }

   if (mapType) {
      map.setMapType(mapTypes[mapType]); 
   }

   if (markerArg) {   // lastMarker set in args processing.
      np(markerArg);  // Warning: np() clears lastMarker
      lastMarker = MK[markerArg][mk_GM];
      map.addOverlay(lastMarker);
      lastMarker = null;
   } else {
      np("home");
   }

  if (testLevel == 6){
     GEvent.addListener(map, 'mousemove', function(latlng) {
      var str  = latlng.lat().toFixed(4)
      var str1 = latlng.lng().toFixed(4)
      var str = str + ' ' + str1
      document.getElementById('auxMenu').innerHTML =str
      })
  }
}  

function editCurrent() {
    reservedMarkers = {home:1, About:1, latlon:1};
    if (reservedMarkers[pname]){
       alert(pname + " is not a marker that you can edit.");
    } else {
       var name = pname.replace('&', '%26'); 
       window.location="./cgi/edit_page.py?fname=" + name;
    }
}

///*** RESIZE WINDOW ***///

var logoHeight = 73;


function resizeWin() {
    if (inPrintState) {
       return;
    }
    if (window.self && self.innerHeight){
        height = self.innerHeight;
        width  = self.innerWidth;
    } 
    else if (document.documentElement && document.documentElement.clientWidth) {
        height = document.documentElement.clientHeight;
        width  = document.documentElement.clientWidth;
    }
    else if (document.body && document.body.clientHeight){
         height = document.body.clientHeight;
         width  = document.body.clientWidth;

    } else {
        height = 600;
        width  = 800;
    }
    document.getElementById("map").style.height = (height - 25) + "px";
    document.getElementById("map").style.width = (width - 425) + "px"; 
var logoHeight = 73;
var buttonHeight = 19;
// resize

    if (loggedIn == 1){
// alert('logged In')
         slideTop = logoHeight + buttonHeight * 2;
    } else {
///alert('Not logged In')
         slideTop = logoHeight + buttonHeight;
    }
    slideHeight = height - slideTop -30  // -0
// alert("" + slideTop + ' ' + slideHeight +' '+ loggedIn)
    document.getElementById("slideSection").style.top = 
                 slideTop + "px";
    document.getElementById("slideSection").style.height = 
                    slideHeight + "px";


    adjustSliderNote()
}

//    document.getElementById("").style.top = () + "px";
//    document.getElementById("").style.height = () + "px";


//editButtonsEID.style.top = (logoHeight + buttonHeight) + 'px'
//vpageEID.style.top  =  (logoHeight + buttonHeight * 2) + 'px'
//editButtonsEID.style.top = (logoHeight + buttonHeight) + 'px'
//vpage1EID.style.top  =  (buttonHeight) + 'px'


//***    LOG routine  ***///
// from http://ajaxcookbook.org/javascript-debug-log/
// By Bret Taylor


function log(message) {
    if (!log.window_ || log.window_.closed) {
        var win = window.open("", null, "width=400,height=200," +
                              "scrollbars=yes,resizable=yes,status=no," +
                              "location=no,menubar=no,toolbar=no");
        if (!win) return;
        var doc = win.document;
        doc.write("<html><head><title>Debug Log</title></head>" +
                  "<body></body></html>");
        doc.close();
        log.window_ = win;
    }
    var logLine = log.window_.document.createElement("div");
    logLine.appendChild(log.window_.document.createTextNode(message));
    log.window_.document.body.appendChild(logLine);
}

//***  Cookies routies ***//

//  This example is from the book _JavaScript: The Definitive Guide_.     -->
//  Written by David Flanagan.  Copyright (c) 1996 O'Reilly & Associates. -->
//  This example is provided WITHOUT WARRANTY either expressed or implied.-->
//  You may study, use, modify, and distribute it for any purpose.        -->
//  *  See http://examples.oreilly.com/jscript2/ example 15.1


function Cookie(document, name, hours, path, domain, secure)
{
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}


function _Cookie_store()
{

    var cookieval = "";
    for(var prop in this) {
        // ignore properties with names that begin with '$' and also methods
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }
    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';
    this.$document.cookie = cookie;
}
function _Cookie_load()
{
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;
    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // cookie not defined for this page.
    start += this.$name.length + 1;  // skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);
    var a = cookieval.split('&');  // break it into array of name/value pairs
    for(var i=0; i < a.length; i++)  // break each pair into an array
        a[i] = a[i].split(':');
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }
    return true;
}
function _Cookie_remove()
{
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
}
new Cookie();
Cookie.prototype.store = _Cookie_store;
Cookie.prototype.load = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;


/// ** Tool tip routines **  //

// From http://
//  googlemapsbook.com/chapter9/CustomInfoWindow/map_functions.js.source#l9-2

//create the ToolTip overlay object

function ToolTip(marker,html,width) {
	this.html_ = html;
	this.width_ = (width ? width + 'px' : 'auto');
	this.marker_ = marker;
}

ToolTip.prototype = new GOverlay();

ToolTip.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.style.display = 'none';
	map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	
	this.map_ = map;
	this.container_ = div;
}

ToolTip.prototype.remove = function() {
	this.container_.parentNode.removeChild(this.container_);
}

ToolTip.prototype.copy = function() {
	return new ToolTip(this.html_);
}

ToolTip.prototype.redraw = function(force) {
	if (!force) return;
	
	var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
	this.container_.innerHTML = this.html_;
	this.container_.style.position = 'absolute';
	this.container_.style.left = pixelLocation.x + "px";
	this.container_.style.top = pixelLocation.y + "px";
	this.container_.style.width = this.width_;
	this.container_.style.font = 'bold 10px/10px verdana, arial, sans';
	this.container_.style.border = '1px solid black';
	this.container_.style.background = '#0c0';
	this.container_.style.padding = '4px';
	
	//one line to desired width
	this.container_.style.whiteSpace = 'nowrap';
	if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
	this.container_.style.display = 'block';
}

GMarker.prototype.ToolTipInstance = null;

GMarker.prototype.openToolTip = function(content) {
	//don't show the tool tip if there is acustom info window
	if(this.ToolTipInstance == null) {
		this.ToolTipInstance = new ToolTip(this,content)
		map.addOverlay(this.ToolTipInstance);
	}
}

GMarker.prototype.closeToolTip = function() {
	if(this.ToolTipInstance != null) {
		map.removeOverlay(this.ToolTipInstance);
		this.ToolTipInstance = null;
	}
}



/// ** Formerly map_functions.js  **  ///

function centerGreenville() {
    map.setCenter(new GLatLng(45.465, -69.598),14);
    np("home");
}

function centerMoosehead() {
    map.setCenter(new GLatLng(centerLatitude, centerLongitude),10)
    if (last_path_name) {
        map.removeOverlay(paths[last_path_name]);
        last_path_name = 0;
    }
    np("home");
}


function createMarker() {
 var opaqueListener = GEvent.addListener(map, "click",function(overlay,latlng){
      Pmarker = new GMarker(latlng);
      map.addOverlay(Pmarker);
      lastMarker = Pmarker;
      GEvent.removeListener(opaqueListener);
      user_info.lat = latlng.lat();
      user_info.lon = latlng.lng();
      user_info.store(200);
 });
 np("latlon");
}


function undoMarker() {   // Removes ?m=marker and "Create Marker" markers.
    if (lastMarker){
        map.removeOverlay(lastMarker);
        lastMarker = null;
    }
}





///*** mt(): Marker Type ***///
// Called when a marker type button is pushed on main menu 
// Removes any markers of the old type then puts new ones on.

mk_lat = 0
mk_lng = 1
mk_GM  = 2
mk_vis = 3
var oldType = "";
var lastMajorType = '';
var lastMinorType = '';

function mt(type) {
// log('Type:' + type)
    if (type.match(/\*/)) {
//#       log('match major: ' + type)
//#       console.log('match Major: ' + type)
       lastMajorType = type
    }
    clearAux = 1;
    if(oldType){      // If previous markers exist on the map remove them
        for (marker in TY[oldType]){
           markerName = TY[oldType][marker];
           map.removeOverlay(MK[markerName][mk_GM]);
        }
    }

    if (type.match(/\-/)) {      // Will set an actual marker.
	clearAux = 0;
    }
    if (type == "home") {
         endMarkerTable();
         clearAux = 0;
    }

    mtm = type.substring(0,2) + type.substring(3,type.length) + '*'
    mtm=  mtm.replace(/_/g, ' ')   // Replace underscore with spaces
    mtm=  mtm.replace(/\*/ , '')   //Delete *
    mtm=  mtm.replace(/O / , '')   // Delete 'O ' which was O_ 
/// if ?????
    for (var n in minorTypes){ // We clicked on a 
        if(minorTypes[n][0] == mtm){
//#          log("Minor type: " + type)
	  lastMinorType = type
          displaySubMenu(minorTypes[n][1] + '*')    
          text =  '<button class="b2" onclick=backMenu()'
          text += '>&larr; &nbsp; Back</button><br>'
          text += '<button class="b2">' + mtm + '</button>' 
          document.getElementById('mainMenu').innerHTML = text;
        }
    }
/// junk below?
    if (m2[mtm] != undefined && mtm.length > 4){    ////adjust for the O_-
        alert('gotit')
        alert(m2[mtm][0][0])
    }

    if (type.lastIndexOf('*') == type.length - 1) {
        displaySubMenu(type);
        type = 0;
        clearAux = 0
        return;
    }
/*   Clear out old markers and add new ones. */

    for (marker in TY[type]){
         var markerName
         markerName = TY[type][marker]
         if (! MK[markerName][mk_GM]){
             new_mk_GM(markerName)
         }
         map.addOverlay(MK[markerName][mk_GM]);
         lastDisplayedMarkerType = type
        }
    oldType = type;
    if (clearAux) {
        document.getElementById('auxMenu').innerHTML = ''
    } 
}


function backMenu(){ //  // Back button to main menu + outdoor list 
    doMainMenu()
    mt('O_*')
}
function backFromMarker(){ // Back button on marker page to previous menu config
// either sub menu or minor menu
    np('home');
    if (lastMajorType == 'O_*'){
      mt(lastMinorType)
    }else{
      mt(lastMajorType)
    }
    mt(lastDisplayedMarkerType)
    map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom)
}


function backMainMenu(){
    doMainMenu()
    document.getElementById('auxMenu').innerHTML = ''

}
/*    Populate the MK[markerName][mk_GM] object */

function new_mk_GM(markerName) {
     MK[markerName][mk_GM] = new GMarker(new GLatLng(
          MK[markerName][mk_lat], MK[markerName][mk_lng]));
      addlis(MK[markerName][mk_GM], markerName);
}


function addlis(marker, name){
    GEvent.addListener(marker, "click", function(){np(name)});

    GEvent.addListener(marker, "mouseover", function(){
        marker.openToolTip(name);
    });

    GEvent.addListener(marker, "mouseout", function(){
        marker.closeToolTip();
    });
}


// New Page: load a new page

function np(name) {  // Send request if we don't have page, else load it
    undoMarker()
    if (latLngListener){
       GEvent.removeListener(latLngListener)
    }
    pname = name
    if (pages[name] == null) {
         u_url = "cgi/users/tim/" + name + ".html"
         GDownloadUrl(u_url, url_resp);
    } else {
         updatePage(name);
    }
}

function url_resp (data, responseCode) {   //  Send requist, load when done.
    if(responseCode == 200 || responseCode == 0) {
         pages[pname] = data;
// #
// # If a path is encoaded in the html, it was probably from
// # http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/encodeForm.html
// # Put the path and level info in the path comment seperated by one space.
// #   ie <!--path lkjoijoj lkjijij -->
// #
         re = 
        /\<!--path\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+--\>/;

         pathLevel = re.exec(data);
         if (pathLevel) { 
             paths[pname] = new GPolyline.fromEncoded({

//   <!-- #0000ff 4 1.0 e_xtGpoxhLl~whL? PP 2 18 -->

                   color:      pathLevel[1],
                   weight:     pathLevel[2],
                   opacity:    pathLevel[3],
                   points:     pathLevel[4],
                   levels:     pathLevel[5],
                   zoomFactor: pathLevel[6],
                   numLevels:  pathLevel[7]
             });
         }
// # Get params Zoom, center Lat and Lng, llflag, etc
         re = 
      /\<!--params\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+--\>/;

         params = re.exec(data);
         if (params){
             paramDat[pname] = params
         }
         updatePage(pname)
         if (testLevel == 3) {   //////  and pname == np 
             rtDisplay();
         }
    } else {
         alert("Could not load page:"  + u_url + ' Error #' +
                  responseCode);
    }
}

function writeZoomButtons(doIt){ 
   var text0 = '';
   var text1 = '';
   var text2 = '';
// doit = 0; clear out the fields, doit = 1 fill them in
    if (doIt){
        text0 = '<img style="cursor: pointer;" src=cgi/ZoomIn.png ' + 
                      'onclick="markerZoomIn()">';
        text1 = '<img style="cursor: pointer;" src=cgi/ZoomBack.png ' +
                       'onclick="markerZoomOut()">';
        text2 = '<button class="b3" onclick=backFromMarker()>' +
                           '&larr; &nbsp; Back</button><br>'
    }
    document.getElementById('zoomInOut').innerHTML = text0;
    document.getElementById('zoomBack').innerHTML = text1;
    document.getElementById('BackButton').innerHTML = text2;
}
function backTypesMenu(){
//log(oldType)
np('home')
}

function adjustSliderNote(){
    window.setTimeout(adjustSliderNoteX, 200);
}


function adjustSliderNoteX(){
    var text = '';
    var width = document.getElementById('slideSection').clientWidth
    if (width < 400){
       text = '<img src="cgi/sliderNote.png">';
    }
    document.getElementById('sliderNote').innerHTML = text;
}


function twidle(element){
document.getElementById("slideText").style.display = "none"; 
window.setTimeout(twidleDeferred, 0);
}

function twidleDeferred(){
   document.getElementById("slideText").style.display = ""; 
   adjustSliderNote()
}

function updatePage(name){
    if (pages[name]) {
        pageHtml = pages[name];
        if (MK[name] != undefined){   // Defined for normal pages only, 
                                      // not home and help
             oldMarkerZoomCenter = map.getCenter()
             oldMarkerZoom = map.getZoom()
             zoomName = name
             markerZoomIn()
             writeZoomButtons(1)
        } else {
             writeZoomButtons(0)
        }
        document.getElementById('slideText').innerHTML = pageHtml;
//var ele = document.getElementById("slideText");
//ele.style.display = "none"; // Cause the slideText to be invisible
//sele = document.getElementById("slideSection");
//sele.style.display = "none"; // Cause the slideText to be invisible
//ele.style.display = ""; // Make slideText visible, causes recalcuation of size
//sele.style.display = ""; // Make slideText visible, causes recalcuation of size
        if (last_path_name) {
            map.removeOverlay(paths[last_path_name]);
            last_path_name = 0;
         }
        if (paths[name]) {
            map.addOverlay(paths[name]);   ///  ie error
            last_path_name = name;
        }
        if (name == 'home'){
             doMainMenu()
        }
    }
   twidle();
  if (args.mType){
    menuType = args['mType']
    delete args.mType
   mt(menuType)
  }


} //* End of updatePage()

//
// Called to zoom into marker, if paramDat has special location use that
//   otherwise center marker in window and use zoom of 14
//
function markerZoomIn(){
   if (paramDat[zoomName]){
      pd = paramDat[zoomName]
      map.setCenter(new GLatLng(pd[1], pd[2]), pd[3] - 0)
      makeLatLngBox()
   } else {
      map.setCenter(new GLatLng(MK[zoomName][0], MK[zoomName][1]), 14)
   }
}

// ............. Really want to make box immediately  when first called
// ... how abpit a popup tool box: lat lng, distance orietation

function makeLatLngBox(){ // called by pages that want lanLng box
      latLngListener = GEvent.addListener(map, 'mousemove', function(latlng) {
        var str  = '&nbsp;' + latlng.lat().toFixed(4)
        var str1 = latlng.lng().toFixed(4)
        var s = '<table border=1 border-color=black>'
        s = s + '<tr><td border = 0 width= 75>Longitude:</td><td>'
        s = s + str +'</td></tr>'
        s = s + '<tr><td >Latitude:</td><td>' + str1 + '</td></tr>'
        s = s + '</table>'
       var id = document.getElementById('auxMenu');
        if (id){
          id.innerHTML = s;
        }else{
          GEvent.removeListener(latLngListener);
        }
      })
}




function markerZoomOut(){
    map.setCenter(oldMarkerZoomCenter, oldMarkerZoom)
}

// ** Print page related routines ** //

function printFmt() {
//var p = 'slideSection';
//    var eid = document.getElementById(p)
//alert(document.getElementById(p).clientWidth)
//alert(document.getElementById(p).offsetWidth)
//alert(document.getElementById(p).scrollWidth)
// window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft

//return
    inPrintState = 1
    document.getElementById("map").style.left = "0px";
    document.getElementById("map").style.height = 740 + "px";
    document.getElementById("map").style.width = 700 + "px";
    document.getElementById("legend").style.display = "inline";
    document.getElementById('buttons').style.display="none";
    document.getElementById('slideSection').style.display="none";
    document.getElementById('logo').style.display = 'none';
    mapLegend();
}

function unprint(){
    inPrintState =  0;
    document.getElementById("map").style.left = "400px";
    document.getElementById("legend").style.display = "none";
    document.getElementById('buttons').style.display= "inline";
    document.getElementById('slideSecyion').style.display= "inline";
    document.getElementById('logo').style.display = "inline";
    resizeWin();
}

function mapLegend() {  // Cide from Marcelo on gmap group
    zoom = map.getZoom()
    document.getElementById("legend").innerHTML =
        '<table><tr><td width="350"><input type="button" value="Back" onclick=\
"unprint()\"<h5><br>Caution Map may have errors due to out of date or incorrec\
t information, or software errors.</h5></td><td width="128"><img src=map/scale\
/ms' + zoom + '.png></td></td><td width="128"><h3>mooseheadmaps.com</h3><\/td>\
</tr><table>'
}


/*
 * This function parses ampersand-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in 
 * properties of an object and returns that object. Use it like this:
 * 
 * var args = getArgs();  // Parse args from URL
 * var q = args.q || "";  // Use argument, if defined, or a default value
 * var n = args.n ? parseInt(args.n) : 10; 
 * Exampel 14-1 from Javascript The Definitive guide by David Flanagan
 * Copyright O'Reilly Media ISBN  0-596-10100-6
 */
function getArgs() {
    var args = new Object();
    var query = location.search.substring(1);     // Get query string
    var pairs = query.split("&");                 // Break at ampersand
    for(var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');          // Look for "name=value"
        if (pos == -1) continue;                  // If not found, skip
        var argname = pairs[i].substring(0,pos);  // Extract the name
        var value = pairs[i].substring(pos+1);    // Extract the value
        value = decodeURIComponent(value);        // Decode it, if needed
        args[argname] = value;                    // Store as a property
    }
    return args;                                  // Return the object
}


// Marker Table: Secondary marker table routines //

function startMarkerTable(id) {
    savedMTID = id  
    markerTableText = ''
}

function addMarkerTable(text, marker) {  // Level 2 on right
    markerTableText = markerTableText + 
    '<button class="b2" style="cursor:pointer;" onclick=mt("' + marker + '")>' + 
    text + '</button><br>'; 

}
function endMarkerTable() {
    document.getElementById('auxMenu').innerHTML = markerTableText
    markerTableText = ''
}

// De-mulitplex click


function gotClick(point, latlng){  // tile, map, latlng location
    if (latlng == undefined){
        return
    }
    if (testLevel == 1){                     // Print lat, lng, map, tile, pix
        clickPrint(point, latlng);
        return;
    }
    if (testLevel == 2){                          //  Bearing start 
        setStart(point, latlng);
        return;
    }
    if (testLevel == 101){                         //   Bearing second pint
        setEnd(point, latlng);
        return;
    }
    if (testLevel == 3){                           // Route maker Start
        rtStart(point, latlng)
        return
     }
    if (testLevel == 103){                         // Route maker Next Point
        rtAddSeg(point, latlng)
        return
     }
    if (testLevel == 4) {                          // Log multiple points 
	markerTableText =  '<button style="width:200px"  \
              onclick=armClick()>' + ' Arm</button>';
	endMarkerTable();
       // http://www.teohuiming.name/toydimap/sandbox/change-map-cursor.html
    }
    if (testLevel == 104) {
	log(latlng.lat() + ' ' + latlng.lng())

      var Pmarker = new GMarker(latlng);
      map.addOverlay(Pmarker);

        testLevel = 4
    }
}
function armClick() {
    testLevel = 104
}
// Called when you click on a map in t=1 mode

function clickPrint(point, latlng){
    var lat, lng
    var pixLoc = map.fromLatLngToDivPixel(latlng);
//    GLog.write('ll:' + latlng + ' at:' + pixLoc);
    lat = latlng.lat();
    var xMapIdx = ((70 + latlng.lng()) / 0.128).toFixed(2)
    var yMapIdx = ((46.0 - latlng.lat()) / 0.128).toFixed(2)
    var zoom = map.getZoom()
    var proj = map.getCurrentMapType().getProjection();
    var xy = proj.fromLatLngToPixel(latlng, zoom);
    var x = xy.x
    var y = xy.y
    var xTile = Math.floor(x/256)
    var xPix = x - xTile * 256
    var yTile = Math.floor(y/256)
    var yPix = y - yTile * 256

    var lat = lat.toFixed(4);
    var lng = -latlng.lng().toFixed(4);

    markerTableText = lat + ' N&nbsp&nbsp ' + lng +  ' E<br>';
    addMarkerTable('Z = ' +  zoom);
    addMarkerTable('<br>' + xMapIdx + '   ' + yMapIdx)  
    addMarkerTable('<br>' + xTile + '+' + xPix + ' ' + yTile + '+' + yPix)  
    endMarkerTable();
}

//
// Bearing Between Two Points:  t=2
//             http://mathforum.org/library/drmath/view/55417.html
//     http://williams.best.vwh.net/avform.htm

var startEndLine = null;
var savedStart;
var startText = '<button style="width:200px" onclick=newStartPoint()>' + 
    ' Reset Start</button>'; 
var pi = Math.PI;

function setStart(point, latlng){
    savedStart = latlng;
    testLevel = 101;
    markerTableText = startText
    endMarkerTable();
}

function setEnd(point, latlng){
    if (startEndLine){
        map.removeOverlay(startEndLine);
    }
   startEndLine = new GPolyline([savedStart, latlng], '#ff0000', 4, 1);
   map.addOverlay(startEndLine);
   var dist = (startEndLine.getLength() * 0.000621371192).toFixed(1);  // in miles
   markerTableText = startText + '<br>' + dist + ' miles';
   var lat1 = savedStart.latRadians();
   var lon1 = savedStart.lngRadians();
   var lat2 = latlng.latRadians();
   var lon2 = latlng.lngRadians();
   var bearing = Math.atan2(Math.sin(lon1-lon2)*Math.cos(lat2),
           Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*
           Math.cos(lat2)*Math.cos(lon1-lon2))*180/pi;
   if (bearing < 0){
      bearing = -bearing;
   }else{
      bearing = 360 - bearing;
   }
   recip = (bearing + 180).toFixed() % 360;
   markerTableText += '<br> Bearing: ' + bearing.toFixed() + '/' + recip;
   endMarkerTable();
}
function newStartPoint(){
    testLevel = 2;
}

// Make a route and calulate distance

var rtSegs = [];
var rtLatlng = [];
var rtLastLatlng;
var rtMiles = 0;
var rtStartMk = 0;

function rtClear(){
   while (pathSeg = rtSegs.pop()) {
      map.removeOverlay(pathSeg);
   }     
   rtLatlng = [];
   rtSegs = [];
   rtMiles = 0;
   rtDisplay();
   testLevel = 3;
   map.removeOverlay(rtStartMk);
   rtStartmMK = 0;
   return;
}

function rtStart(loc, latlng){
     rtLastLatlng = latlng;
     rtStartMk = new GMarker(latlng, 'Start');
     rtLatlng.push(latlng);
     map.addOverlay(rtStartMk);
     rtDisplay();
     testLevel = 103;
     return;
}

function rtAddSeg(loc, latlng){
    var seg = new GPolyline([rtLastLatlng , latlng], '#ff0000', 2, 1);
    map.addOverlay(seg);
    rtSegs.push(seg)
    rtLatlng.push(latlng);
    rtLastLatlng = latlng;
    rtMiles += seg.getLength() * 0.000621371192;  // Meters to miles
    rtDisplay();
}



function rtDelSeg(){
   if (rtLatlng.length < 1) {
      return
   }
   var seg = rtSegs.pop();
   map.removeOverlay(seg);
   rtLatlng.pop();
   rtLastLatlng = rtLatlng[rtLatlng.length - 1]
   rtMiles -= seg.getLength() * 0.000621371192;
   rtDisplay();
}

function rtDisplay(){                     // Display markerTable info
    markerTableText = 'Trail Distance<br>' + 
         rtMiles.toFixed(3) + ' Miles<br>' +
        '<button style="width:200px" onclick=rtDelSeg()>' + 
         'Delete Last Segment </button><br>' +
         '<button style="width:200px" onclick=rtClear()>' + 
         'Clear</button><br>';
    endMarkerTable();
}


function displaySubMenu(type){
    startMarkerTable('auxMenu');  //aux menu is a doc id type for doc.xxx.write
    for (var i = 0; i < m2[type].length; i++){
        addMarkerTable(m2[type][i][0], m2[type][i][1]);
    }
    endMarkerTable();
}


function doMainMenu(){    // First level on left
    var text ='';
    var t1 = '<button class=b2 style="cursor:pointer;" onclick=mt("';
    var t2 = '*")>';
    var t3 = '</button><br>';
    for (type in majorTypes) {
        text += t1 + majorTypes[type][1] + t2+  majorTypes[type][0] + t3;
    }
    document.getElementById('mainMenu').innerHTML = text;
}



function drawBoxes(){
// Draw boundary
// old boundries were n= 46, s= 45.125, w = -70, e = -69.125
  var n = 46.0732
  var s = 45.1297
  var e = -69.1816
  var w = -70.0735
  var Opolyline = new GPolyline([
    new GLatLng(n, w),
    new GLatLng(s,w),
    new GLatLng(s, e),
    new GLatLng(n, e),
    new GLatLng(n, w)
        ], "#000000", 5, 1);
    map.addOverlay(Opolyline);
}

