﻿/// <reference path="VEJS/VeJavaScriptIntellisenseHelper.js" />

var RB_theMainContainer;
var RB_mapDv = "";
var RB_map = null; //= new VEMap("myMap");
var RB_tempPushPin = null// = new VEShape();
var RB_filterTags = "";
var RB_bestview = false;
var RB_bestview_ignore = false;
var RB_reset = true;
var RB_areaID;
var RB_displayEvents = true;
var RB_displayArea = true;
var RB_jsonLoading = false;
var RB_blockOver = false;
var RB_jsonArea = null;
var RB_jsonEvent = null;
var RB_jsonPushpin = null;
var RB_clusterZoomLevel = 15;

var RB_mapEventLayer = null;
var RB_mapFavLayer = null;
var RB_mapAreaLayer = null;
var RB_eventSID = null;

var RB_mapFind = false;

function RB_initMap(element) {
    if (!Array.indexOf) {
        Array.prototype.indexOf = function(obj) {
            for (var i = 0; i < this.length; i++) {
                if (this[i] == obj) {
                    return i;
                }
            }
            return -1;
        }
    }

    var dv = document.getElementById(element);


    if (!dv) {
        alert("Element with ID=" + element + " was not found");
        return;
    }

    RB_mapDv = element;

    RB_map = new VEMap(element);

    var ve_LatLong = new VELatLong(40.633197, -8.659598, 0, VEAltitudeMode.RelativeToGround);

    RB_map.SetDashboardSize(VEDashboardSize.Small);
   
    RB_map.LoadMap(ve_LatLong, 0);

    RB_map.SetTileBuffer(0);
    RB_map.Hide3DNavigationControl();
    RB_map.HideFindControl();
    RB_map.HideMiniMap();
    RB_map.HideTrafficLegend();
    RB_map.SetZoomLevel(3);

    RB_map.SetMapStyle(VEMapStyle.Road);
    RB_map.SetDashboardSize(VEDashboardSize.Small);
    RB_map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);
    RB_map.SetZoomLevel(3);

    RB_map.AttachEvent("onmouseup", RB_onMapClick);
    RB_map.AttachEvent("onmouseover", RB_onMapOver);
    RB_map.AttachEvent("onmouseout", RB_onMapOut);
    RB_map.AttachEvent("oninitmode", RB_resetMapLayers);
    RB_map.AttachEvent("onendpan", RB_onMapPan);
    RB_map.AttachEvent("onstartzoom", RB_onMapStartZoom);
    RB_map.AttachEvent("onendzoom", RB_onMapEndZoom);
    RB_map.AttachEvent("onresize", RB_resetMapLayers);
    RB_map.AttachEvent("onchangemapstyle", RB_resetMapLayers);
    RB_map.AttachEvent("onerror", RB_onMapError);


    RB_map.ShowMessageBox = false;
    RB_map.EnableShapeDisplayThreshold(false);
    RB_map.SetFailedShapeRequest(VEFailedShapeRequest.DoNotDraw);
    RB_map.SetShapesAccuracy(VEShapeAccuracy.Pushpin);
    RB_map.SetShapesAccuracyRequestLimit(25);

}

function RB_initMapLatLon(element, lat, lon, alt) {
    RB_initMap(element);
    if (RB_map == null)
        return;

    if (alt < 2)
        alt = 2;

    var ve_LatLong = new VELatLong(lat, lon, alt, VEAltitudeMode.RelativeToGround);
    RB_map.SetCenterAndZoom(ve_LatLong, alt);
    RB_displayEvents = true;
}

function RB_initMapArea(element, aid) {
    RB_areaID = aid;

    RB_initMap(element);
    if (RB_map == null)
        return;

    RB_bestview = true;
    RB_displayArea = true;
    RB_resetMapLayers(null);
}


function RB_searchMapKey(e) {
    if (RB_map == null)
        return true;

    var keychar = window.event ? e.keyCode : e.which;

    if (keychar == 13) {
        var txt = e.srcElement;

        if (txt.value != "") {
            RB_map.Find("", txt.value);

            return false;
        }
    }
    return true;
}

