/*
(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 myKaMap = myKaNavigator = myKaQuery = null;
var myBoatManager = null;

function myOnLoad()
{
    var centerAndScale = '-86.66775,24.51755,7500000';
    initDHTMLAPI();
    myKaMap = new kaMap( 'viewport' );
    myKaMap.initialize('', '', centerAndScale); // mapName,extents,centerAndScale
    myBoatManager = new hmBoatManager( myKaMap );
    var myKaScalebar = new kaScalebar( myKaMap, 'scalebar' );
    var myKaLegend = new kaLegend( myKaMap, 'legend', false );
    var myKaKeymap = new kaKeymap( myKaMap, 'keymap' );
    myKaMap.registerForEvent( KAMAP_INITIALIZED, null, myInitialized );
    myKaMap.registerForEvent( KAMAP_MAP_INITIALIZED, null, myMapInitialized );
    myKaMap.registerForEvent( KAMAP_SCALE_CHANGED, null, myScaleChanged );
    myKaMap.registerForEvent( KAMAP_QUERY, null, myQuery );

    myKaNavigator = new kaNavigator( myKaMap );
    myKaNavigator.activate();

    myKaQuery = new kaQuery( myKaMap, KAMAP_RECT_QUERY );
    myProj = new Proj('EPSG:4269');
    
    ckButtons();
    drawPage();
}

/**
 * event handler for KAMAP_INITIALIZED.
 *
 * at this point, ka-Map! knows what map files are available and we have
 * access to them.
 */
function myInitialized()
{
    //get list of maps and populate the maps select box
    var aMaps = myKaMap.getMaps();
    var oSelect = document.forms[0].maps;
    var j = 0;
    var opt = new Option( 'select a map', '', true, true );
    oSelect[j++] = opt;
    for(var i in aMaps)
    {
        oSelect[j++] = new Option(aMaps[i].title,aMaps[i].name,false,false);
    }
}

/**
 * event handler for KAMAP_MAP_INITIALIZED
 *
 * the scales are put into a select ... this will be used for zooming
 */
function myMapInitialized( eventID, mapName )
{
    //update the scales select
    var currentMap = myKaMap.getCurrentMap();
    var scales = currentMap.getScales();
    oSelect = document.forms[0].scales;
    while( oSelect.options[0] ) oSelect.options[0] = null;
    j=0;

    var nice_zoom_str = new Array ( );
    nice_zoom_str[7500000] = "1x";
    nice_zoom_str[2500000] = "3x";
    nice_zoom_str[1000000] = "10x";
    nice_zoom_str[333000]  = "20x";
    

    for(var i in scales)
    {
        oSelect.options[j++] = new Option(nice_zoom_str[scales[i]],scales[i],false,false);
    }

    hmProcessStartEndTime();
}

/************************************************************************/
/*                              hmProcessBoats                          */
/*                                                                      */
/*      Call back function called after the server is queried           */
/*      (related to function hmGetBoats                                 */
/************************************************************************/
function hmProcessBoats(szValue)
{
    var d = new Date();
    eval(szValue);
    document.forms[0].lease_areas_goto.options[0].text = '--- Pick a boat ---';
    var sel = document.forms[0].class_goto;
    sel.options[sel.options.length] = new Option('ALL','ALL',false,true);
    myBoatManager.aClasses.sort();
    var niceClasses = new Array ();
    for (var i in myBoatManager.aClasses){
      niceClasses.push(i);
    }
    niceClasses.sort();
    for (var i in niceClasses){
      sel.options[sel.options.length] = new Option(niceClasses[i],niceClasses[i],false,false);
    }   
    document.forms[0].class_goto.options[0].text = '';
    myKaMap.triggerEvent( HM_BOATS_INITIALIZED );
    myKaMap.triggerEvent(HM_TIME_CHANGED, myBoatManager.nCurrentTime );
    myToggleWatch(-999,true,false);
}

/**
 * called when kaMap tells us the scale has changed
 */
function myScaleChanged( eventID, scale )
{
    //todo: update scale select and enable/disable zoomin/zoomout
    var oSelect = document.forms[0].scales;
    for (var i=0; i<oSelect.options.length; i++)
    {
        if (oSelect.options[i].value == scale)
        {
            oSelect.options[i].selected = true;
            document.forms[0].zoomout.disabled = (i==0);
            document.forms[0].zoomin.disabled = (i==oSelect.options.length - 1);
        }
    }
}

/**
 * called when the user changes scales.  This will cause the map to zoom to
 * the new scale and trigger a bunch of events, including:
 * KAMAP_SCALE_CHANGED
 * KAMAP_EXTENTS_CHANGED
 */
function mySetScale( scale )
{
    myKaMap.zoomToScale( scale );
}

/**
 * called when the map selection changes due to the user selecting a new map.
 * By calling myKaMap.selectMap, this triggers the KAMAP_MAP_INITIALIZED event
 * after the new map is initialized which, in turn, causes testMapInitialized
 * to be called
 */
function mySetMap( name )
{
    myKaMap.selectMap( name );
}

function myGotoTime( timestamp )
{
    myKaMap.gotoTime( timestamp );
}

