var mf; //map form
var cvs; //canvas
var base; //holds map
var drag; //for panning
var box; //drawing box
var load; //loading message
var lgd; //legend
var extents = new Array('0');
var curr_ext = 0;
var curr_top = 0;
var curr_left = 0;

function gotoError() {
  window.location = errPage;
}

// Page load / unload
function loadPage() {
  mf = document.forms['mapserv'];
  cvs = xGetElementById('canvas');
  base = xGetElementById('base');
  drag = new dragger('action');
  box = xGetElementById('box');
  load = xGetElementById('loading');
  xOpacity('action', 0);
  xOpacity(box, 0.5); //let user decide opacity? also set opacity for watermark! and fix watermark for advanced canvas
  if (iLgd && cLgd) lgd = new xCollapsible('legendlayers', cLgdCol);
  setTool(mf.tool.value);
  if (adv_app) pageLoadAdvanced();
  if (typeof pageLoadPopup != 'undefined') pageLoadPopup();
  if (document.forms['modis_date'] &&(typeof initModis != 'undefined')) initModis();
  xMoveTo(load, (xWidth(cvs) / 2) - (xWidth(load) / 2), (xHeight(cvs) / 2) - (xHeight(load) / 2));
  xHeight('dycontainer2', getBottom('dycontainer2') - xTop('dycontainer2') + 20); //what if no dycontainer2?
  xHeight('mapboddie', getBottom('mapboddie') - xPageY('mapboddie')); //what if no dycontainer2?
  if (bmVars) {
    pageLoadBMLoad();
    getMap(false);
  } else {
    if (iLgd) initLegend();
    getMap(true);
  }
}
function unloadPage() {
  if (cLgd) lgd.onUnload();
}
function initLegend() {
  var lyrs = dlayers.split(',');
  var i, ln, el;
  for (i in lyrs) {
    ln = trim(lyrs[i]);
    if (eval('mf.layer_' + ln)) eval ('mf.layer_' + ln + '.checked = true');
    else if (eval('mf.group_' + ln)) eval ('mf.group_' + ln + '.checked = true');
  }
  if (typeof(dtlayers) != 'undefined') {
    lyrs = dtlayers.split(',');
    for (i in lyrs) {
      ln = trim(lyrs[i]);
      if (eval('mf.tlayer_' + ln)) eval ('mf.tlayer_' + ln + '.checked = true');
      else if (eval('mf.tgroup_' + ln)) eval ('mf.tgroup_' + ln + '.checked = true');
    }
  }
}
function clearDiv(d) {
  xInnerHtml(d, '');
}
function showDiv(d, s) {
  if (s) xStyle('visibility', 'visible', d);
  else xStyle('visibility', 'hidden', d);
}
function showDiv2(d) {
  e = xGetElementById(d);
  if (e.style.visibility == 'hidden') {
    xStyle('visibility', 'visible', e);
    xStyle('height', 'auto', e);
  } else {
    xStyle('visibility', 'hidden', e);
    xStyle('height', '0', e);
  }
}
function getMap(newExtent, msg) {
  showDiv(load, true);
  var data = new Object();
  data.updateExtent = newExtent;
  if (msg) data.msg = msg;
  var qs = formToQuery(mf);
  if (newExtent) qs += '&refresh=no';
  else qs += '&refresh=yes';
  var xhr = new xHttpRequest();
  if (!xhr.send('POST', map_lib, qs, xhrTo, false, false, data, onMapResponse)) gotoError();
  xhr = null;
}
function onMapResponse(req, status, data) {
  if (status == 0) {
    var json = JSON.parse(req.responseText);
    if (json.ok) {
      if (json.extent) mf.extent.value = json.extent;
      if (json.imgUrl) {
        var oldImgs = xGetElementsByClassName('mapimg', base, 'img');
        var newImg = document.createElement('img');
        newImg.setAttribute('src', json.imgUrl);
        xAddClass(newImg, 'mapimg');
        xMoveTo(newImg, curr_left, curr_top);
        base.appendChild(newImg);
        setTimeout(function() {for (var i in oldImgs) base.removeChild(oldImgs[i]);}, 100);
      }
      if (json.tImgUrl) onAdvancedMapResponse(json, data);
      if (data.updateExtent) updateExtents(json.extent);
      if (json.refUrl && ((el = xGetElementById('refmap')) != null)) el.setAttribute('src', json.refUrl);
      if (json.scalebar && ((el = xGetElementById('scale')) != null)) {
        el.setAttribute('src', json.scalebar.url);
        el.setAttribute('width', json.scalebar.width);
        el.setAttribute('height', json.scalebar.height);
      }
      showDiv(load, false);
      if (json.scale) alert(json.scale);
      if (data.msg) alert(data.msg);
    } else alert(json.err);
  } else gotoError();
}
function formToQuery(f) {
  if (!(f = xGetElementById(f))) return null;
  var qs = ''
  for (var i=0; i<f.elements.length; i++) {
    ele = f.elements[i];
    if (ele.name != '') {
      if (ele.type == 'checkbox') {
        if (ele.checked) qs += ele.name + '=' + escape(ele.value) + '&';
      } else if (ele.type == 'radio') {
        if (ele.checked) qs += ele.name + '=' + escape(ele.value) + '&';
      } else qs += ele.name + '=' + escape(ele.value) + '&';
    }
  }
  return qs.substr(0, qs.length - 1);
}
function goRefresh(dl) {
  if (dl != null) mf.drawlayers.value = dl;
  getMap(false);
  if (adv_app) mf.drawlayers.value = 'all';
}
function goFull() {
  mf.full_extent.value = 'yes';
  getMap(true);
  mf.full_extent.value = 'no';
}
function enableZoom() {
  drag.enableDrag(zoomStart, zoomGo, zoomEnd);
  showDiv(box, false);
}
function zoomStart(el, x, y, ev) {
  el.minx = xPageX(el)
  el.maxx = el.minx + xWidth(el);
  el.miny = xPageY(el);
  el.maxy = el.miny + xHeight(el);
  el.x0 = x;
  el.y0 = y;
  xResizeTo(box, 2, 2);
  xMoveTo(box, x - el.minx, y - el.miny);
  showDiv(box, true);
}
function zoomGo(el, dx, dy, ev) {
  var bl, bt, bw, bh;
  var px = ev.pageX;
  var py = ev.pageY;
  dx = px - el.x0;
  dy = py - el.y0;
  if (dx >= 0) {
    bl = el.x0 - el.minx;
    if (px > el.maxx) bw = el.maxx - el.x0;
    else bw = dx;
  } else {
    if (px < el.minx) {
      bl = 0;
      bw = el.x0 - el.minx;
    } else {
      bl = px - el.minx;
      bw = -dx;
    }
  }
  if (dy >= 0) {
    bt = el.y0 - el.miny;
    if (py > el.maxy) bh = el.maxy - el.y0;
    else bh = dy;
  } else {
    if (py < el.miny) {
      bt = 0;
      bh = el.y0 - el.miny;
    } else {
      bt = py - el.miny;
      bh = -dy;
    }
  }
  xMoveTo(box, bl, bt);
  xResizeTo(box, bw, bh);
}
function zoomEnd(el, x, y, ev) {
  mf.zoombox.value = xLeft(box) + ' ' + xTop(box) + ' ' + xWidth(box) + ' ' + xHeight(box);
  showDiv(box, false);
  getMap(true);
}