function RB_searchMap(txt) {
    if (RB_map == null)
        return false;

    if (txt) {
        if (txt.value != "") {
            RB_map.Find("", txt.value);
            RB_mapFind = true;
            RB_blockOver = true;

            if (RB_tempPushPin != null) {
                RB_map.DeleteShape(RB_tempPushPin);
                RB_tempPushPin = null;
            }

            var p = window;
            var vellpx = RB_map.GetCenter();

            RB_tempPushPin = new VEShape(VEShapeType.Pushpin, vellpx);
            RB_map.AddShape(RB_tempPushPin);
            RB_tempPushPin.UserDate = "temp";
            RB_tempPushPin.SetDescription("<div id='RB_Shape_" + RB_tempPushPin.GetID() + "'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></div>");
            RB_tempPushPin.Show();
            RB_mapFind = false;
        }
    }
    return false;
}


function RB_centerZoomMap(lat, lon, zoom) {
    if (RB_map == null)
        return;

    if (lat == null || lon == null)
        return;

    lat = lat.replace(',', '.');
    lon = lon.replace(',', '.');

    var center = new VELatLong(lat, lon, 0, VEAltitudeMode.RelativeToGround);

    if (zoom >= 0 && RB_map.GetZoomLevel() != zoom) {
        RB_map.SetZoomLevel(zoom);
    }

    RB_map.SetCenter(center);
    RB_resetMapLayers(null);

    return false;
}

function RB_centerMap(lat, lon) {
    centerZoomMap(lat, lon, -1);
}

function RB_isGuid(a) {
    try {
        return a.match("^(([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12})$");
    } catch (ex) {
        return false;
    }
}



function RB_toogleLayer(sender, id) {
    var index = 0;

    if (RB_map == null)
        return;

    if (sender == null)
        return;

    var originalUrl = sender.src;
    var sep = originalUrl.lastIndexOf("_");
    var originalUrlBase = originalUrl.substr(0, sep);


    var finalUrl = originalUrlBase;

    var pos = RB_filterTags.indexOf(id);
    if (pos == -1) {
        if (RB_filterTags.length > 0)
            RB_filterTags += ",";
        RB_filterTags += id;

        finalUrl += "_on.png";
        sender.setAttribute("suffix", "_on.png");

    } else {
        RB_filterTags = RB_filterTags.replace("," + id, "");
        RB_filterTags = RB_filterTags.replace(id, "");
        finalUrl += "_off.png";
        sender.setAttribute("suffix", "_off.png");
    }

    sender.src = finalUrl;
    RB_resetMapLayers(null);

    return false;
}

