//************************HELP

function showHelp()
{
    window.open("/help.html");
}

//************************conversions

function toDegreesMinSec(input, t)
{
    //-xx.xxxxxxxxxx° => xx° xx.x' N        
    var output = "";
    var degDec = Math.abs(input);
    var absDeg = Math.floor(Math.abs(degDec));    
    var minDec = (degDec-absDeg);
    var absMin = Math.abs(minDec*60).toFixed(1);    
    output += absDeg + "&deg; ";
    output += absMin + "' ";    
    output += direction(input, t);    
    return(output);
    
}
function toDecimalDegrees(input, t)
{
    //-xx.xxxxxxxxxx° => xx.xxxxxxxxxx° W                
    var output = Math.abs(input).toFixed(2) + "&deg; ";                
    output += direction(input, t);
    return(output);
}

function direction(input, t)
{    
    if (t == "lat")
    {
        if (parseInt(input) < 0)
        {                        
            return("S");
        }
        else if (parseInt(input) > 0)
        {                        
            return("N");
        }
    }
    else
    {
        if (parseInt(input) < 0)
        {
            return("W");
        }
        else if (parseInt(input) > 0)
        {
            return("E");
        }
    }
    return "";
}

function showPoint(e)
{
        //get the attributes for the mouseover node
        var id = String(e.getAttribute("id"));
        var x = String(e.getAttribute("gmn:x"));
        var y = String(e.getAttribute("gmn:y"));
        var user = String(e.getAttribute("gmn:user"));
        var fleet = String(e.getAttribute("gmn:fleet"));
        var color = String(e.getAttribute("gmn:color"));
        var date = String(e.getAttribute("gmn:date"));
        var time = String(e.getAttribute("gmn:time"));
        var lat = String(e.getAttribute("gmn:lat"));
        var lon = String(e.getAttribute("gmn:lon"));
        var speed = String(e.getAttribute("gmn:speed"));
        var course = String(e.getAttribute("gmn:course"));
                    
        var detail = $('detail');
        var output = createDetailDisplay( user, fleet, color, date, time, lat, lon, speed, course);
        var detailcount = 1;
        var rowcount = 1;
        var shownvessels = user;//keep track of the shown vessels if there are multiple details shown then we only want one detail of one vessel, otherwise confusing.     
        x = Math.round(parseInt(x));        
        y = Math.round(parseInt(y));         
        //get the other detail nodes        
        var points = $('points').getElementsByTagName("a");        
        
        for(var i=0; i< points.length; i++)
        {                                    
            var f = points[i];
            var id_2 = String(f.getAttribute("id"));
            var user_2 = String(f.getAttribute("gmn:user"));            
            var x_2 = String(f.getAttribute("gmn:x"));
            var y_2 = String(f.getAttribute("gmn:y"));
                        
            if (shownvessels.indexOf(user_2) < 0)//don't show the same boat more than once
            {                                                                                                                
                if ((Math.abs(x-x_2) <= 10) && (Math.abs(y-y_2) <= 10))
                {                
                    shownvessels += "," + user_2;//collect the boat list for the details shown                
                    var user_2 = String(f.getAttribute("gmn:user"));                                    
                    var fleet_2 = String(f.getAttribute("gmn:fleet"));
                    var color_2 = String(f.getAttribute("gmn:color"));
                    var date_2 = String(f.getAttribute("gmn:date"));
                    var time_2 = String(f.getAttribute("gmn:time"));
                    var lat_2 = String(f.getAttribute("gmn:lat"));
                    var lon_2 = String(f.getAttribute("gmn:lon"));
                    var speed_2 = String(f.getAttribute("gmn:speed"));
                    var course_2 = String(f.getAttribute("gmn:course"));
                
                    detailcount++;                          
                    if (detailcount == 5) //only show 4 items in the detail
                    {
                        output += "<div id=\"toomanyvessels\">There are more vessels in this area. Zoom in for more.</div>"                                                
                        break;
                    }
                    //add the next vessel
                    output += createDetailDisplay( user_2, fleet_2, color_2, date_2, time_2, lat_2, lon_2, speed_2, course_2);
                }                                
            }            
        }                      
        output += "<div style=\"clear:both\"></div>";//fix for ie floats
        detail.innerHTML = output;
        
        //now adjust for the sides and top/bottom
        
        if (detailcount > 2)
        {
            rowcount = 2;
        }
        var xoffset = (160*rowcount) + 10;
        var yoffset = (100*rowcount) + 20;
        if (rowcount > 1)
        {
            yoffset += 20;
        }
        if (x > (xp-xoffset))
        {
            x = (x-xoffset);
        }
        else
        {
            x = x+10
        }
        if (y > (yp-yoffset+138))
        {
            y = (yp-yoffset+138);           
        }        
        else
        {
            y= y+10;
        }
        detail.style.left = x +"px";        
        detail.style.top = y + "px";                      
        Element.show('detail');//finally show the detail
}

