// (c) 2006 Horizon Marine, Inc.  Marion, MA.  All rights reserved.
// 
// This code was developed by Horizon Marine, Inc. and is protected by
// copyright law. You may not copy, retransmit, archive, modify, distribute,
// or exploit any content on iBoatTrack.com. Redistribution of any content
// over any network, construction of a database, or offer for sale of any
// content is prohibited without written permission from Horizon Marine, Inc.
// Content that appears on this website is for personal use only, commercial
// use of the content is strictly prohibited.

var downx   = 0;
var downy   = 0;
var currx   = 0;
var curry   = 0;
var m_stat = 'up';

function leadingZero(x) {
   neg = '';
   if (x < 0) {
     neg = '-';
   }
   x = Math.abs(x);
   return (x>9)?(neg+x):(neg+'0'+x);
}

function dd_to_dms(dd,p) {
  d  = Math.floor(dd);
  dd = (dd - d) * 60;
  m  = Math.floor(dd);
  dd = (dd - m) * 60;
  s  = Math.round(dd * Math.pow(10,p)) / Math.pow(10,p);
  return(leadingZero(d)+'&deg;'+leadingZero(m)+'\''+leadingZero(s)+'"');
}

function get_map_action() {
  var actions = new Array('zoom_in','zoom_out','pan','query','measure');
  for (i = 0; i < actions.length; i++) {
    el = top.document.getElementById('radio_'+actions[i]);
    if (el.checked) {
      return actions[i];
    }
  }
}

function go(s) {
  eval(s);
}

// Keep track of whether or not this is a double click.
var dc = false;

function dblclk(e) {
  if(navigator.appName == 'Netscape') {
    downx  = e.pageX;
    downy  = e.pageY;
    button = e.which;
  }
  else {
    downx  = event.clientX;
    downy  = event.clientY;
    button = event.button;
  }

  rbox = document.getElementById("rboxov");
  rbox.style.left   = downx - document.map_form.img_size_w.value / 8;
  rbox.style.top    = downy - document.map_form.img_size_h.value / 8;
  rbox.style.width  = document.map_form.img_size_w.value / 4;
  rbox.style.height = document.map_form.img_size_h.value / 4;
  rbox.style.visibility = 'visible';
  m_stat = 'down';
  dc = true;

  // Go ahead and process the zoom action.
  upxy(e);
  dc = false;
  return;
}

function dblclk_to_scale(e) {
  if(navigator.appName == 'Netscape') {
    downx  = e.pageX;
    downy  = e.pageY;
    button = e.which;
  }
  else {
    downx  = event.clientX;
    downy  = event.clientY;
    button = event.button;
  }

  // Calculate the geo coords for this click.
  scalex = document.map_form.map_ext_x.value * 2 / document.map_form.img_size_w.value;
  ulx = parseFloat(document.map_form.x.value)-(scalex*(document.map_form.img_size_w.value / 2));
  ddx = parseFloat(parseFloat(ulx) + (scalex * downx));
  scaley = document.map_form.map_ext_y.value * 2 / document.map_form.img_size_h.value;
  uly = parseFloat(document.map_form.y.value)+(scaley*(document.map_form.img_size_h.value / 2));
  ddy = uly - (scaley * downy);

  var z = get_next_zoom(document.forms[0].zoom_level.value);
  document.forms[0].zoom_level.value = z;
  hilite_zoom(z);
  top.center_and_zoom_map(ddx,ddy,top.size_ext_x[top.frames['mapdisplay'].document.map_form.img_size_w.value] / z, -1, false, z);

  dc = false;
  return;
}