function RB_resetMapLayers(ev) {
    if (RB_map == null)
        return;

    if (RB_reset == false) {
        RB_reset = true;
        return;
    }

    if (RB_tempPushPin) {
        RB_tempPushPin = null;
    }
    if (RB_mapFind) {
        RB_mapFind = false;
    }

    var counter = document.getElementById("RB_MapCounter");

    if (counter) {
        counter.innerText = "";
    }

    var url;
    var options = "";
    if (typeof (RB_UserID) != "undefined") {
        options += "&user=" + RB_UserID;
    }

    if (typeof (RB_UserKey) != "undefined") {
        options += "&key=" + RB_UserKey;
    }

    if (typeof (RB_OwnEvents) != "undefined") {
        options += "&own=true";
    }

    var mapRec = RB_map.GetMapView();


    if (RB_eventSID != null) {
        RB_mapLoadingStart(RB_mapDv);
        url = RB_getSiteRoot() + "/ws/event.ashx?opt=1&zoom=" + RB_map.GetZoomLevel() + "&esid="+RB_eventSID + "&tags=" + RB_filterTags;
        RB_jsonEvent = RB_GetDataJson(url + options, "RB_onMapLayerLoad", RB_jsonEvent);
     

    } else {
        if (RB_displayArea && RB_getUserIsAuth()) {
            if (RB_areaID) {

                url = RB_getSiteRoot() + "/ws/area.ashx?id=" + RB_areaID;
                RB_mapLoadingStart(RB_mapDv);
                RB_jsonArea = RB_GetDataJson(url + options, "RB_onMapLayerLoad", RB_jsonArea);

            } else {
                var zoom = RB_map.GetZoomLevel();
                if (zoom > 12) {
                    if (RB_bestview == true) {
                        url = RB_getSiteRoot() + "/ws/area.ashx?zoom=10&lat_min=30&long_min=-10&lat_max=50&long_max=-6";
                    }
                    else {
                        url = RB_getSiteRoot() + "/ws/area.ashx?zoom=" + zoom + "&lat_min=" + mapRec.BottomRightLatLong.Latitude + "&long_min=" + mapRec.TopLeftLatLong.Longitude + "&lat_max=" + mapRec.TopLeftLatLong.Latitude + "&long_max=" + mapRec.BottomRightLatLong.Longitude;
                    }

                    RB_mapLoadingStart(RB_mapDv);
                    RB_jsonArea = RB_GetDataJson(url + options, "RB_onMapLayerLoad", RB_jsonArea);
                }
            }
        }

        if (RB_displayEvents) {
            RB_mapLoadingStart(RB_mapDv);
            url = RB_getSiteRoot() + "/ws/event.ashx?opt=1&zoom=" + RB_map.GetZoomLevel() + "&lat_min=" + mapRec.BottomRightLatLong.Latitude + "&long_min=" + mapRec.TopLeftLatLong.Longitude + "&lat_max=" + mapRec.TopLeftLatLong.Latitude + "&long_max=" + mapRec.BottomRightLatLong.Longitude + "&tags=" + RB_filterTags;
            
            RB_jsonEvent = RB_GetDataJson(url + options, "RB_onMapLayerLoad", RB_jsonEvent);
        }

    }
}




//javascript for adding object to map in client side.
function RB_addEvent(container) {
    if (RB_tempPushPin == null)
        return;

    var theTitleBox = document.getElementById(container + "_txtEventTitle");
    var theDescriptionBox = document.getElementById(container + "_txtEventDescription");
    var objs = document.getElementsByName(container + "$rdbImpactFactor");
    var latitudeBox = document.getElementById(container + "_hdfLatitude");
    var longitudeBox = document.getElementById(container + "_hdfLongitude");

    var title = theTitleBox.value;
    var description = theDescriptionBox.value;
    var lat = latitudeBox.value;
    var lon = longitudeBox.value;


    var factor = -100;

    for (var i = 0; i < objs.length; i++) {
        if (objs[i].checked) {
            factor = objs[i].value;
            break;
        }
    }

    RB_tempPushPin.SetDescription("<span id='RB_Shape_" + RB_tempPushPin.GetID() + "'><center><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></span>");

    var divTempPP = document.getElementById('RB_Shape_' + RB_tempPushPin.GetID());

    if (divTempPP)
        divTempPP.innerHTML = "<div id='RB_Shape_" + RB_tempPushPin.GetID() + "'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></div>";

    var url = RB_getSiteRoot() + "/private/event.aspx?action=add&lat=" + lat + "&long=" + lon + "&title=" + encodeURIComponent(title) + "&desc=" + encodeURIComponent(description) + "&factor=" + factor + "&mapid=" + RB_tempPushPin.GetID();
    RB_jsonPushpin = RB_GetDataJson(url, "RB_onEventLoad", RB_jsonPushpin);

    RB_map.ShowInfoBox(RB_tempPushPin);
    return true;
}


function RB_validateName(e) {
    var keychar;

    if (window.event) // IE
    {
        keychar = e.keyCode;
    }
    else if (e.which) {
        keychar = e.which;
    }

    if (keychar == 13) {
        var lat = document.getElementById("lvPushPin_hdfLatitude").value;
        var lon = document.getElementById("lvPushPin_hdfLongitude").value;

        addFavorites(lat, lon);
        return false;
    }
    else
        return true;
}



