//the file contains MARKER functions used by the WebGUI mapping portion of SailView
//copyright 2008 Samuel C Grant

function hideRhumbs()
{
    for( var i=0; i<rhumblines.length; i++ )
    {
        map.removeOverlay(rhumblines[i]);
    }
}

function showRhumbs(rID)
{

    for( var i=0; i<rhumblines.length; i++ )
    {
        var poly = rhumblines[i];

        if(poly.myFID == rID)
        {
                    GEvent.addListener(poly,"click",function()
                    { 
                        parent.frame2.sideBar(tips[poly.myTIPID]);
                    });

            map.addOverlay(poly);

        }
    }
}    

function createPolyline(pts,colour,width,trans,f_id,ttip) 
{
    var polyOptions = {geodesic:true};
    var polyline = new GPolyline(pts,colour,width,trans,polyOptions);
                        
    polyline.myFID = f_id;

    GEvent.addListener(polyline, 'click', function() 
    {
         //parent.frame2.sideBar(ttip);
    });
    GEvent.addListener(polyline,"mouseover",function()
    { 
        parent.frame2.sideBar(ttip);
    });

    GEvent.addListener(polyline,"mouseout",function()
    { 
        parent.frame2.sideBar(HowTo);
    });
    
    return polyline;
}


// create the static markers and set up associated events
function createSMarker(point,icontype,id,name,colr,shape,attitude,timing,sdesc,desc,lat,lon)
{
 // === create a static marker with the requested icon ===
    remote_opts = {
        "icon": marks[icontype],
        "clickable": true
        //"title": desc
    };

    var marker = new LabeledMarker(point, remote_opts);

    marker.myId       = id;
    marker.myTitle    = name;
    marker.myColor    = colr;
    marker.myShape    = shape;
    marker.myAttitude = attitude;
    marker.myTiming   = timing;
    marker.myDesc     = desc;
    marker.mySDesc    = sdesc;
    marker.myLat      = lat;
    marker.myLon      = lon;
    marker.tooltip    = '<div class="tooltip">'+sdesc+'<br />'+desc+'<br />Lat:'+lat+'<br />Lon:'+lon+'</div>';

    data[id] = marker.tooltip;

    GEvent.addListener(marker, "click", function() {
        var iwAnchor = marker.getIcon().infoWindowAnchor;
        var iconAnchor = marker.getIcon().iconAnchor;
        var offset = new GSize(iwAnchor.x-iconAnchor.x,iwAnchor.y-iconAnchor.y);
        map.openInfoWindow(marker.getLatLng(), data[id], {pixelOffset:offset});
        hideRhumbs();
        showRhumbs(marker.myId);
    });

    GEvent.addListener(map.getInfoWindow(),"closeclick", function() {
        hideRhumbs();
    });

    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker,"mouseover", function() {
        //showRhumbs(marker.myId);
        //showTooltip(marker);
    });        
    GEvent.addListener(marker,"mouseout", function() {
        //tooltip.style.visibility="hidden";
        //hideRhumbs();
    });

    Smarkers.push(marker);
    return marker;
}

// create the remote marker and set up associated events
function createMarker(point,icontype,id,name,in_html,colr)
{
 // === create a marker with the requested icon ===
    remote_opts = { 
        "icon": gicons[icontype],
        "clickable": true
        //"title": name
    };		

    var marker = new LabeledMarker(point, remote_opts);

    marker.myTitle = name;
    marker.myColor = colr;
    marker.tooltip = '<div class="tooltip">'+name+'</div>';

    if( id > 0 )
    {
        var myhtml = '<a href="javascript:myclick(' + id + ')">' + name + '</a><br>';
            side_bar_html += myhtml;
    }
    data[id] = in_html;

    GEvent.addListener(marker, "click", function() {
        var iwAnchor = marker.getIcon().infoWindowAnchor;
        var iconAnchor = marker.getIcon().iconAnchor;
        var offset = new GSize(iwAnchor.x-iconAnchor.x,iwAnchor.y-iconAnchor.y);
        map.openInfoWindow(marker.getLatLng(), data[id], {pixelOffset:offset});
    }); 

    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker,"mouseover", function() {
        showTooltip(marker);
    });        
    GEvent.addListener(marker,"mouseout", function() {
        tooltip.style.visibility="hidden"
    });

    Rmarkers.push(marker);
    return marker;
}       