function downxy(e) {
  if(navigator.appName == 'Netscape') {
    downx  = e.pageX;
    downy  = e.pageY;
    button = e.which;
  }
  else {
    downx  = event.clientX;
    downy  = event.clientY;
    button = event.button;
  }

  map_act = get_map_action();

  // only support left click
  if (button == '1') {
    m_stat = 'down';
    if (map_act == 'zoom_in' || map_act == 'zoom_out' || map_act == 'query') {
      rbox = document.getElementById("rboxov");
      rbox.style.left   = downx;
      rbox.style.top    = downy;
      rbox.style.width  = 0;
      rbox.style.height = 0;
      rbox.style.visibility = 'visible';
    }
    else if (map_act == 'measure') {
      // Draw the marker dots.
      rad = 4;
      jg.setColor('red');
      jg.fillEllipse(downx-rad,downy-rad,2*rad,2*rad);
      jg.setColor('black');
      jg.drawEllipse(downx-rad,downy-rad,2*rad,2*rad);

      // geospatial coords
      scalex = document.map_form.map_ext_x.value * 2 / document.map_form.img_size_w.value;
      ulx = parseFloat(document.map_form.x.value)-(scalex*(document.map_form.img_size_w.value / 2));
      ddx = parseFloat(parseFloat(ulx) + (scalex * currx));
      scaley = document.map_form.map_ext_y.value * 2 / document.map_form.img_size_h.value;
      uly = parseFloat(document.map_form.y.value)+(scaley*(document.map_form.img_size_h.value / 2));
      ddy = uly - (scaley * curry);

      // Draw a connector line and dist. bet. points if we need to.
      if (last_measure_click[0] != 0 && last_measure_click[1] != 0) {
        // connector
        jg.setColor('blue');
        jg.drawLine(last_measure_click[0],last_measure_click[1],downx,downy);

        // distance
        jg.setColor('black');
        call('./proj?positions='+last_measure_dd[1]+' '+last_measure_dd[0]+' '+ddy+' '+ddx+'&nm&js'
          +'&x='+parseInt(Math.abs(downx+last_measure_click[0])/2)
          +'&y='+parseInt(Math.abs(downy+last_measure_click[1])/2)
          +'&running_total='+total_dist
          ,null,go);
      }
      else {
        jg.paint();
      }
      last_measure_click = Array(downx,downy);
      last_measure_dd    = Array(ddx,ddy);
    }
    else {
      last_measure_click = Array(0,0);
      last_measure_dd    = Array(0,0);
    }
  }
}

function upxy(e) {
  map_act = get_map_action();

  // If we're mesauring, don't do anything special when mouse up.
  if (map_act == 'measure') {
    m_stat = 'up';
    return;
  }
  
  if (m_stat == 'down') {
    m_stat = 'up';
    rbox   = document.getElementById("rboxov");
    rbox.style.visibility = 'hidden';
    ex     = parseFloat(document.map_form.map_ext_x.value);
    ey     = parseFloat(document.map_form.map_ext_y.value);
    if (ex > ey) {
      y_ratio = ex / ey;
      x_ratio = 1;
    }
    else {
      y_ratio = 1;
      x_ratio = ey / ex;
    }
    scalex = ex * 2 / document.map_form.img_size_w.value;
    scaley = ey * 2 / document.map_form.img_size_h.value;
    ulx    = parseFloat(document.map_form.x.value) - (scalex * (document.map_form.img_size_w.value / 2));
    uly    = parseFloat(document.map_form.y.value) + (scaley * (document.map_form.img_size_h.value / 2));
    if (parseFloat(rbox.style.width) > parseFloat(rbox.style.height)) {
      maxside = parseFloat(rbox.style.width);
    }
    else {
      maxside = parseFloat(rbox.style.height);
    }
  }

  if (map_act == 'zoom_in' || dc) {
    newex = maxside * scalex / 2 / x_ratio;
    newey = maxside * scaley / 2 / y_ratio;
  }
  else if (map_act == 'pan') {
    newex = ex; 
    newey = ey;
  }
  else if (map_act == 'zoom_out') {
    newex = ex * (ex / (maxside * scalex / 2 / x_ratio)); 
    newey = ey * (ey / (maxside * scaley / 2 / y_ratio));
  }

  if (top.wp_edit_flag) {
    ddx = parseFloat(parseFloat(ulx) + (scalex * currx));
    ddy = uly - (scaley * curry);
    call('./wp_edit?n=' + top.wp_edit_c + '&lon=' + ddx + '&lat=' + ddy+'&rand='+Math.random(),null,go);
    top.wp_edit_flag = false;
    return;
  }

  if ((map_act == 'query' || (map_act == 'pan' && currx == downx && curry == downy)) && ! dc) {
    return;
  }

  // return the action back to the map controls
  document.map_form.target = top.frames['mapdisplay'].name;
  document.map_form.action = "genmap";

  if ((map_act.indexOf('zoom') >= 0 && maxside != 0) || map_act == 'pan') {
    x1 = parseFloat(rbox.style.left);
    y1 = parseFloat(rbox.style.top);
    x2 = x1 + parseFloat(rbox.style.width);
    y2 = y1 + parseFloat(rbox.style.height);
   
    if (map_act == 'zoom_in' || dc) {
      document.map_form.x.value = ulx + (scalex * x1) + newex;
      document.map_form.y.value = uly - (scaley * y1) - newey;
      document.map_form.map_ext_x.value = newex;
      document.map_form.map_ext_y.value = newey;
    } 
    else if (map_act == 'pan') {
      document.map_form.x.value = parseFloat(document.map_form.x.value) - (scalex * (currx - downx));
      document.map_form.y.value = parseFloat(document.map_form.y.value) + (scaley * (curry - downy));
    }
    else if (map_act == 'zoom_out') {
      document.map_form.x.value = ulx + scalex * (x1 +((x2 - x1) / 2));
      document.map_form.y.value = uly - scaley * (y1 +((y2 - y1) / 2));
      document.map_form.map_ext_x.value = newex;
      document.map_form.map_ext_y.value = newey;
    }
    document.map_form.submit();
  }
}