function RB_addFavorites(element, lat, lon) {

    if (!element || !lat || !lon)
        return;

    var txtName = document.getElementById(element);

    if (RB_tempPushPin == null || txtName == null)
        return;

    RB_tempPushPin.SetDescription("<div id='RB_Shape_" + RB_tempPushPin.GetID() + "'><center><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></div>");
    RB_map.ShowInfoBox(RB_tempPushPin);

    var divTempPP = document.getElementById('RB_Shape_' + RB_tempPushPin.GetID());

    if (divTempPP)
        divTempPP.innerHTML = "<img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' />";

    var url = RB_getSiteRoot() + "/private/favorites.aspx?action=add&lat=" + lat + "&long=" + lon + "&name=" + encodeURIComponent(txtName.value) + "&mapid=" + RB_tempPushPin.GetID();

    RB_jsonPushpin = RB_GetDataJson(url, 'RB_onEventLoad', RB_jsonPushpin);
}


function RB_onThis(sender, _action) {

    var originalUrl = sender.src;
    var sep = originalUrl.lastIndexOf("_");
    var originalUrlBase = originalUrl.substr(0, sep);
    var suffix = originalUrl.substr(sep, originalUrl.length);

    switch (_action) {

        case "over":
            sender.setAttribute("suffix", suffix);
            suffix = "_hover.png";
            break;

        case "out":
            if (sender.attributes["suffix"] != null) {
                var oldSuffix = sender.attributes["suffix"].value;
                sender.removeAttribute("suffix");
                suffix = oldSuffix;
            }
            else
                return;
            break;
    }

    sender.src = originalUrlBase + suffix;
}




function RB_onMapClick(e) {


    if (RB_map == null)
        return;

    if (e.rightMouseButton) {


        if (typeof (RB_ReadOnly) != "undefined")
            if (RB_ReadOnly)
            return;

        RB_blockOver = true;

        if (RB_tempPushPin != null) {
            RB_map.DeleteShape(RB_tempPushPin);
            RB_tempPushPin = null;
        }

        var p = window;
        var vepx = new VEPixel(e.mapX, e.mapY);
        var vellpx = RB_map.PixelToLatLong(vepx);

        RB_tempPushPin = new VEShape(VEShapeType.Pushpin, vellpx);
        RB_map.AddShape(RB_tempPushPin);
        RB_tempPushPin.UserDate = "temp";
        RB_tempPushPin.SetDescription("<div id='RB_Shape_" + RB_tempPushPin.GetID() + "'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></div>");
        RB_tempPushPin.Show();

        var url = RB_getSiteRoot() + "/pushpin.aspx?id=temp&lat=" + vellpx.Latitude + "&long=" + vellpx.Longitude + "&zoom=" + RB_map.GetZoomLevel() + "&mapid=" + RB_tempPushPin.GetID();
        if (typeof (RB_UserKey) != "undefined")
            url += "&key=" + RB_UserKey;

        if (typeof (RB_UserID) != "undefined")
            url += "&user=" + RB_UserID;

        RB_jsonPushpin = RB_GetDataJson(url, "RB_onEventLoad", RB_jsonPushpin);

        RB_map.ShowInfoBox(RB_tempPushPin);

        return;
    }


    if (e.leftMouseButton) {
        RB_onMapOver(e);
        return false;
    }

}

function RB_onMapOut(e) {
    if (RB_map == null)
        return;

    if (RB_map == null)
        return;

    if (e.elementID == null)
        return;


    var pp = RB_map.GetShapeByID(e.elementID);

    if (!pp) {
        return;
    }

    if (pp.GetType() == VEShapeType.Polygon) {
        pp.SetLineWidth(1);
        //   pp.SetLineColor(new VEColor(100, 100, 100, 0.5));
        return;
    }

}

function RB_onMapOver(e) {
    if (RB_blockOver) {
        RB_blockOver = false;
        return;
    }

    if (RB_map == null)
        return;

    if (e.elementID == null)
        return;


    var pp = RB_map.GetShapeByID(e.elementID);

    if (!pp) {
        return;
    }

    if (pp.GetType() == VEShapeType.Polygon) {
        pp.SetLineWidth(2);
        //   pp.SetLineColor(new VEColor(200, 0, 0, 0.8));
        //   pp.ShowIcon();
        return;
    }
    if (!RB_isGuid(pp.UserDate) && pp.UserDate != "temp") {
        RB_map.ShowInfoBox(pp, pp.GetPoints());
        return true;
    }

    var url = RB_getSiteRoot() + "/pushpin.aspx?";

    if (pp.GetType() == VEShapeType.Polygon) {
        url += "a";
    }

    var pts = pp.GetPoints();
    url += "id=" + pp.UserDate + "&mapid=" + pp.GetID() + "&lat=" + pts[0].Latitude + "&long=" + pts[0].Longitude + "&zoom=" + RB_map.GetZoomLevel();

    RB_jsonPushpin = RB_GetDataJson(url, "RB_onEventLoad", RB_jsonPushpin);

    RB_map.ShowInfoBox(pp, pp.GetPoints());

    return true;
}