function myGotoBoat( n, gotoBoat )
{
    myKaMap.gotoBoat( n, gotoBoat );
}

function myGotoClass( myBoatsOnly )
{
    if (myBoatsOnly) {
      sel = document.forms[0].class_goto;
      sel.selectedIndex = 0;
    }
    myBoatManager.selectClass();
}

function myToggleTrack( b, setupOnly, forceOn, forceOff )
{
    myKaMap.toggleTrack( b, setupOnly, forceOn, forceOff );
}

function myToggleWatch( b, setupOnly, forceOn )
{
    myKaMap.ToggleWatch( b, setupOnly, forceOn );
}

function myQuery( eventID, queryType, coords )
{
    var currentMap = myKaMap.getCurrentMap();
    var layers = currentMap.getLayers();
    var qLayers = "";
    
    // find the layer checkboxes
    for(var i=0;i<document.getElementsByTagName('input').length;i++)
    {
      if(/CB/i.test(document.getElementsByTagName('input')[i].name))
      {
        var sb=document.getElementsByTagName('input')[i];
        if (sb.checked == true)
          qLayers = qLayers+","+sb.name;
      }
    }
    
    //the timestamp of the current map
    theDate = new Date(document.forms[0].time_stamp_js_epoch.value * 1);
    mm = new String(theDate.getUTCMonth()+1);
    mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
    dd = new String(theDate.getUTCDate());
    dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
    hh = new String(theDate.getUTCHours());
    hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
    var timestamp = 
      theDate.getUTCFullYear()
      +"_"+mm
      +"_"+dd
      +"_"+hh;

    if (queryType == KAMAP_RECT_QUERY)
    {
      winRef = window.open('query.phtml?qLayers='+qLayers+'&x='+coords[0]+'&y='+coords[1]+'&x1='+coords[2]+'&y1='+coords[3]+'&ts='+timestamp,'query_res','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=775,height=300');
      winRef.focus();
    }
    else {
      winRef = window.open('query.phtml?qLayers='+qLayers+'&x='+coords[0]+'&y='+coords[1]+'&ts='+timestamp,'query_res','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=775,height=300');
      winRef.focus();
    }
}

function myZoomIn()
{
    myKaMap.zoomIn();
}

function myZoomOut()
{
    myKaMap.zoomOut();
}

function myZoomTo( lon, lat )
{
    myKaMap.zoomTo( lon, lat );
}

function toggleReference(obj)
{
    if (obj.innerHTML == 'hide reference')
    {
        obj.innerHTML = 'show reference';
        var d = getObject('reference');
        d.top = "-356px";
    }
    else
    {
        obj.innerHTML = 'hide reference';
        var d = getObject('reference');
        d.top = "0px";
    }
}

function dialogToggle( href, szObj )
{
    var obj = getObject(szObj);
    if (obj.display == 'none')
    {
        obj.display = 'block';
        href.childNodes[0].src = 'images/dialog_shut.png';

    }
    else
    {
        obj.display = 'none';
        href.childNodes[0].src = 'images/dialog_open.png';
    }
}
function drawPage()
{
    var browserWidth = getInsideWindowWidth();
    var browserHeight = getInsideWindowHeight();

    var viewport = getRawObject('viewport');

    viewport.style.width = (browserWidth-3- -2) + "px";
    viewport.style.height = (browserHeight-3- 129) + "px";

    myKaMap.resize();
}

function ckButtons () {
  }

function bakDay (syncAll) {
  if (document.forms[0].time_stamp_js_epoch.value * 1 - 1000*3600 < document.forms[0].time_stamp_js_epoch_min.value * 1) {
    return;
  }
  document.forms[0].time_stamp_js_epoch.value = document.forms[0].time_stamp_js_epoch.value * 1 - 1000*3600;
  theDate = new Date(document.forms[0].time_stamp_js_epoch.value * 1);
  mm = new String(theDate.getUTCMonth()+1);
  mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
  hh = new String(theDate.getUTCHours());
  hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
  document.forms[0].time_stamp.value = 
    theDate.getUTCFullYear()
    +"-"+mm
    +"-"+dd
    +" "+hh+":00 GMT";

  // now sync the display date    
  var Mon3 = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var span = getRawObject('time_stamp_display');
  theDate.setUTCHours(theDate.getUTCHours() - 5);
  mm = new String(theDate.getUTCMonth());
  mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
  hh = new String(theDate.getUTCHours());
  hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
  span.innerHTML = 
    Mon3[Number(mm)]
    +" "+dd
    +" "+hh+":00 CDT";
  
  syncToCalendar();
  ckButtons();
  hmTimeClicked(0);
  if (syncAll) {
    myGotoTime();
  }
}