function createDetailDisplay( user, fleet, color, date, time, lat, lon, speed, course)
{
        var output = "";
        output += "<table class=\"boatinfo\" id=\"pointdetail\" cellspacing=\"0\" style=\"width: 150px; border: 1px solid #" + color + "; border-right: none\">";
        output += "<tr>";
        output += "<td style=\"background-color: #" + color+ "\" rowspan=\"7\">&nbsp;</td>";
        output += "<td class=\"boatlabel\">Vessel</td>";
        output += "<td class=\"boatvalue\">" + user + "</td>";
        output += "</tr>";
        output += "<tr>";
        output += "<td class=\"boatlabel\">Date</td>";
        output += "<td class=\"boatvalue\">" + date + "</td>";
        output += "</tr>";
        output += "<tr>";
        output += "<td class=\"boatlabel\">Time</td> ";
        output += "<td class=\"boatvalue\">" + time + " UT</td>";
        output += "</tr>";
        output += "<tr>";
        output += "<td class=\"boatlabel\">Lat</td> ";
        output += "<td class=\"boatvalue\">" + toDegreesMinSec(lat, "lat") + "</td>";
        output += "</tr>";
        output += "<tr>";
        output += "<td class=\"boatlabel\">Lon</td> ";
        output += "<td class=\"boatvalue\">" + toDegreesMinSec(lon, "lon") + "</td></tr>";
        output += "<tr>";
        output += "<td class=\"boatlabel\">Speed</td> ";
        output += "<td class=\"boatvalue\" >" + parseFloat(speed).toFixed(1) + " kt</td></tr>";
        output += "<tr>";
        output += "<td class=\"boatlabel\">Course</td>";
        output += "<td class=\"boatvalue\">" + parseFloat(course).toFixed(0) + "° T</td>";
        output += "</tr>";        
        output += "</table>"; 
        return output;
}

function hidePoint(id)
{
    $(id).innerHTML = "";
}


//************************MAP UTIL SECTION

function get_time() 
{
    boat_sel="";

    time_sel = document.forms['fleet'].show_time.value;
    track_sel = document.forms['fleet'].show_track[0].checked

    var n = 0;
    vesselCount = 0;
    var al = document.forms['fleet'].boatlist.length;
   
    if (al == undefined) 
    {
        boat_sel = document.forms['fleet'].boatlist.value+"|"+color[n]+":";
    }
    else 
    {
        while ((n) < al)
        {
        if (document.forms['fleet'].boatlist[n].checked)
            {
            boat_sel = boat_sel + document.forms['fleet'].boatlist[n].value+"|"+color[n]+":";
            vesselCount++;
            }
        n++;
        }
        boat_sel = boat_sel.substring (0, boat_sel.length-1);    
    }
}

function get_world_map()    
{        
    oldlat = 0;
    oldlon = 0;
    oldzoom = 360;
    changeMap("");
    
}

function get_first_map()    
{    
    oldlat = firstlat;
    oldlon = firstlon;
    oldzoom = firstzoom; 
    
    var al = document.forms['fleet'].boatlist;
       
    for (var i = 0; i < al.length; i++)
    {
        document.forms['fleet'].boatlist[i].checked = true;            
    }
        
    changeMap("");    
 
}

function zoom_out() 
{
    if (oldzoom >= 300) 
    {
        alert ('maximum zoom out');
        return;
    }
    var zoom = 2*oldzoom;    
    oldzoom = zoom;    
    changeMap("");
    
}

function zoom_in() 
{
    if (oldzoom <= .5) 
    {
        alert ('maximum zoom in');
        return;
    }
    var zoom = .5*oldzoom;    
    oldzoom = zoom;        
    changeMap("");
    
}

function select()
{
    $("detail").innerHTML = "";
    redraw(newlat,newlon,oldzoom);    
}

function redraw(lat,lon,zoom) 
{
    oldlon = lon;
    oldlat = lat;    
    oldzoom = zoom;    
    changeMap("")    
    
}

function googleearth()
{
    get_time();    
    mapURL = "lat="+oldlat+"&lon="+oldlon+"&zoom="+oldzoom+"&x="+xp+"&y="+yp+"&tracks="+track_sel+"&time="+time_sel+"&vessels="+boat_sel+"&fmt=kml";        
    winLoc = serverURL + pw + mapURL ;
    window.location = winLoc;

//   kmlHead = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.0"><NetworkLink><Url><href>';
//   kmlTail = '</href><refreshMode>onInterval</refreshMode><viewRefreshMode>onRequest</viewRefreshMode><refreshInterval>3600</refreshInterval></Url> </NetworkLink></kml>';
//   winLoc = kmlHead + serverURL + pw + mapURL + kmlTail;
  
//   document.write(winLoc); 
}

function refresh() 
{       
    changeMap("");
}

