﻿var g_mapSurface;
var g_inOperation=false;
var g_trackPreviousCoordinate = null;

var g_routeHighlightTimeout = null;
var g_rectTreeReady = false;

var g_friluftRectangleTreeController;

var g_TT_Debug = false;
if( g_TT_Debug )
{
    var t_debugSlots = [
        $dom("div").$attr("id", "tt_slot1"),
        $dom("div").$attr("id", "tt_slot2"),
        $dom("div").$attr("id", "tt_slot3"),
        $dom("div").$attr("id", "tt_slot4"),
        $dom("div").$attr("id", "tt_slot5")
    ];

    var t_body = $$("body")[0];
    window.ttDebugDiv = $dom("div", null, t_debugSlots, t_body).$attr("id", "ttDebugDiv");
    window.ttDebugDiv.setStyle(
        {
            "position":"absolute",
            "left" : "50px",
            "top" : "50px",
            "width" : "200px",
            "backgroundColor" : "White",
            "zIndex" : 50000
        });
}

$attemptInvoke(
    function() {
        g_mapSurface=$("mapsurface");

        g_kartController.addMapElementEventListener(
            "map:grabbed",
            function(t_event) {
                g_inOperation=true;
            });
        g_kartController.addMapElementEventListener(
            "map:moved",
            function(t_event) {
                g_inOperation=false;
            });
        g_kartController.addMapElementEventListener(
            "map:zoomed",
            function(t_event) {
                g_inOperation=false;
            });
        g_kartController.addMapElementEventListener(
            "map:mouseOut",
            function(t_event) {
                g_inOperation=false;
            });
        g_kartController.addMapElementEventListener(
            "map:mouseClicked",
            function(t_event) {
                g_inOperation=false;
            });
        g_kartController.addMapElementEventListener(
            "map:mouseMoved",
            function(t_event)
            {
                if( !g_rectTreeReady )
                {
                    g_rectTreeReady = $defined(g_friluftRectangleTreeController);
                }
            
                if( g_rectTreeReady && g_kartController.getMap().getState() == 'default' )
                {
                    if( !g_inOperation )
                    {
                        if( _findSegmentTimeout != null )
                        {
                            clearTimeout(_findSegmentTimeout);
                        }
                        _findSegmentTimeout = setTimeout(
                            _findSegments.bind(window, t_event),
                            15);
                    }
                }
            });
    }
);

var _findSegmentTimeout = null;
function _findSegments(t_event) {
    var t_found=false;
    var t_ignoreEvent = false;
    if (!g_inOperation) {
        var t_map=g_kartController.getMap();
        var coords=t_event.memo.mouseMapCoords;

        //Check prev coordinate to prevent IE from constantly firing this code. 
        //(mousemove never stops firing in IE)
        if (g_trackPreviousCoordinate==null||
            (g_trackPreviousCoordinate.x!=coords.x||
            g_trackPreviousCoordinate.y!=coords.y)) {

            if( g_TT_Debug )
            {
                //write nr. of search calls to debug.
                var t_slot = $("tt_slot1");
                if( t_slot.backingBean == null )
                    t_slot.backingBean = {counter : 0};
                    
                t_slot.backingBean.counter++;
                t_slot.update("Antall søk: " + t_slot.backingBean.counter);
            }

            if( g_routeHighlightTimeout != null )
            {
                try
                {
                    clearTimeout(g_routeHighlightTimeout);
                }
                catch(e){}
            }

            var t_shortestDistance=Number.MAX_VALUE;
            var t_mapBBox=t_map.getBoundingBox();
            var t_width=t_map.getWidth();
            var t_mpp=(t_mapBBox.right-t_mapBBox.left)/t_width;

            //247848,07 6627152,39 280827,11 6676538,29
            var t_mousePointBBox=new BoundingBox(
                coords.x-t_mpp*5,
                coords.y-t_mpp*5,
                coords.x+t_mpp*5,
                coords.y+t_mpp*5);

            var t_sections=g_friluftRectangleTreeController.findAll(t_mousePointBBox);
            var i, t_length=t_sections.length;
            //var t_logdiv=$("offsetDiv")  ;
            
            if( g_TT_Debug )
            {
                //write nr. of search calls to debug.
                var t_slot = $("tt_slot2");
                t_slot.update("Antall segmenter: " + t_length);
            }
            
            for (i=0; i<t_length&&!t_found; i++) {
                var t_segmentCoordinates=t_sections[i].getCoordinatesWithOffset();
                var t_offset = t_sections[i].getOffset();
                var t_mouseX=coords.x-t_offset.x;
                var t_mouseY=coords.y-t_offset.y;
                
                var j, t_length2=t_segmentCoordinates.length; //Field from TrackSegment.
                for (j=0; j<t_length2-3; j+=2) {
                    var t_distance=Utilities.Karto.linePointDistance(
                        t_segmentCoordinates[j],
                        t_segmentCoordinates[j+1],
                        t_segmentCoordinates[j+2],
                        t_segmentCoordinates[j+3],
                        t_mouseX,
                        t_mouseY,
                        true);

                    //t_logdiv.update("max=" + t_mpp*5 + "<br/>x="+(coords.x-t_offsetX)+"<br/>y="+(coords.y-t_offsetY));
       
                    if (t_distance < t_mpp * 5) {
                        g_mapSurface.style.cursor = "pointer";
                        t_found = true;
                        var memo = {
                            marked : t_found
                        };

                        document.fire('tracktooltip:ontrackhighlighted', memo);
                        
                        g_routeHighlightTimeout = setTimeout(
                            _highlightTrackSegment.bind(window, t_sections[i], t_mpp),
                            35
                        );
                        break;
                    }
                }
            }
            g_trackPreviousCoordinate=t_event.memo.mouseMapCoords;
        }
        else 
        { 
            t_ignoreEvent = true;
        }
    }

    if ( !t_found && !t_ignoreEvent ) 
    {
        g_mapSurface.style.cursor="";
        DrawingControl.removeDrawingGroup(g_drawingHighlightId);
        
        g_currentFeatureHashCode = -1;
        
        var memo = {
            marked : t_found
        };

        document.fire('tracktooltip:ontrackhighlighted', memo);
    }
}