function mm(e) {
  map_act = get_map_action();

  if(navigator.appName == 'Netscape') {
    currx = parseFloat(e.pageX);
    curry = parseFloat(e.pageY);
  }
  else {
    currx = parseFloat(event.clientX);
    curry = parseFloat(event.clientY);
  }
  
  if (m_stat == 'down') {
    if (map_act == 'pan') {
      ml = document.getElementById("map");
      ml.style.left = currx - downx;
      ml.style.top  = curry - downy;
    }
    else if (map_act == 'zoom_in' || map_act == 'zoom_out') {
      rbox = document.getElementById("rboxov");
      if (currx > downx) {
         rbox.style.left  = downx;
         rbox.style.width = currx - downx;
       }
      else {
         rbox.style.left  = currx;
         rbox.style.width = downx - currx;
       }
      if (curry > downy) {
        rbox.style.top    = downy;
        rbox.style.height = curry - downy;
      }
      else {
        rbox.style.top    = curry;
        rbox.style.height = downy - curry;
      }
    }
  }

  // Always update the coords.
  scalex = document.map_form.map_ext_x.value * 2 / document.map_form.img_size_w.value;
  ulx = parseFloat(document.map_form.x.value)-(scalex*(document.map_form.img_size_w.value / 2));
  ddx = -parseFloat(parseFloat(ulx) + (scalex * currx));
  scaley = document.map_form.map_ext_y.value * 2 / document.map_form.img_size_h.value;
  uly = parseFloat(document.map_form.y.value)+(scaley*(document.map_form.img_size_h.value / 2));
  ddy = uly - (scaley * curry);
  // Figure out whether to display N/S E/W.
  n = " N ";
  if (ddy < 0) {
    n = " S ";
    ddy = Math.abs(ddy);
  }
  w = " W ";
  if (ddx < 0) {
    w = " E ";
    ddx = Math.abs(ddx);
  }

  top.cursor_dd  = ddy.toFixed(4) + '&deg;' + n + ddx.toFixed(4) + '&deg;' + w.replace(/ $/,'');;
  top.cursor_dms = dd_to_dms(ddy.toFixed(2),0) + n + dd_to_dms(ddx.toFixed(2),0) + w;

  if (top.active_u == 'dd') {
    top.document.getElementById('coords').innerHTML = top.cursor_dd;
  }
  else {
    top.document.getElementById('coords').innerHTML = top.cursor_dms;
  }
}

function go_maptech(lon,lat,trackback_url,descrip) {
  u = 'http://mapserver.maptech.com/bp/mapserver/index.cfm?scale=2160000&zoom=50&type=0&icon=sailboatE_color_32_41_-20_-16|' + lat + '|' + lon + '|' + trackback_url + '|^' + descrip + '&lat=' + lat + '&lon=' + lon;
  window.open(u,'_blank');
}