function RB_onEventLoad(data) {
    RB_blockOver = false;

    if (data && data.event) {
        try {
            var pp = RB_map.GetShapeByID(data.event.mapid);

            if (!pp) {
                pp = new VEShape(VEShapeType.Pushpin, event.latitude, event.longitude);
                RB_map.AddShape(pp);
            }
            pp.UserDate = "";

            pp.SetDescription(data.event.description);
            var div = document.getElementById("RB_Shape_" + data.event.mapid);
            if (div) {
                div.innerHTML = data.event.description;
            }

        } catch (e) {

        }
    }

    RB_jsonPushpin = RB_RemoveJSONScript(RB_jsonPushpin);
}

function RB_onMapLayerLoad(data) {
    RB_blockOver = false;

    if (!data || !data.layer) {
        RB_mapLoadingStop(RB_mapDv);
        return;
    }

    var i = 0;
    var zoom = RB_map.GetZoomLevel();
    var iconSize = 15;
    if (zoom < 10) {
        iconSize -= 10 - zoom;
    }
    var iconOffsetTop = -iconSize / 2 + 13;
    var iconOffsetLeft = -iconSize / 2 + 11;
    if (data.layer.events) {
        if (!RB_mapEventLayer) {
            RB_mapEventLayer = new VEShapeLayer();
            RB_map.AddShapeLayer(RB_mapEventLayer);
            // RB_mapEventLayer.SetClusteringConfiguration(VEClusteringType.Grid);
        } else {
            RB_mapEventLayer.DeleteAllShapes();
        }
        RB_mapEventLayer.Hide();
      
        if (RB_map.GetZoomLevel() > RB_clusterZoomLevel) {

           
            
            for (i = 0; i < data.layer.events.length; i++) {
                var event = data.layer.events[i];
                var pushpin_latlon = new VELatLong(event.latitude, event.longitude, 0);
             
                
                var pushpin = new VEShape(VEShapeType.Pushpin, pushpin_latlon);

                var customIcon = new VECustomIconSpecification();
                customIcon.TextContent = "";
                var name = event.sectitle;

                if (event.icon != undefined) {
                    customIcon.CustomHTML = "<div style='top:" + iconOffsetTop + "px; left:" + iconOffsetLeft + "px; position:absolute; '><img src='" + event.icon + "' width='" + iconSize + "px' /><div class='map-point-text'>" + name + "</div></div>";

                } else {
                    customIcon.CustomHTML = "<div style='top:" + iconOffsetTop + "px; left:" + iconOffsetLeft + "px; position:absolute;'><img src='" + RB_getSiteRoot() + "/image.ashx?KeywordId=" + event.keyword + "' width='" + iconSize + "px'/><div class='map-point-text'>" + name + "</div></div>";

                }


                pushpin.SetCustomIcon(customIcon);

                RB_mapEventLayer.AddShape(pushpin);

                pushpin.UserDate = event.id;
                if (event.sectitle == "")
                    pushpin.SetTitle(event.title);
                else
                    pushpin.SetTitle(event.sectitle+" "+event.title);
                pushpin.SetDescription("<div id='RB_Shape_" + pushpin.GetID() + "'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></div>");
            }

          
            
        } else
            RB_clusterLayer(RB_mapEventLayer, data.layer.events);

//claudio - para meter um pseudo caminho.
//        var pathCoords = new Array();
//        if (data.layer.events.length > 1 && data.layer.events.length < 25) 
//        {
//            for(  i = 0; i < 25 && i< data.layer.events.length ; i++ ) {
//                var eventPath = data.layer.events[i];
//                var ltLong = new VELatLong(eventPath.latitude, eventPath.longitude, 0);
//                pathCoords[i] = ltLong;
//           }
//            var PathTravelOptions = new VERouteOptions();
//            PathTravelOptions.DistanceUnit = VERouteDistanceUnit.Kilometer;
//          //  PathTravelOptions.RouteMode = VERouteMode.Walking;

//            RB_map.GetDirections(pathCoords, PathTravelOptions);
//        }
        
        var counter = document.getElementById("RB_MapCounter");

        if (counter) {
            counter.innerText = data.layer.events.length + " pontos nesta vista";
        }

        RB_mapEventLayer.Show();

    }

    if (data.layer.favorites) {
        if (!RB_mapFavLayer) {
            RB_mapFavLayer = new VEShapeLayer();
            RB_map.AddShapeLayer(RB_mapFavLayer);
        } else {
            RB_mapFavLayer.DeleteAllShapes();
        }
        RB_mapFavLayer.Hide();

        for (i = 0; i < data.layer.favorites.length; i++) {
            var event = data.layer.favorites[i];
            var pushpin;
            var pushpin_latlon = new VELatLong(event.latitude, event.longitude, 0);
            pushpin = new VEShape(VEShapeType.Pushpin, pushpin_latlon);
            pushpin.SetCustomIcon(event.icon);
            RB_mapFavLayer.AddShape(pushpin);
            pushpin.UserDate = event.id;
            pushpin.SetDescription("<div id='RB_Shape_" + pushpin.GetID() + "'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /></div>");
        }

        RB_mapFavLayer.Show();
    }

    if (data.layer.favorites || data.layer.events) {
        RB_jsonEvent = RB_RemoveJSONScript(RB_jsonEvent);
    }

    if (data.layer.areas) {
        if (RB_mapAreaLayer == null) {
            RB_mapAreaLayer = new VEShapeLayer();
            RB_map.AddShapeLayer(RB_mapAreaLayer);
        } else {
            RB_mapAreaLayer.DeleteAllShapes();
        }

        RB_mapAreaLayer.Hide();

        var icon = RB_getSiteRoot() + "/img/mapicons/area.png";

        var zoom = RB_map.GetZoomLevel();
        var iconSize = 20 + zoom;
        var iconOffsetTop = -iconSize / 2 - 10;
        var iconOffsetLeft = -iconSize / 2 + 9;

        for (i = 0; i < data.layer.areas.length; i++) {
            try {
                var area = data.layer.areas[i];
                var content = area.geom;
                var j;

                for (j = 0; j < content.length; j++) {
                    var k;
                    var polygon = content[j].points;
                    var parray = new Array();

                    for (k = 0; k < polygon.length; k++) {
                        parray[k] = new VELatLong(parseFloat(polygon[k].lat), parseFloat(polygon[k].lon));
                    }

                    var shape = new VEShape(VEShapeType.Polygon, parray);
                    shape.SetLineWidth(1.5);
                    shape.SetLineColor(new VEColor(20, 20, 255, 1));
                    shape.SetFillColor(new VEColor(0, 0, 0, 0));
                    shape.SetTitle(area.title);
                    shape.SetDescription("<a href='" + RB_getSiteRoot() + "/private/area.aspx?id=" + area.id + "'>Gerir área</a>");

                    var customIcon = new VECustomIconSpecification();
                    customIcon.CustomHTML = "<div style='top:" + iconOffsetTop + "px; left:" + iconOffsetLeft + "px; position:absolute;'><img src='" + RB_getSiteRoot() + "/img/mapicons/area.png' width='" + iconSize + "px'/></div>";
                    shape.SetCustomIcon(customIcon);

                    RB_mapAreaLayer.AddShape(shape);
                }
            } catch (ex) {


            }
        }

        RB_mapAreaLayer.Show();

        RB_jsonArea = RB_RemoveJSONScript(RB_jsonArea);


        if (RB_bestview) {
            if (RB_bestview_ignore == true)
                RB_bestview_ignore = false;
            else {
                RB_map.SetMapView(RB_mapAreaLayer.GetBoundingRectangle());
                RB_bestview_ignore = true;
            }
        }






    }
    RB_mapLoadingStop(RB_mapDv);

}