function fwdDay (syncAll) {
  if (document.forms[0].time_stamp_js_epoch.value * 1 + 1000*3600 > document.forms[0].time_stamp_js_epoch_max.value * 1) {
    return;
  }
  document.forms[0].time_stamp_js_epoch.value = document.forms[0].time_stamp_js_epoch.value * 1 + 1000*3600;
  theDate = new Date(document.forms[0].time_stamp_js_epoch.value * 1);
  mm = new String(theDate.getUTCMonth()+1);
  mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
  hh = new String(theDate.getUTCHours());
  hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
  document.forms[0].time_stamp.value = 
    theDate.getUTCFullYear()
    +"-"+mm
    +"-"+dd
    +" "+hh+":00 GMT";
    
  // now sync the display date    
  var Mon3 = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var span = getRawObject('time_stamp_display');
  theDate.setUTCHours(theDate.getUTCHours() - 5);
  mm = new String(theDate.getUTCMonth());
  mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
  hh = new String(theDate.getUTCHours());
  hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
  span.innerHTML = 
    Mon3[Number(mm)]
    +" "+dd
    +" "+hh+":00 CDT";
    
  syncToCalendar();
  ckButtons();
  hmTimeClicked(1);
  if (syncAll) {
    myGotoTime();
  }
}

function syncToCalendar () {
  var month_names = new Array ( );
  month_names[month_names.length] = "January";
  month_names[month_names.length] = "February";
  month_names[month_names.length] = "March";
  month_names[month_names.length] = "April";
  month_names[month_names.length] = "May";
  month_names[month_names.length] = "June";
  month_names[month_names.length] = "July";
  month_names[month_names.length] = "August";
  month_names[month_names.length] = "September";
  month_names[month_names.length] = "October";
  month_names[month_names.length] = "November";
  month_names[month_names.length] = "December";

  theDate = new Date(document.forms[0].time_stamp_js_epoch.value * 1);
  
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');

}

function syncFromCalendar () {
  theDate = new Date(Number(document.forms[0].time_stamp_js_epoch.value) * 1);

  mm = new String(theDate.getUTCMonth()+1);
  mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
  hh = new String(theDate.getUTCHours());
  hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
  document.forms[0].time_stamp.value = 
    theDate.getUTCFullYear()
    +"-"+mm
    +"-"+dd
    +" "+hh+":00 GMT";
  newDate2 = new Date(mm+"/"+dd+"/"+theDate.getUTCFullYear()+" "+hh+":00 GMT");  
  document.forms[0].time_stamp_js_epoch.value = newDate2.getTime();
  
  document.forms[0].HMTimeSelector.selectedIndex =
    findTimeSelMatchIdx(theDate.getUTCFullYear()+"-"+mm+"-"+dd+" "+hh+":00 GMT");

  // now sync the display date    
  var Mon3 = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var span = getRawObject('time_stamp_display');
  theDate.setUTCHours(theDate.getUTCHours() - 5);
  mm = new String(theDate.getUTCMonth());
  mm = mm.replace(/(\b)(\d)\b/g, '$10$2');
  dd = new String(theDate.getUTCDate());
  dd = dd.replace(/(\b)(\d)\b/g, '$10$2');
  hh = new String(theDate.getUTCHours());
  hh = hh.replace(/(\b)(\d)\b/g, '$10$2');
  span.innerHTML = 
    Mon3[Number(mm)]
    +" "+dd
    +" "+hh+":00 CDT";
  
  ckButtons();
  hmTimeClicked(-1);
  myGotoTime();
};  

function findTimeSelMatchIdx (ts) {
  var sel = document.forms[0].HMTimeSelector;
  for (i = 0; i < sel.options.length; i++) {
    if (sel.options[i].text == ts) {
      return(i);
    }
  }
  return 0;
} 

var timeout;
function anim (a, r) {
  if (r == 1 && timeout) {
    clearTimeout(timeout);
  }
  if (a == -1) {
    // Stop animating if we're at the beginning of the road.
    if (document.forms[0].time_stamp_js_epoch.value * 1 - 1000*3600 < document.forms[0].time_stamp_js_epoch_min.value * 1) {
      timeout = setTimeout('anim(0,1)',600);
    }
    else {
      bakDay(true);
      timeout = setTimeout('anim(-1,0)',600);
    }
  }
  else if (a == 1) {
    // Stop animating if we're at the end of the road.
    if (document.forms[0].time_stamp_js_epoch.value * 1 + 1000*3600 > document.forms[0].time_stamp_js_epoch_max.value * 1) {
      timeout = setTimeout('anim(0,1)',600);
    }
    else {
      fwdDay(true);
      timeout = setTimeout('anim(1,0)',600);
    }
  }
  else {
    clearTimeout(timeout);
    myGotoTime();
  }
}

function toggleMyBoatsViz () {
  el = document.getElementById('showHideMyBoats');
  if (document.getElementById("my_boats_div").style.visibility == "hidden") {
    document.getElementById("my_boats_div").style.visibility = "visible";
    el.innerHTML = '&nbsp;<a href="#" onClick="toggleMyBoatsViz();">Hide</a>';
  } 
  else {
    document.getElementById("my_boats_div").style.visibility = "hidden";
    el.innerHTML = '<span class="mapTipsRow1">&nbsp;<a href="#" onClick="toggleMyBoatsViz();">Restore</a>&nbsp;&nbsp;BOAT CONTROL PANEL&nbsp;</span>';
  }
}