//  loads all static markers from the corresponding XML files
function loadStaticMarkers(mrkID)
{
    var id;
    var lat;
    var lon;
    var point;
    var icontype;
    var marker;
    var name;
    var html;
    var Colr;
    var shape;
    var sdesc;
    var desc;
    var timing;
    var attitude;
		
    //lets do the static markers
    var request2 = GXmlHttp.create();
    request2.open("GET", StaticFile, false);

    request2.onreadystatechange = function()
    {
        if (request2.readyState == 4)
        {
            var xmlDoc2 = GXml.parse(request2.responseText);
            var statics = xmlDoc2.documentElement.getElementsByTagName("Smarker");

            for (var i = 0; i < statics.length; i++)
            {
                id       = parseInt(statics[i].getAttribute("id"));
                if( mrkID > -1 )
                {
                    if( mrkID == id )
                    {
                     icontype = statics[i].getAttribute("icontype");
                    }
                    else
                    {
                     icontype = "black_square_solid";
                    }
                }
                else
                {
                     icontype = statics[i].getAttribute("icontype");
                }
                lat      = parseFloat(statics[i].getAttribute("lat"));
                lon      = parseFloat(statics[i].getAttribute("lon"));
                name	   = statics[i].getAttribute("name");
                Colr	   = statics[i].getAttribute("color");
                shape	   = statics[i].getAttribute("shape");
                attitude = statics[i].getAttribute("attitude");
                timing   = parseFloat(statics[i].getAttribute("timing")); 
                sdesc	   = statics[i].getAttribute("sdesc");
                desc	   = statics[i].getAttribute("desc");
                point    = new GLatLng(lat,lon);

                // === create the marker, passing the icontype string ===
                marker = createSMarker(point,icontype,id,name,Colr,shape,attitude,timing,sdesc,desc,lat,lon);
            }
				
            Smgr.addMarkers(Smarkers,0,17);
            Smgr.refresh();

        }
    }
    request2.send(null);
}

//  loads all remote markers from the corresponding XML files
function loadRemoteMarkers()
{
    var id;
    var lat;
    var lon;
    var point;
    var icontype;
    var marker;
    var name;
    var html;
    var Colr;
    var shape;
    var desc;
    var timing;
    var attitude;

    //lets add the course
    addCourse();

    var bounds = new GLatLngBounds();
    var request = GXmlHttp.create();
    request.open("GET", RemoteFile, false);
    request.onreadystatechange = function()
    {
        if (request.readyState == 4)
        {
            var xmlDoc = GXml.parse(request.responseText);
            var remotes = xmlDoc.documentElement.getElementsByTagName("Rmarker");

            for (var i = 0; i < remotes.length; i++)
            {
                id       = parseInt(remotes[i].getAttribute("id"));
                icontype = remotes[i].getAttribute("icontype");
                Colr	   = remotes[i].getAttribute("color");
                lat      = parseFloat(remotes[i].getAttribute("lat"));
                lon      = parseFloat(remotes[i].getAttribute("lon"));
                name	   = remotes[i].getAttribute("name");
                html	   = remotes[i].getAttribute("html");
                point    = new GLatLng(lat,lon);

                // === create the marker, passing the icontype string ===
                marker = createMarker(point,icontype,id,name,html,Colr);

                bounds.extend(point);
            }
				
            mgr.addMarkers(Rmarkers,0,17);
            mgr.refresh();

            // ===== determine the zoom level from the bounds =====
            //map.setZoom(map.getBoundsZoomLevel(bounds));

            // ===== determine the centre from the bounds ======
            map.setCenter(bounds.getCenter());
        }
    }
    request.send(null);
	
}

// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) {
    tooltip.innerHTML = marker.tooltip;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
    var anchor=marker.getIcon().iconAnchor;
    var width=marker.getIcon().iconSize.width;
    var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
    pos.apply(tooltip);
    tooltip.style.visibility="visible";
}

// grabs new locations for all remote markers and then moves them
//       to thier new location
function moveMarkers()
{          
    var id;
    var lat;
    var lon;
    var point;   
		      
    var request = GXmlHttp.create();
    var url = MovementFile + new Date().getTime(); 
    request.open("GET", url, true); 

    request.onreadystatechange = function()
    {
        if (request.readyState == 4)
        {
            var xmlDoc = GXml.parse(request.responseText);
            var moves  = xmlDoc.documentElement.getElementsByTagName("Rmarker");

            for (var i = 0; i < moves.length; i++)
            {
                id       = parseInt(moves[i].getAttribute("id"));
                lat      = parseFloat(moves[i].getAttribute("lat"));
                lon      = parseFloat(moves[i].getAttribute("lon"));
                point    = new GLatLng(lat,lon);

                // === move the marker ===
                Rmarkers[id].setPoint(point);
            }  
            mgr.refresh();

            // update the past-track lines
            addLines(xmlDoc);

            // get the new distance and bearings for the remotes
            //updateDistBear();
        }

    }
    request.send(null);

    window.setTimeout(function(){ moveMarkers()},750);
}