function changeMap(args)
{   

    get_time();    
    loading();
    mapURL = "lat="+oldlat+"&lon="+oldlon+"&zoom="+oldzoom+"&x="+xp+"&y="+yp+"&tracks="+track_sel+"&time="+time_sel+"&vessels="+boat_sel+args;        
    drawpoints();                                
}

function drawpoints(req)
{

    var g = new Date()
    var gt = g.getTime()
    var arg = pw + "lat="+oldlat+"&lon="+oldlon+"&zoom="+oldzoom+"&x="+xp+"&y="+yp+"&tracks="+track_sel+"&time="+time_sel+"&vessels="+boat_sel+"&vesselcount="+vesselCount + "&zzz=" + gt;
    var url = serverPointsURL;
        var opt = {
                    method: 'GET',                    
                    onSuccess: showResponsePoints,                                
                    onFailure: function(t) 
                    {
                      alert('Could not update map points');//'Error ' + t.status + ' -- ' + t.statusText);
                    }
                    }   
    //window.open(url + arg);
    var ajax = new Ajax.Updater('points', url + arg, opt);                                                            
}

function showResponsePoints(req)
{

    var g = new Date()
    var gt = g.getTime()    
    var resp = req.responseText;            
    $('points').innerHTML = resp;        
    map = document.getElementById('map');
    map.height = yp;
    map.width = xp;        
    map.onload = loaded;  
    map.src= serverURL + pw + mapURL + "&zzz=" + gt; 
}

function loaded()
{
    var l = $("loadcontainer");
    l.style.visibility = "hidden";
    mapURL = serverURL + mapURL;             
}

function loading()
{
    var l = $("loadcontainer");
    l.style.visibility = "visible";    
}

function login()
    {
    winLoc = "/password.html";
    newwindow = window.open(winLoc, "info", "width=480,height=340");
    newwindow.focus();
}
function contact()
    {
    winLoc = "/contact.html";
    newwindow = window.open(winLoc, "info", "width=580,height=440");
    newwindow.focus();
}

function showHelp()
	{
	winLoc = "/help.html";
	newwindow = window.open(winLoc, "help", "width=580,height=440");
	newwindow.focus();
}

function resizeWindow()
{
    if ($("selections"))
    {
       var selections = $("selections");
       selections.style.right = "10px";
       selections.style.top = "148px";
   }    
   resizeimage();
   refresh();
}

function resizeimage()
{    
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        xp = window.innerWidth;
        yp = window.innerHeight;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        xp = document.documentElement.clientWidth;
        yp = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        xp = document.body.clientWidth;
        yp = document.body.clientHeight;
      }          
     yp = yp-138;   
    
}

function show_info(sel)
{
    winLoc = "/cgi-bin/boat_info.pl?" + pw2 + "&boat="+sel;                
    newwindow = window.open(winLoc, "boat_info", "width=486,height=360");
}

function getMouseXY(e) 
{
    
    if (document.all?true:false) 
    { // grab the x-y pos.s if browser is IE	
        tempX = event.clientX;// + document.body.scrollLeft;    
        tempY = event.clientY;// + document.body.scrollTop;	
    }
     else 
    {  // grab the x-y pos.s if browser is NS		
      tempX = e.pageX						    
      tempY = e.pageY;			
    }  

            

    // catch possible negative values in NS4
    if (tempX < 0){tempX = 0}
    if (tempY < 0){tempY = 0}
    
    if (tempY > 138)
    {

        //lat = y
        //lon = x
        //FIND PIXEL RATIO
        var ratio = xp/oldzoom;    
        var centerX = (xp/2);
        var centerY = (yp/2)+138;
            
        var newX = tempX;
        var newY = tempY;
        //find the distance from center
        //how far and where is the new point compared to the center
        var distanceX = newX-centerX;
        var distanceY = (centerY-newY);
        
        newlon = (oldlon+(distanceX/ratio));
        newlat = (oldlat+(distanceY/ratio));
        
        if (newlon < -180)
        {
            newlon = ((180 + newlon) * (-1))+180;
        }     
        if (newlon > 180)
        {
            newlon = ((180 - newlon) * (-1))-180
        }     

        if(newlat > 90)
        {
            newlat = 90;
        }
        if(newlat < -90)
        {
            newlat = -90;
        }            
        
        $("lon1").innerHTML = toDegreesMinSec(newlon, "lon");
        $("lat1").innerHTML = toDegreesMinSec(newlat, "lat");    
                
    }            
      return true
}

function showFilters()
{
    var s = $('selections');        
    if (s.style.display == "none")
    {                
        Element.show('selections'); 
        s.style.right = "10px";
        s.style.top = "148px";        
        $("filters").innerHTML = "<a href=\"#\" onClick=\"javascript:showFilters();\">Hide Map Tools</a>"
    }
    else
    {            
        Element.hide('selections');        
        $("filters").innerHTML = "<a href=\"#\" onClick=\"javascript:showFilters();\">Show Map Tools</a>"
    }        
}