function RB_onMapStartZoom() {
    if (RB_mapFind)
        return;

    RB_map.DeleteAllShapeLayers();
    RB_mapAreaLayer = null;
    RB_mapEventLayer = null;
    RB_mapFavLayer = null;
}

function RB_onMapEndZoom() {
    if (RB_mapFind)
        return;

    RB_map.DeleteAllShapeLayers();
    RB_mapAreaLayer = null;
    RB_mapEventLayer = null;
    RB_mapFavLayer = null;

    RB_resetMapLayers(null);
}

function RB_onMapPan() {
    RB_resetMapLayers(null);
}


function RB_onMapError(e) {

}

function RB_clusterLayer(layer, points) {
    var mapView = RB_map.GetMapView();
    var zoom = RB_map.GetZoomLevel();
    var gridSize = 16;
    var maxDescription = 50;
    var spacing = 360 / (Math.pow(2, zoom) * gridSize);

    var startLat = (mapView.TopLeftLatLong.Latitude - Math.abs(mapView.TopLeftLatLong.Latitude % spacing) + spacing).toPrecision(10);
    var startLong = (mapView.TopLeftLatLong.Longitude + Math.abs(mapView.TopLeftLatLong.Longitude % spacing) - spacing).toPrecision(10);
    var endLat = (mapView.BottomRightLatLong.Latitude - Math.abs(mapView.BottomRightLatLong.Latitude % spacing) - spacing).toPrecision(10);
    var endLong = (mapView.BottomRightLatLong.Longitude + Math.abs(mapView.BottomRightLatLong.Longitude % spacing) + spacing).toPrecision(10);

    var latDiff = Math.abs(endLat - startLat);
    var longDiff = Math.abs(endLong - startLong);

    var numYCells = Math.ceil(latDiff / spacing);
    var numXCells = Math.ceil(longDiff / spacing);

    var keywords = new Array();

    for (var cnt = 0; cnt < points.length; cnt++) {
        var event = points[cnt];

        if (typeof (keywords[event.keyword]) != "undefined") {
            keywords[event.keyword].events.push(event);

        }
        else {
            keywords[event.keyword] = { id: "", events: new Array() };
            keywords[event.keyword].id = event.keyword;
            keywords[event.keyword].events.push(event);


        }
    }

    for (var keyword in keywords) {
        if (typeof (keywords[keyword].events) == "undefined")
            break;

        var icon = RB_getSiteRoot() + "/image.ashx?KeywordId=" + keywords[keyword].id + "&size=2";

        var gridCells = new Array();

        for (var cnt = 0; cnt < keywords[keyword].events.length; cnt++) {
            var event = keywords[keyword].events[cnt];

            var eventLatDiff = Math.abs(event.latitude - startLat);
            if (eventLatDiff > latDiff)
                continue;

            var eventLongDiff = Math.abs(event.longitude - startLong);
            if (eventLongDiff > longDiff)
                continue;

            var j = Math.floor(eventLatDiff / spacing);
            var i = Math.floor(eventLongDiff / spacing);

            var key = i + j * numXCells;
            if (isNaN(key))
                alert("NAN");

            if (typeof (gridCells[key]) == "undefined") {
                gridCells[key] = { id: "", latitude: 0, longitude: 0, title: "", description: "", length: 0, icon: "", secTitle: "" };
            }

            if (gridCells[key].length == 0) {
                gridCells[key].latitude = event.latitude;
                gridCells[key].longitude = event.longitude;
                gridCells[key].id = event.id;
                gridCells[key].sectitle = event.sectitle;

                if (event.title)
                    gridCells[key].title = event.title;

                if (event.description) {
                    if (event.description.length > 30)
                        gridCells[key].description = event.description.substr(0, 30) + "...";
                    else
                        gridCells[key].description = event.description;
                }

                if (event.icon) {
                    gridCells[key].icon = event.icon;
                } else {
                    gridCells[key].icon = icon
                }


            } else {
                if (gridCells[key].length == 2) {
                    if (event.title)
                        gridCells[key].description = gridCells[key].title + "<br />" + event.title + "<br />";
                } else {
                    if (gridCells[key].length < 10) {
                        if (event.title)
                            gridCells[key].description += event.title + "<br />";
                    } else
                        if (gridCells[key].length == 10)
                        gridCells[key].description += "..."
                }
            }

            gridCells[key].length++;

        }

        for (var key in gridCells) {
            if (typeof (gridCells[key].latitude) == "undefined")
                break;

            if (gridCells[key].length > 0) {

                var clusterShape = new VEShape(VEShapeType.Pushpin, new VELatLong(gridCells[key].latitude, gridCells[key].longitude, 0));
                clusterShape.SetTitle(gridCells[key].title);
                clusterShape.UserDate = gridCells[key].id;
                layer.AddShape(clusterShape);

                if (gridCells[key].length == 1) {
                    var iconSize = 15;

                    if (zoom < 5)
                        iconSize = 5;
                    else
                        if (zoom < 15) {
                        iconSize = 1 + zoom - 3;

                    }
                    var name = "";
                    if (zoom > 12 && gridCells[key].sectitle) {
                        name= gridCells[key].sectitle;
                    }

                    var iconOffsetTop = -iconSize / 2 + 11;
                    var iconOffsetLeft = -iconSize / 2 + 11;

                    var customIcon = new VECustomIconSpecification();
                    customIcon.CustomHTML = "<div style='top:" + iconOffsetTop + "px; left:" + iconOffsetLeft + "px; position:absolute; width: auto;'><img src='" + gridCells[key].icon + "' width='" + iconSize + "px'/><div class='map-point-text'>" + name + "</div></div>";
                    clusterShape.SetCustomIcon(customIcon);
                    clusterShape.UserDate = gridCells[key].id;

                    if (gridCells[key].sectitle == "")
                        clusterShape.SetTitle(gridCells[key].title);
                    else
                        clusterShape.SetTitle(gridCells[key].sectitle + " " + gridCells[key].title);
                        
              
                    clusterShape.SetDescription("<div id='RB_Shape_" + clusterShape.GetID() + "'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading.gif' /><div class='map-point-text'>" + name + "</div></div>");
                }
                else {
                    var iconSize = 20;

                    if (zoom < 15) {
                        iconSize = 5 + zoom;
                    }
                    
                  
                    var customIcon = new VECustomIconSpecification();
                    var iconOffsetTop = -iconSize / 2 + 11;
                    var iconOffsetLeft = -iconSize / 2 + 11;
                    customIcon.CustomHTML = "<div style='top:" + iconOffsetTop + "px; left:" + iconOffsetLeft + "px; position:absolute;'><img src='" + gridCells[key].icon + "' width='" + iconSize + "px' /></div>";
                    clusterShape.SetDescription(gridCells[key].description);
                    clusterShape.UserDate = "";
                    clusterShape.SetCustomIcon(customIcon);
                    clusterShape.SetTitle("Existem aqui " + gridCells[key].length + " pontos<br /><hr />");

                }

            }
        }
    }
}


function RB_mapLoadingStart(e) {
    if (e == null)
        return;

    if (document.getElementById(e + "_loading") != null)
        return;

    var dv_map = document.getElementById(e);

    if (dv_map == null)
        return;

    var dv = document.createElement("div");
    dv.setAttribute('id', e + "_loading");
    dv.setAttribute('z-index', 1000);
    dv.innerHTML = "<div class='RB_overlay_dark' style='width:" + dv_map.style.width + "; height:" + dv_map.style.height + ";'></div><div class='RB_overlay_image'><img src='" + RB_getSiteRoot() + "/img/siteicons/loading_big.gif' width='64px'/></div>";

    dv_map.appendChild(dv);
}

function RB_mapLoadingStop(e) {


    if (e == null)
        return;

    var dv = document.getElementById(e + "_loading");

    if (dv == null)
        return;

    var dv_map = document.getElementById(e);
    if (!dv_map)
        return;

    dv_map.removeChild(dv);
}