function go_gmap(lon,lat,trackback_url,descrip) {
  u = 'http://maps.google.com/maps?q=' + lat + ',+' + lon + '(' + descrip + ')'
    +'&ll=' + lat + ',' + lon + '&z=13&hl=en&t=h&ie=UTF8';
  window.open(u,'_blank');
}

function wp_mkpath() {
  if (document.main.wp_num_pts.value != -1 && (document.main.wp_start_lon.value == '' || document.main.wp_start_lat.value == '' || document.main.wp_end_lon.value == '' || document.main.wp_end_lat.value == '' || document.main.wp_num_pts.value == '')) {
    alert('Please provide a value for all waypoint fields.');
    return;
  }
  call('./wp_mkpath?start_lon=' + document.main.wp_start_lon.value + '&start_lat=' + document.main.wp_start_lat.value + '&end_lon=' + document.main.wp_end_lon.value + '&end_lat=' + document.main.wp_end_lat.value + '&num_pts=' + document.main.wp_num_pts.value+'&rand='+Math.random(),null,go);
}

function wp_rmpt(n) {
  call('./wp_rmpt?n=' + n+'&rand='+Math.random(),null,go);
}

function wp_edit(n) {
  wp_edit_flag = true;
  wp_edit_c    = n;
}

function wp_mkmanpath(a) {
  call('./wp_mkmanpath?p=' + a.join(",")  +'&rand='+Math.random(),null,go);
}

function wp_save_base() {
  if (!(0.1 <= document.main.wp_base_spd.value && document.main.wp_base_spd.value <= 20)) {
    alert('An invalid base speed was entered (ok: 0.1 - 20 kts).');
    return;
  }
  if (!(0.1 <= document.main.wp_base_draft.value && document.main.wp_base_draft.value <= 50)) {
    alert('An invalid base draft was entered (ok: 0.1 - 50 meters).');
    return;
  }
  if (!(0.1 <= document.main.wp_base_fwy.value && document.main.wp_base_fwy.value <= 200)) {
    alert('An invalid base freeway tolerance was entered (ok: 0.1 - 200 nm).');
    return;
  }

  call('./wp_save_base?s=' + document.main.wp_base_spd.value + '&d=' + document.main.wp_base_draft.value + '&f=' + document.main.wp_base_fwy.value,null,go);
}

function wp_buffer_clear() {
  document.main.wp_buffer.value = '';
}

function wp_buffer_run() {
  if (top.document.main.wp_mode[1].checked) {
    call('./wp_label?p='+document.main.wp_buffer.value,null,go);
  }
  else if (top.document.main.wp_mode[2].checked) {
    top.go_anim_wp();
  }
  else {
    alert('Running the buffer is only supported in the Label mode.');
  }
}

function wp_go(n) {
  if (!top.document.main.wp_mode) {
    return;
  }
  if (top.document.main.wp_mode[1].checked) {
    // count how many spaces are in the buffer
    p = top.document.main.wp_buffer.value.split(' ');
    top.document.main.wp_buffer.value += n + '.' + p.length + ' ';
  }
  else if (top.document.main.wp_mode[2].checked) {
    top.document.main.wp_buffer.value += n + "\n";
  }
}