function enablePan() {
  drag.enableDrag(panStart, panGo, panEnd);
}
function panStart(el, x, y, ev) {
  el.sx = x;
  el.sy = y;
}
function panGo(el, dx, dy, ev) {
  xMoveTo(base, xLeft(base) + dx, xTop(base) + dy);
  if (adv_app) xMoveTo(tbase, xLeft(tbase) + dx, xTop(tbase) + dy);
}
function panEnd(el, x, y, ev) {
  dx = x - el.sx;
  dy = y - el.sy;
  mf.pan.value = dx + ' ' + dy;
  curr_top = curr_top - dy;
  curr_left = curr_left - dx;
  getMap(true);
}
function panner(dir) {
  mf.pandir.value = dir;
  getMap(true);
  mf.pandir.value = '';
}

function setTool(tool) {
  drag.disableDrag();
  mf.tool.value = tool;
  if (xGetElementById('tool_zoom_in')) {
    if (tool == 'zoom_in') {
      enableZoom();
      setToolStatus('tool_zoom_in', 'selected');
      xStyle('cursor', 'crosshair', 'action');
    } else setToolStatus('tool_zoom_in', 'enabled');
  }
  if (xGetElementById('tool_zoom_out')) {
    if (tool == 'zoom_out') {
      enableZoom();
      setToolStatus('tool_zoom_out', 'selected');
      xStyle('cursor', 'crosshair', 'action');
    } else setToolStatus('tool_zoom_out', 'enabled');
  }
  if (xGetElementById('tool_pan')) {
    if (tool == 'pan') {
      enablePan();
      setToolStatus('tool_pan', 'selected');
      xStyle('cursor', 'move', 'action');
    } else setToolStatus('tool_pan', 'enabled');
  }
  if (xGetElementById('tool_info')) {
    if (tool == 'info') {
      enableInfo();
      setToolStatus('tool_info', 'selected');
      xStyle('cursor', 'help', 'action');
    } else {
      disableInfo();
      setToolStatus('tool_info', 'enabled');
    }
  }
  if (xGetElementById('tool_search')) {
    if (tool == 'search') {
      enableSearch();
      setToolStatus('tool_search', 'selected');
      xStyle('cursor', 'pointer', 'action');
    } else {
      disableSearch();
      setToolStatus('tool_search', 'enabled');
    }
  }
  if (xGetElementById('tool_selectbox')) {
    if (tool == 'selectbox') {
      enableSelect();
      setToolStatus('tool_selectbox', 'selected');
      xStyle('cursor', 'crosshair', 'action');
    } else setToolStatus('tool_selectbox', 'enabled');
  }
  for (var i=1; i<=nCTools; i++) eval('disableCustom'+i+'()');
}
function setTextToolStatus(tool, stat) {
  el = xGetElementById(tool);
  if (el != null) {
    if (stat == 'selected') el.className = 'button yes';
    else if (stat == 'enabled') el.className = 'button no';
    else if (stat == 'disabled') el.className = 'button no nogo';
  }
}
function setImageToolStatus(tool, stat) {
  el = xGetElementById(tool);
  if (el != null) {
    if (stat == 'selected') el.setAttribute('src', eval(tool + '_on'));
    else if (stat == 'enabled') el.setAttribute('src', eval(tool + '_off'));
    else if (stat == 'disabled') el.setAttribute('src', eval(tool + '_na'));
  }
}
function updateExtents(extent) {
  if ((curr_ext != 0) || (extents[0] != '0')) curr_ext++;
  extents[curr_ext] = extent;
  enableExtentTools();
}
function enableExtentTools() {
  if (curr_ext > 0) setToolStatus('tool_back_extent', 'enabled');
  else setToolStatus('tool_back_extent', 'disabled');
  if (curr_ext < (extents.length - 1)) setToolStatus('tool_next_extent', 'enabled');
  else setToolStatus('tool_next_extent', 'disabled');
}
function goBack() {
  if (curr_ext > 0) {
    curr_ext--;
    mf.extent.value = extents[curr_ext];
    getMap(false);
    enableExtentTools();
  }
}
function goNext() {
  if (curr_ext < (extents.length - 1)) {
    curr_ext++;
    mf.extent.value = extents[curr_ext];
    getMap(false);
    enableExtentTools();
  }
}
function toggleUnits() {
  xInnerHtml('scale_units', mf.sunits.value + ' units');
  if (mf.sunits.value == 'Metric') mf.sunits.value = 'English';
  else mf.sunits.value = 'Metric';
  mf.refresh_scale.value = 'yes';
  getMap(false);
  mf.refresh_scale.value = 'no';
}
function getBottom(el) {
  var b = null;
  if (el = xGetElementById(el)) {
    var els = xGetElementsByClassName('checkpos', el);
    if (els.length > 0) {
      b = xPageY(els[0]) + xHeight(els[0]);
      for (var i in els) b = Math.max(b, xPageY(els[i]) + xHeight(els[i]));
    }
  }
  return b;
}
function toggleView() {
  showDiv(load, true);
  var qs = formToQuery(mf) + '&rmval_ini=&rmval_drawlayers=';
  var xhr = new xHttpRequest();
  if (!xhr.send('POST', '/lib/savesession.php', qs, xhrTo, false, false, null, onToggleResponse)) gotoError();
  xhr = null;
}
function onToggleResponse(req, status, obj) {
  if (status == 0) {
    var json = JSON.parse(req.responseText);
    if (json.ok) {
      if (adv_app) window.location = 'basic.phtml?';
      else window.location = 'advanced.phtml?';
    } else alert(json.err);
  } else gotoError();
}
function showPage(url, wWidth, wHeight) {
  var win = window.open(url, null, "width="+wWidth+",height="+wHeight+",resizable=yes,scrollbars=yes,toolbar=no,location=no,menubar=no,status=no");
  win.focus();
}
function saveMap() {
  var win = window.open('/lib/saveimg.phtml?img=' + xGetElementsByClassName('mapimg', base, 'img')[0].src);
  win.focus();
}