var TrackTooltip = {

    highlightTrack : function (t_wmsId, t_wmsLayersIds, t_hash)
    {
        var t_map = g_kartController.getMap();
        var t_shortestDistance=Number.MAX_VALUE;
        var t_mapBBox=t_map.getBoundingBox();
        var t_width=t_map.getWidth();
        var t_mpp=(t_mapBBox.right-t_mapBBox.left)/t_width;
        
        if( t_wmsLayersIds != null )
        {
            var i, t_idsLength = t_wmsLayersIds.length;
            for(i=0;i<t_idsLength;i++)
            {
                var t_items = g_friluftRectangleTreeController.items(t_wmsLayersIds[i]);
                var j, t_length = t_items.length;
                for( j=0; j<t_length; j++ )
                {
                    if( t_items[j].getHashCode() == t_hash )
                    {
                        _highlightTrackSegment(t_items[j], t_mpp);
                        break;
                    }
                }
            }
        }
    }
}


var g_currentFeatureHashCode = -1;
var g_drawingHighlightId = "trackhighlight";
function _highlightTrackSegment(t_segment, t_tolerance)
{
    if(g_currentFeatureHashCode == t_segment.getHashCode())
    {
        return;
    }

    g_currentFeatureHashCode = t_segment.getHashCode();;
    var t_coords = t_segment.getTrackCoordinates(t_tolerance);
    
    var t_canvas = g_kartController.getMap().getDrawCanvas();
    if( t_canvas == null )
    {
        t_canvas = new WAPICanvas();
        g_kartController.getMap().addDrawCanvas(t_canvas);
    }
    else
    {
        t_canvas.clear(g_drawingHighlightId);
    }
    var t_line = new PolyLine([], {'rgba' : "rgba(0,0,0,1)", 'lineWidth' : 4} );
    var i, t_length = t_coords.length;
    
    if( g_TT_Debug )
    {
        //write nr. of search calls to debug.
        var t_slot = $("tt_slot3");
        t_slot.update("Antall koordinater: " + t_length);
        
        var t_str = "";
        t_coords.each(function(t_c){t_str+=t_c.x + ", " + t_c.y + " ";});
        t_slot = $("tt_slot4");
        t_slot.update("Koordinater: " + t_str);
    }
    
    for(i=0; i<t_length; i++)
    {
        t_line.addPoint(t_coords[i]);
    }
    t_canvas.addPolyLine(t_line, g_drawingHighlightId);
}