function refresh_wp_table(ar,refresh) {
  var tab = top.document.getElementById('wp_table');
  var t   = tab.getElementsByTagName('tbody')[0]
  // clear out old data
  while (t.rows.length > 0) {
    t.deleteRow(t.rows.length-1);
  }

  // put a msg if no data
  if (ar.length <= 2) {
    tr = document.createElement('tr');
    td = document.createElement('td');
    td.align = 'center';
    td.innerHTML = '<span style="font-size:10;">No waypoints exist.</span>';
    tr.appendChild(td);
    t.appendChild(tr);
    if (refresh) {
      top.refresh_map();
    }
    return;
  }

  // headers
  tr = document.createElement('tr');
  // del
  td = document.createElement('td');
  td.align   = 'center';
  td.innerHTML = '<span style="font-size:10;">Del</span>';
  tr.appendChild(td);
  // #
  td = document.createElement('td');
  td.align   = 'center';
  td.innerHTML = '<a href="javascript:wp_sort()"><span style="font-size:10;">ID</span></a>';
  tr.appendChild(td);
  // mv
  td = document.createElement('td');
  td.align   = 'center';
  td.innerHTML = '<span style="font-size:10;">Edit</span>';
  tr.appendChild(td);
  // ins above
  td = document.createElement('td');
  td.colSpan = 2;
  td.align   = 'center';
  td.innerHTML = '<span style="font-size:10;">Insert</span>';
  tr.appendChild(td);
  // zoom
  td = document.createElement('td');
  td.align   = 'center';
  td.innerHTML = '<span style="font-size:10;">Zoom</span>';
  tr.appendChild(td);
  t.appendChild(tr);

  // build the idx array to determine how to loop
  var idx = new Array();
  if (wp_sort_flag == 1) {
    for (i = 0; i < ar.length - 2; i = i + 2) {
      idx.push(i/2+1);
    }
  }
  else {
    for (i = ar.length - 2; i > 0; i = i - 2) {
      idx.push(i/2);
    }
  }

  // add the new
  for (i = 0; i < idx.length; i++) {
    c = idx[i];
    tr = document.createElement('tr');
    // del
    td = document.createElement('td');
    a = document.createElement('a');
    a.href = 'javascript:wp_rmpt("' + c + '")';
    img = document.createElement('img');
    img.src = top.img_rm.src;
    img.style.border = 'none';
    a.appendChild(img);
    td.appendChild(a);
    tr.appendChild(td);
    // id
    td = document.createElement('td');
    td.align = 'right';
    td.innerHTML = '&nbsp;' + c + '&nbsp;';
    tr.appendChild(td);
    // mv
    td = document.createElement('td');
    a = document.createElement('a');
    a.href = 'javascript:wp_edit("' + c + '")';
    img = document.createElement('img');
    img.src = top.img_edit.src;
    img.style.border = 'none';
    a.appendChild(img);
    td.appendChild(a);
    tr.appendChild(td);
    // ins above
    td = document.createElement('td');
    a = document.createElement('a');
    a.href = 'javascript:wp_edit("' + (c-0.5*wp_sort_flag) + '")';
    img = document.createElement('img');
    img.src = top.img_up.src;
    img.style.border = 'none';
    a.appendChild(img);
    td.appendChild(a);
    tr.appendChild(td);
    // ins below
    td = document.createElement('td');
    a = document.createElement('a');
    a.href = 'javascript:wp_edit("' + (c*1+0.5*wp_sort_flag) + '")';
    img = document.createElement('img');
    img.src = top.img_down.src;
    img.style.border = 'none';
    a.appendChild(img);
    td.appendChild(a);
    tr.appendChild(td);
    // zoom
    td = document.createElement('td');
    td.align = 'center';
    a = document.createElement('a');
    a.href = 'javascript:center_and_zoom_map(' + ar[2*(c-1)] + ',' + ar[2*c-1] + ',size_ext_x[top.frames[\"mapdisplay\"].document.map_form.img_size_w.value]/wp_zoom,-1,false,wp_zoom)';
    img = document.createElement('img');
    img.src = top.img_zoom.src;
    img.style.border = 'none';
    a.appendChild(img);
    td.appendChild(a);
    tr.appendChild(td);
    t.appendChild(tr);
  }

  document.getElementById('running_tots').innerHTML = ar[ar.length-1] + ' nm<br>' + ar[ar.length-2] + ' days';

  if (refresh) {
    top.refresh_map();
  }

  // save arr for later
  wp_arr = ar;
}

function wp_import() {
  window.open('./wp_import','wp_import');
}

function wp_export() {
  window.open('./wp_export','wp_export');
}

function wp_report() {
  window.open('./wp_report?wp_start=1','wp_report');
}

function wp_sort() {
  wp_sort_flag = -1 * wp_sort_flag;
  refresh_wp_table(wp_arr,false);  
}

function info(l,cb) {
  document.getElementById('info_'+l).src = top.img_spinner.src;
  call('/ogc/wxs?metadata=1&LAYERS='+l+'&lmap='+l+'&time_sec='+top.frames['mapdisplay'].document.map_form.time.value+'&cbox='+cb,null,go);
}
