// Convinience class to group functionality concerning POI presentation

var POIController = Class.create();

POIController.prototype = {
    m_poiCollection: null, // Hash
    m_tooltipId: null,
    m_annotationPOIGroupNames: null,
    m_annotations: [],
    m_eventManager: new EventHandlerManager(),
    m_onPoiUpdated: null,
    m_aggregate: false,

    initialize: function(t_poiCollection, t_tooltipId, t_aggregatePois) {
        this.m_aggregate = $defined(t_aggregatePois) ? t_aggregatePois : false;
        this.m_poiCollection = t_poiCollection;
        var t_annotationPOIGroupNames = [];
        var t_add = function(t_value) {
            t_annotationPOIGroupNames[t_annotationPOIGroupNames.length] = t_value[1].featureNumber;
        };
        this.m_poiCollection.each(t_add);
        this.m_annotationPOIGroupNames = t_annotationPOIGroupNames;

        this.m_tooltipId = t_tooltipId;

        g_kartController.addMapElementEventListener(
            "annotation:mouseClicked",
            this._annotationClicked.bindAsEventListener(this));

        g_kartController.addMapElementEventListener(
            "map:moved",
            this._reload.bind(this));

        //        g_kartController.addMapElementEventListener(
        //            "map:zoomed",
        //            this._reload.bind(this));

        this._reload();
        this.m_onPoiUpdated = this.m_eventManager.addEventType("poiUpdated");
    },

    _getPoiIconUrl: function(t_category) {
        var t_layer = this.m_poiCollection.get(t_category);
        if (t_layer != null) {
            return t_layer.iconUrl;
        }
        else {
            return "/Static/Shared/images/poigroup.gif";
        }
    },

    addEventListener: function(/*string*/t_eventName, /*function*/t_listener) {
        this.m_eventManager.addEventListener(t_eventName, t_listener);
    },

    getAnnotations: function() {
        return this.m_annotations;
    },

    // Switch POIs with type t_category on or off depending on t_checked
    poiClicked: function(t_category, t_checked) {
        this.m_poiCollection.get(t_category).selected = t_checked;
        var t_bbox = this._getViewport();

        if (t_checked || this.m_aggregate) {
            if (this.m_aggregate) //We must reload from server every time
            {
                this._clear();
                this.m_poiCollection.get(t_category).viewport = t_bbox;
                this._createRequest(this.getCheckedPoiTypes());
            }
            else //load new poi layer
            {
                this.m_poiCollection.get(t_category).viewport = t_bbox;
                this._createRequest(String(t_category));
            }
        }
        else {
            g_kartController.getMap().removeAnnotationGroup(t_category);
        }

    },

    _clear: function() {
        if (!this.m_aggregate) {
            for (i = 0; i < this.m_annotationPOIGroupNames.length; i++) {
                g_kartController.getMap().removeAnnotationGroup(this.m_annotationPOIGroupNames[i]);
            }
        }
        else {
            g_kartController.getMap().removeAnnotationGroup("pois");
        }
    },

    _reloadTimeout: null,
    _reload: function() {
        if (this._reloadTimeout != null) {
            clearTimeout(this._reloadTimeout);
        }

        var t_bbox = this._getViewport();
        this._clear();
        var t_types = this.getCheckedPoiTypes();

        this._reloadTimeout = setTimeout(this._createRequest.bind(this, t_types), 350);
    },

    _getAnnotationLink: function(t_coord) {
        var t_url = encodeURI(
	            "/System/Friluft/DirectLink/" +
	            g_kartController.getCustomerId() +
	            "?path=" + (location.host + location.pathname).replace("#", "") +
	            "&wmsId=" + null +
	            "&wmsLayersIds=" + null +
	            "&trackId=" + "" +
                "&x=" + t_coord.x +
                "&y=" + t_coord.y +
                "&zoom=" + g_kartController.getMap().getZoomLevel()
            );

        //        var t_link = "<a style='padding-left:7px;' href='#' onclick='window.open(\"" + t_url + 
        //            "\", \"\", \"width=500px, height=175px, scrollbars=1, resize=yes\", false);'>Kopier link</a>";
        var t_link = "<a style='padding-left:7px;' href='#' onclick='displayInfoWindow(\"" + t_url +
            "\", 175, 500);'>Kopier link</a>";
        return t_link;
    },

    _annotationClicked: function(t_event) {
        var t_ann = t_event.memo.annotation;
        
        if(t_ann.group == "adressestandplasserkomtek") {
            var t_content;
            var t_urlDefined = $defined(t_ann.url);
            if (t_urlDefined) {
                t_content = "<div id='annotationContentPlaceholder' style='width: 270px; overflow: auto;' ><img src='/Static/Shared/images/ui/red-spinner.gif' /> Henter informasjon... </div>";
            }
            else {
                t_content = "<div style='width: 270px; overflow: auto;'>" + t_ann.description + 
                            this._getAnnotationLink(t_ann.coordinate) + "</div>";
            }
            setLeftMenuInfo(t_content);
            t_event.stop();
            
            if (t_urlDefined) {
                new Ajax.Updater("annotationContentPlaceholder", t_ann.url);
            }
        }
        else {
            var t_tooltip = $find(this.m_tooltipId);
            t_tooltip.set_title(t_ann.title);

            var t_content;
            var t_urlDefined = $defined(t_ann.url);
            if (t_urlDefined) {
                t_content = "<div id='annotationContentPlaceholder' style='height: 169px; width: 230px; overflow: auto;' ><img src='/Static/Shared/images/ui/red-spinner.gif' /> Henter informasjon... </div>";
                t_tooltip.set_content(t_content);
            }
            else {
                t_content = "<div style='height: 169px; width: 230px; overflow: auto;'>" + t_ann.description;

                if (t_ann.group == 'measurepoints') {
                    var t_link = "<a style='padding-left:7px;' href='#' onclick='removeMeasurePoint(\"" + t_ann.id +
                    "\", \"" + this.m_tooltipId + "\");'>Fjern m&aring;lepunkt</a>";
                    t_content += t_link + "</div>";
                }
                else {
                    t_content += this._getAnnotationLink(t_ann.coordinate) + "</div>";
                }
                t_tooltip.set_content(t_content);
            }

            t_tooltip.set_content(t_content);

            t_tooltip.set_targetControl(t_event.element());
            t_tooltip.set_relativeTo(1);
            t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.TopCenter);

            var tooltipwidth = 240; // legger på 10px "slack"
            var tooltipheight = 275; // legger på 10px for "slack"

            var h = Utilities.Window.getSize().height;
            var w = Utilities.Window.getSize().width;

            var minx = 0;
            var maxx = w;
            var miny = 34;
            var maxy = h - 34;

            if (g_kartController.isLeftMenuExpanded()) {
                minx = 322;
            }

            if (g_kartController.isGlobeExpanded()) {
                maxx = w - ((w - minx) / 2);
            }

            var y_direction = "top";
            var x_direction = "center";

            if (t_event.pointerY() < tooltipheight + miny) {
                y_direction = "bottom";
            }

            if (t_event.pointerX() < (tooltipwidth + minx)) {
                x_direction = "right";
            }
            else if (t_event.pointerX() > maxx - tooltipwidth) {
                x_direction = "left";
            }

            // Set correct callout-direction
            if (y_direction == "top") {
                if (x_direction == "right") {
                    t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.TopRight);
                }
                else if (x_direction == "center") {
                    t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.TopCenter);
                }
                else if (x_direction == "left") {
                    t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.TopLeft);
                }
            }
            else if (y_direction == "bottom") {
                if (x_direction == "right") {
                    t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.BottomRight);
                }
                else if (x_direction == "center") {
                    t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.BottomCenter);
                }
                else if (x_direction == "left") {
                    t_tooltip.set_position(Telerik.Web.UI.ToolTipPosition.BottomLeft);
                }
            }

            t_tooltip.show();
            t_event.stop();

            if (t_urlDefined) {
                new Ajax.Updater("annotationContentPlaceholder", t_ann.url);
            }
            else {
                // Får friluftspoi-kategoriikon-placeholderelement fra poiprovider som må få riktig src.
                var t_headerimg = t_tooltip.get_contentElement().getElementsByTagName("img");
                if (t_headerimg != null) {
                    var i, t_length = t_headerimg.length;
                    for (i = 0; i < t_length; i++) {
                        var t_category = t_headerimg[i].category;
                        if (t_category == null) {
                            t_category = t_headerimg[i].getAttributeNode("category").value
                        }
                        t_headerimg[i].src = this._getPoiIconUrl(t_category);
                    }
                }
            }
        }
    },

    hideDescription: function(t_tooltipId) { // Lukker en hvilken som helst tooltip
        var t_tooltip = $find(t_tooltipId);
        if (t_tooltip.isVisible()) {
            t_tooltip.hide();
        }
    },

    closePOITooltip: function() { // Lukker POIControllers tooltip...
        var t_tooltip = $find(this.m_tooltipId);
        if (t_tooltip.isVisible()) {
            t_tooltip.hide();
        }
    },

    _getViewport: function() {
        var t_map = g_kartController.getMap();
        var t_w = t_map.getWidth();
        var t_h = t_map.getHeight();
        var t_min = t_map.getPixelLatLon({ x: 0, y: t_h });
        var t_max = t_map.getPixelLatLon({ x: t_w, y: 0 });

        return ({ minLat: t_min.y, minLon: t_min.x, maxLat: t_max.y, maxLon: t_max.x, height: t_h, width: t_w });
    },

    getCheckedPoiTypes: function() {
        var t_types = "";

        var t_check = function(t_value) {
            if (t_value[1].selected) {
                if (t_types != "") {
                    t_types += ",";
                }
                t_types += t_value[1].featureNumber;
            }
        };
        this.m_poiCollection.each(t_check);
        return t_types;
    },

    getPOITypesNames: function() {
        var t_types = "";

        var t_check = function(t_value) {
            if (t_value[1].selected) {
                if (t_types != "") {
                    t_types += ",";
                }
                t_types += t_value[1].featureNumber + "|" + t_value[1].featureName;
            }
        };
        this.m_poiCollection.each(t_check);
        return t_types;
    },

    update: function(t_types, t_checked) {
        this._clear();

        if (t_types != "") {
            var t_typesarray = t_types.split(",");
            var i, t_length = t_typesarray.length;
            for (i = 0; i < t_length; i++) {
                this.m_poiCollection.get(t_typesarray[i]).selected = t_checked;
            }

            this._createRequest(this.getCheckedPoiTypes());
        }
    },

    _createRequest: function(t_types) {

        //g_kartController.getMap().clearAnnotations()
        // Fjern POI-annotations fra "gammel bbox"
        if (t_types != "") {
            this._fetchPOIFromProxy(t_types);
        }
    },

    _fetchPOIFromProxy: function(t_types) {
        if (g_kartController.getDisplay2D()) {
            if (t_types != "") {
                var t_bbox = this._getViewport();
                var t_bottomLeft = g_kartController.getMap().decimalDegreesToUTM(new Coordinate(t_bbox.minLon, t_bbox.minLat));
                var t_topRight = g_kartController.getMap().decimalDegreesToUTM(new Coordinate(t_bbox.maxLon, t_bbox.maxLat));
                var t_mapDimensions = g_kartController.getMapPaneDimensions();

                Norkart.Web.Fag.Applications.MapPortal.AJAX.WebServices.Friluft.FriluftPOIProxy.getPOIAggregated(
                        t_types,
                        t_bottomLeft.x,
                        t_bottomLeft.y,
                        t_topRight.x,
                        t_topRight.y,
                        this.m_aggregate,
                        t_mapDimensions.width,
                        t_mapDimensions.height,
                        21, 21,
                        this._onPOISuccess,
                        this._onPOIFailed,
                        this);
            }
        }
    },

    // TODO: Change the "../../"-reference in image path
    _onPOISuccess: function(t_value, t_thisbind) {
        var t_groupByCategory = t_thisbind.m_aggregate ? false : true;

        t_thisbind.m_annotations = [];
        try {
            if ($defined(t_value)) {
                var t_map = g_kartController.getMap();
                var i, t_length = t_value.length;
                var t_kartController = g_kartController;
                for (i = 0; i < t_length; i++) {
                    var t_title = t_value[i].Name;
                    var t_description = "<div>" + t_value[i].Description + "</div>";
                    var t_annotation = new Annotation(
					        new Coordinate(t_value[i].Coordinate.Easting, t_value[i].Coordinate.Northing),
					        t_title,
					        t_description,
					        t_thisbind._getPoiIconUrl(t_value[i].Category),
					        0, 0, 0, 0,
					        (t_groupByCategory ?
					            t_value[i].Category :
					            "pois"));

                    //Create annotation id. this is required by globe, and can eventually be used
                    //to do a selective add and remove of annotations.
                    t_annotation.id = i;
                    //					    t_annotation.title + "_" + 
                    //					    t_annotation.group + "_" + 
                    //					    t_annotation.coordinate.x + "_" + 
                    //					    t_annotation.coordinate.y;

                    t_map.addAnnotation(t_annotation);
                    // stops click-events on annotations from bubbling. When clicking an annotation which
                    // is placed over a getfeature-layer, annotation get priority.
                    Event.observe(t_annotation.element, 'click', function(e) { e.stop() });
                    t_thisbind.m_annotations.push(t_annotation);
                }
            }
        }
        catch (e)
        { }

        t_thisbind.m_onPoiUpdated.fire(t_thisbind.m_annotations);
    },

    _onPOIFailed: function(t_value, t_thisbind) {
        //wedebug.log("poi", "Error communicating with FriluftPOIProxy.","error");
        t_thisbind.m_annotations = [];
        t_thisbind.m_onPoiUpdated.fire(t_thisbind.m_annotations);
    },

    getPOIInBBox: function(e) {
        var t_bbox;
        if (e.memo) {
            t_bbox = e.memo.boundingbox;
            DrawingControl.drawBoundingBox(t_bbox, "gpxbbox");
            saveGPSPOIAreaFile(this.getCheckedPoiTypes(), t_bbox.left, t_bbox.bottom, t_bbox.right, t_bbox.top);
        }
    }
}
