﻿/**
 *   POI Manager
 *        plots specified poi type points onto current map view
 *
 *   These scripts need to be included: 
 *
 *   <script type="text/javascript" src="Scripts/ServerAJAX.js"></script>
 *   <script type="text/javascript" src="Scripts/JSON.js"></script>
 *   <script type="text/javascript" src="Scripts/ClientCache.js"></script>
 */
var POIManager = new POIManagerClass();

function POIManagerClass()
{
    var poiToggles = new Array();
    var maxPinLimit = 80;
    var currentPinCount = 0;
    var eventsAttached = false;
    var g_POIs = new Array();
    //var allShapes = new Array();
    var processedCount = 0;
    var typesToProcessCount = 0;
    var poiItemStyles = new Array();
    
    // set client cache variable for all pois to inactive
    for(var typeId=0; typeId<17; typeId++){
        ClientCache.Save('poi_'+typeId,((ClientCache.Retrieve('poi_'+typeId)!=null) ? ClientCache.Retrieve('poi_'+typeId) : 'inactive'));
    }
    
    this.Restore = RestoreState;
    this.RefreshPOIs = ShowToggledPOIsOnMap;
    this.HidePOIs = HideToggledPOIsFromMap;
    this.GetPOIToogleState = GetPOIToogleState;
    this.OnPOIClick = m_poiItemClickHandler;
    this.showMaplevelAlert = showMaplevelAlert;
    this.styleCarouselPoi = styleCarouselPoi;
    this.GDDForPOIPopup = GDDForPOIPopup;
    this.GNBForPOIPopup = GNBForPOIPopup;
    this.GenerateDescription = GenerateDescription;
    this.GenerateName = GenerateName;
    this.GenerateAddress = GenerateAddress;
    this.GenerateImage = GenerateImage;
    this.SavePOIToCustomMap = SavePOIToCustomMap;
    
    /**
     * Toggle POI of specific type
     *
     * @param typeId (int) - the lookup id of POI Type
     * @param toggled (bool) - checked/unchecked
     */ 
    function TogglePOI(typeId, toggled) {
        poiToggles[typeId] = toggled;
        
        if(toggled){
            ShowPOIsOnMap(typeId);
        }
        else{
            RemovePOIsFromMap(typeId);
        }
            
        // Store into client cache
        ClientCache.Save("POIToggleMap", JSON.stringify(poiToggles));
    }
    
    function GetPOIToogleState(typeId)
    {    
       return poiToggles[typeId];
    }
    
    /**
     * Hide POIs from current map view
     *
     */
    function HideToggledPOIsFromMap() {
        // display each POI layer in poiToggles on map
        for (curType in poiToggles) {
            if (poiToggles[curType] == true) {
                HidePOIsFromMap(curType);
            }
        }
        // dettach onmapmovement events since no pois displayed 
        mapManager.Map.DetachEvent('onendpan', ShowToggledPOIsOnMap);
        mapManager.Map.DetachEvent('onendzoom', ShowToggledPOIsOnMap);
        //alert('showtoggledpoisonmap event detached');
        eventsAttached = false;
    }
    
    /**
     * Display POIs of toggled ones on current map view
     *
     */ 
    function ShowToggledPOIsOnMap()
    {
        HideLoading();
        
        // if map zoomed in far enough
        if (mapManager.Map.GetZoomLevel() > 11) {
            // re-attach onmapmovement events as they would have been removed if HidePOIs previously called
            if (!eventsAttached) {
                mapManager.Map.AttachEvent('onendpan', ShowToggledPOIsOnMap);
                mapManager.Map.AttachEvent('onendzoom', ShowToggledPOIsOnMap);
                eventsAttached = true;
            }
            // display each POI layer in poiToggles on map
            for (curType in poiToggles) {
                if (poiToggles[curType] == true) {
                    ShowPOIsOnMap(curType);
                }
                else {
                    RemovePOIsFromMap(curType);
                }
            }
        }
        else {
            if (eventsAttached) {
                mapManager.Map.DetachEvent('onendpan', ShowToggledPOIsOnMap);
                mapManager.Map.DetachEvent('onendzoom', ShowToggledPOIsOnMap);
                eventsAttached = false;
            }

            //HideLoading();

            var div_zoom_alert = document.getElementById('div_maplevel_alert_message');

            // remove each POI layer in poiToggles from map
            for (curType in poiToggles) {
                if (poiToggles[curType] == true) {
                    if (div_zoom_alert.style.display != 'block') {
                        div_zoom_alert.style.display = 'block';

                        //close the window after 5 seconds
                        setTimeout(hide_div_zoom_alert, 5000);

                        var div_maplevel_alert_message_text_close = document.getElementById('div_maplevel_alert_message_text_close');
                        div_maplevel_alert_message_text_close.onclick = hide_div_zoom_alert;
                        var div_maplevel_alert_message_right_quadrant = document.getElementById('div_maplevel_alert_message_right_quadrant');
                        div_maplevel_alert_message_right_quadrant.onclick = hide_div_zoom_alert;

                        mapManager.Map.ShowControl(div_zoom_alert);
                    }
                    RemovePOIsFromMap(curType);
                }
            }
        }
    }

    /**
    * Remove POI of specified from current map view
    *
    * @param typeId (int) - the lookup id of POI Type
    */
    function RemovePOIsFromMap(typeId) {
        if (poiItemStyles[typeId] != undefined) {
            if (poiItemStyles[typeId][0] != undefined)
                POIManager.styleCarouselPoi(typeId, poiItemStyles[typeId][0], false, poiItemStyles[typeId][1], poiItemStyles[typeId][2], poiItemStyles[typeId][3]);
        }

        ClientCache.Save('poi_' + typeId, 'inactive');

        // delete g_POIs.TypeId pois
        poiToggles[typeId] = false;

        HidePOIsFromMap(typeId);
    }

    /**
    * Hide POI of specified from current map view
    *
    * @param typeId (int) - the lookup id of POI Type
    */
    function HidePOIsFromMap(typeId) {
        clusterManager.DeleteShapes(typeId);
    }

    /**
    * Executes Ajax Request for POI of typId
    *
    * @param typeId - the lookup id of POI Type
    */
    function ShowPOIsOnMap(typeId) {
        ClientCache.Save('poi_' + typeId, 'active');
        //ShowLoading();
        var view = mapManager.Map.GetMapView();
        topleft = view.TopLeftLatLong;
        bottomright = view.BottomRightLatLong;
        var qString = "?poiType=" + typeId + "&topLeftLat=" + topleft.Latitude + "&topLeftLong=" + topleft.Longitude +
            "&bottomRightLat=" + bottomright.Latitude + "&bottomRightLong=" + bottomright.Longitude;
        //alert("Handlers/POIHandler.ashx" + qString);
        var request = new AjaxRequest("Handlers/POIHandler.ashx" + qString, ProcessPOI);

        // sending ajax request for typeId pois
        request.Execute();
    }
    
    /**
     * Process returned POI data
     */
    function ProcessPOI(rText)
    {
        try {
            var poiData = eval('(' + rText + ')');

            if (poiData != undefined && poiData.DataList != null) {
                g_POIs[poiData.TypeId] = poiData.DataList;
                clusterManager.PoiPresent = true;
                var returnedShapes = new Array();
                for (var x = 0; x < poiData.DataList.length; x++) {
                    returnedShapes.push(AddPOIShape(x, poiData.TypeId));
                }
            }
        }
        catch(e)
        {
            //alert(e.message);
        }
        processedCount++;
        
        clusterManager.DeleteShapes(poiData.TypeId);
        clusterManager.AddShapes(returnedShapes, poiData.TypeId);
    }

    /**
    * Generate POI Shape
    */
    function AddPOIShape(poiIndex, typeId) {
        var poiData = g_POIs[typeId][poiIndex];
        var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(poiData.Latitude, poiData.Longitude));
        var poiImg = GetIcon(poiData.POIType);

        shape.SetCustomIcon("<div class='poiPin' style='background:url(Images/" + poiImg + ")'></div>");
        //shape.SetDescription(GenerateDescription(poiIndex));
        var poiKey = InfoBoxManager.GenerateKey('POI' + typeId, poiIndex);
        var description = poiKey;
        //var description = '<span style="display:none">' + poiKey + '</span>' + GenerateDescription(poiIndex);
        shape.SetDescription(description);
        shape.SetTitle('poi');

        return shape;
        /*var poiData = g_POIs.DataList[poiIndex];
        var shape = new VEShape(VEShapeType.Pushpin, new VELatLong(poiData.Latitude, poiData.Longitude));
        var poiImg = GetIcon(poiData.POIType);

        shape.SetCustomIcon("<div class='poiPin' style='background:url(Images/" + poiImg + ")'></div>");
        //shape.SetDescription(GenerateDescription(poiIndex));
        var poiKey = InfoBoxManager.GenerateKey('POI' + typeId, poiIndex);
        var description = poiKey;
        //var description = '<span style="display:none">' + poiKey + '</span>' + GenerateDescription(poiIndex);
        shape.SetDescription(description);
        shape.SetTitle('poi');

        return shape;*/
    }
    
    /**
     * Restore state from client cache
     */
    function RestoreState()
    {
        /*// Restore POI Toggle Map
        var v = ClientCache.Retrieve('POIToggleMap');
        if (v != undefined)
        {
            poiToggles = JSON.parse(v);
        }
        // Refresh map after restore
        if(poiToggles.length > 0)
            ShowToggledPOIsOnMap();*/
        
        // set poitToggles array based on Client Cache variables
        // loop through all poi types
        for(var epoiType=0; epoiType<17; epoiType++){
            // activate poi if set to active in Client Cache
            if(ClientCache.Retrieve('poi_'+epoiType) == 'active'){
                poiToggles[epoiType] = true;
            }
        }
        // Refresh map after restore
        if(poiToggles.length > 0){
            //alert('showing toggled pois');
            ShowToggledPOIsOnMap();
        }
    }
    
    /**
     * Generate the location name included in the description for popup
     *
     * @return the location name included in the description
     */
    function GenerateName(poiIndex,poiType)
    {
        var poiData = g_POIs[poiType][poiIndex];
        return ('<strong>' + poiData.Name + '</strong>');
    }
    
    /**
     * Generate the location address included in the description for popup
     *
     * @return the location address included in the description
     */
    function GenerateAddress(poiIndex,poiType)
    {
        var poiData = g_POIs[poiType][poiIndex];
        return (poiData.AddressHtml);
    }    
    
    /**
     * Generate the location image included in the description for popup
     *
     * @param (int) poiType - type of poi
     * @param poiIndex - index of the specific poi
     *
     * @return the location image included in the description
     */
    function GenerateImage(poiIndex, poiType)
    {
        var poiData = g_POIs[poiType][poiIndex];
        var poiImg = GetIcon(g_POIs[poiType][poiIndex].POIType);
        //var poiImg = GetIcon(poiType);
        return (poiImg = '<img src="Images/' + poiImg + '"></img>');
    }
    
    /**
     * Generate the description for popup
     *
     * @param (int) poiType - type of poi
     * @param poiIndex - index of the specific poi
     *
     * @return the expanded description
     */
    function GenerateDescription(poiIndex, poiType)
    {
        var poiData = g_POIs[poiType][poiIndex];
        var poiImg = GetIcon(g_POIs[poiType][poiIndex].POIType);

        var index = poiIndex; //currentPinCount;
        var key = 'POI' + poiType + '||' + poiIndex;
        var divHeight = "170px";
        var topMargin = "8px";
        var description = '<div style="height: ' + divHeight + ';margin-top:' + topMargin + ';">';   // Overall
        
        description +=      '<div class="popupTop">';   // Top
        description +=          '<div class="popupTopLeft">';   // Top Left
        
        description +=              '<div style="display:block;margin-top:5px; margin-bottom:5px;"><img src="Images/' + poiImg + '"></img></div>';
        description +=              '<div style="font-weight: bold; font: 12px/14px Arial;">';
        description +=                  '<strong>' + poiData.Name + '</strong><br />';
        description +=                  poiData.AddressHtml;
        description +=              '</div>';
       
        description +=          '</div>';   // top left div
        
        description +=          '<div class="popupTopRight">';
        
        // Action area
        description += '<div id=\"AP_ACTION_' + key + '\" class="popupActionArea" style="top:10px;">';
        //description += '<div id=\"AP_ACTION_' + index + '\" class="popupActionArea" style="top:10px;">';
        
        // Empty (Action)
        description += '<div id=\"AP_EMPTY_' + key + '\" style="height:130px; width:100px;"></div>';
        //description += '<div id=\"AP_EMPTY_' + index + '\" style="height:130px; width:100px;"></div>';

        // To Here (Action)
        description += '<div id=\"AP_TO_' + key + '\" style="height:130px;display:none;"><div class="popupHeader"><strong>' + resourceDD + ':</strong></div><br/>';
        //description += '<div id=\"AP_TO_' + index + '\" style="height:130px;display:none;"><div class="popupHeader"><strong>' + resourceDD + ':</strong></div><br/>';
        description +=                      resourceToHere + ':<br/>';
        description += '<input type="text" id="p_toAddress' + key + '" style="width:158px;" onkeydown="ExecuteFindFromInput(\'p_imgTo' + (key) + '\', event);"/><br/>';
        //description += '<input type="text" id="p_toAddress' + index + '" style="width:158px;" onkeydown="ExecuteFindFromInput(\'p_imgTo' + (index) + '\', event);"/><br/>';

        description += '<div><img id="p_imgTo' + key + '" src="' + images + 'GetDD.gif" class="popupLink" style="left:100px; float: right;" onclick="POIManager.GDDForPOIPopup(\'TO\', \'' + (key) + '\');" /></div>';
        //description += '<div><img id="p_imgTo' + index + '" src="' + images + 'GetDD.gif" class="popupLink" style="left:100px; float: right;" onclick="POIManager.GDDForPOIPopup(\'TO\', ' + (index) + ');" /></div>';
        description +=                  '</div>';
        
        // From Here (Action)
        description += '<div id=\"AP_FROM_' + key + '\" style="height:130px;display:none;"><div class="popupHeader"><strong>' + resourceDD + ': </strong></div><br/>';
        //description += '<div id=\"AP_FROM_' + index + '\" style="height:130px;display:none;"><div class="popupHeader"><strong>' + resourceDD + ': </strong></div><br/>';
        description +=                      resourceFromHere +':<br/>';
        description += '<input type="text" id="p_fromAddress' + key + '" style="width:158px;" onkeydown="ExecuteFindFromInput(\'p_imgFrom' + (key) + '\', event);"/><br/>';
        //description += '<input type="text" id="p_fromAddress' + index + '" style="width:158px;" onkeydown="ExecuteFindFromInput(\'p_imgFrom' + (index) + '\', event);"/><br/>';

        description += '<div><img id="p_imgFrom' + (key) + '" src="' + images + 'GetDD.gif" class="popupLink" style="left:100px; float: right;" onclick="POIManager.GDDForPOIPopup(\'FROM\', \'' + (key) + '\');"/></div>';
        //description += '<div><img id="p_imgFrom' + (index) + '" src="' + images + 'GetDD.gif" class="popupLink" style="left:100px; float: right;" onclick="POIManager.GDDForPOIPopup(\'FROM\', ' + (index) + ');"/></div>';
        description +=                  '</div>';

        // What's near (Action)
        description += '<div id=\"AP_NEAR_' + key + '\" style="height:130px;display:none;"><div class="popupHeader"><strong>' + resourceWhatsNearby + ': </strong></div><br/>';
        //description += '<div id=\"AP_NEAR_' + index + '\" style="height:130px;display:none;"><div class="popupHeader"><strong>' + resourceWhatsNearby + ': </strong></div><br/>';
        description +=                      '<div class="popupSubheader">' + resourceSearchForCategory + ':<br/></div>';
        description += '<input type="text" id="p_nearby' + key + '" style="width:158px;" onkeydown="ExecuteFindFromInput(\'p_imgNear' + (key) + '\', event);"/><br/>';
        //description += '<input type="text" id="p_nearby' + index + '" style="width:158px;" onkeydown="ExecuteFindFromInput(\'p_imgNear' + (index) + '\', event);"/><br/>';
        
        description +=                      '<div style="float:left; width:110px">' + resourceWhatsNearbyExample + '</div>';
        description += '<div><img id="p_imgNear' + (key) + '" src="' + images + 'GetDD.gif" class="popupLink" style="margin-top:11px; left:100px; float: right;" onclick="POIManager.GNBForPOIPopup(\'' + (key) + '\');"/></div>';
        //description += '<div><img id="p_imgNear' + (index) + '" src="' + images + 'GetDD.gif" class="popupLink" style="margin-top:11px; left:100px; float: right;" onclick="POIManager.GNBForPOIPopup(' + (index) + ');"/></div>';
        description +=                  '</div>';
        
        // Save to a Map (Action)
        description += '<div id=\"AP_MAP_' + key + '\" style="height:130px;display:none;">';
        //description += '<div id=\"AP_MAP_' + index + '\" style="height:130px;display:none;">';
        description += '<div id=\"AP_MAP_SAVE_' + key + '\" style="display:none;">';
        //description += '<div id=\"AP_MAP_SAVE_' + index + '\" style="display:none;">';
        description +=                          '<div style="float:left;">';
        description +=                              '<div class="popupHeader" style="width:110px"><strong>' + resourceSaveToAMap + ': </strong></div><br />';
        description +=                              '<div style="width:110px">' + resourceSaveToAMapPrompt + '</div>';
        description +=                              '</div>';
        description +=                          '<div><img src="Images/' + poiImg + '" class="popupLink" style="margin-right:10px; margin-top:10px; float: right; border: 1px solid black;" /></div>';

        description +=                          '<div style="margin-top:10px;"><select id="mapSelect" style="width:158px;"></select><br/></div>';
        description += '<div><img id="p_imgAdd' + (key) + '" src="' + images + 'doneButton.gif" class="popupLink" style="left:100px; float: right;" onclick="POIManager.SavePOIToCustomMap(' + (key) + ');"/></div>';
        //description += '<div><img id="p_imgAdd' + (index) + '" src="' + images + 'doneButton.gif" class="popupLink" style="left:100px; float: right;" onclick="POIManager.SavePOIToCustomMap(' + (index) + ');"/></div>';
        description +=                      '</div>';

        description += '<div id=\"AP_MAP_WARN_' + key + '\" style="float:left;display:none">';
        //description += '<div id=\"AP_MAP_WARN_' + index + '\" style="float:left;display:none">';
        description +=                          '<div class="popupHeader" style="width:110px"><strong>' + resourceSaveToAMap + ': </strong></div><br />';
        description +=                          '<div style="width:180px">' + resourceLoginNeeded + '</div>';
        description +=                      '</div>';
        description +=                  '</div>';
        
        description +=              '</div>';   //Action area
        description +=          '</div>';   // top right
        description +=      '</div>';   // top div

        // Function bar
        description += '<div class="popupBottom">';
        description += '<table><td><img src="images/drivingicon.gif" align="left" style="margin-right:3px;margin-left:3px"></img></td>';
        description += '<td>' + resourceDD.toUpperCase();
        description += '<div></div><span class="popupLink popupDrivingFunctionTo" onclick="YPSearchManager.ShowActionDiv(\'AP_\', \'' + (key) + '\', \'FROM\');"><img src="images/tohereicon.gif"><span>' + resourceToHere.toUpperCase() + '</span></img></span> | ';
        //description += '<div></div><span class="popupLink popupDrivingFunctionTo" onclick="YPSearchManager.ShowActionDiv(\'AP_\', ' + (index) + ', \'FROM\');"><img src="images/tohereicon.gif"><span>' + resourceToHere.toUpperCase() + '</span></img></span> | ';
        description += '<span class="popupLink popupDrivingFunctionFrom" onclick="YPSearchManager.ShowActionDiv(\'AP_\', \'' + (key) + '\', \'TO\');"><img src="images/fromhereicon.gif"><span>' + resourceFromHere.toUpperCase() + '</span></img></span>';
        //description += '<span class="popupLink popupDrivingFunctionFrom" onclick="YPSearchManager.ShowActionDiv(\'AP_\', ' + (index) + ', \'TO\');"><img src="images/fromhereicon.gif"><span>' + resourceFromHere.toUpperCase() + '</span></img></span>';
        description += '</td>';  // DD

        description += '<td style="width:60px;margin-right:3px;"><span class="popupLink" onclick="YPSearchManager.ShowActionDiv(\'AP_\', \'' + (key) + '\', \'NEAR\');"><img src="images/nearbyicon.gif" align="left" style="margin-right:3px"></img>';
        //description += '<td style="width:60px;margin-right:3px;"><span class="popupLink" onclick="YPSearchManager.ShowActionDiv(\'AP_\', ' + (index) + ', \'NEAR\');"><img src="images/nearbyicon.gif" align="left" style="margin-right:3px"></img>';
        description += '<span class="popupLink">' + resourceWhatsNearby.toUpperCase() + '</div></span></td>';
        description += '<td style="margin-right:3px; width:70px;"><span class="popupLink" onclick="YPSearchManager.ShowActionDiv(\'AP_\', \'' + (key) + '\', \'MAP\');"><img src="images/savemapicon.gif" align="left" style="margin-right:3px;margin-left:3px"></img>';
        //description += '<td style="margin-right:3px; width:70px;"><span class="popupLink" onclick="YPSearchManager.ShowActionDiv(\'AP_\', ' + (index) + ', \'MAP\');"><img src="images/savemapicon.gif" align="left" style="margin-right:3px;margin-left:3px"></img>';
        description += resourceAddToAMap.toUpperCase() + '</span></td>';
        //description += '<td><div class="popupLink popupPrint" style="width: 60px; float:left"><img src="images/printicon.gif" style="margin-left:3px;margin-right:3px"></img>';
        //description += resourcePrint.toUpperCase() + '</div></td>';
        description += '</tr></table>';   // Function bar
        description += '</div>';   // Bottom div
        
        description += '</div>';  // overall
        
        // Add prefix
        //description = '(S)' + description;
        
        return description;
        //return InfoBoxManager.StoreDescription('POI', index, description);
    }

    /**
     * Get POI icon depending on poi type
     */
    function GetIcon(poiType)
    {
        switch (poiType)    
        {
            case 'BOR':
                return 'poi_border.gif';
            case 'CAR':
                return 'POI-Icons-CarRental.png';
            case 'CPL':
                return 'POI-Icons-Carpool.png';
            case 'EDU':
                return 'POI-Icons-School.png';
            case 'FIN':
                return 'POI-Icons-Bank.png';
            case 'FRE':
                return 'poi_fire.gif';
            case 'GAS':
                return 'POI-Icons-Gas.png';
            case 'HCR':
                return 'POI-Icons-Hospital.png';
            case 'POL':
                return 'poi_police.gif';
            case 'TOU':
                return 'POI-Icons-Tourist.png';
            default:
                return 'dartweb.gif';
        }   
    }

    this.ApplyStyleOnPoiItem = function(itemDivId, isToggled, imageId, imagePath1, imagePath2) {
        var styleToApply = isToggled ? "Arial10Bold" : "Arial10Normal";
        var itemDiv = document.getElementById(itemDivId);
        itemDiv.setAttribute("class", styleToApply);
        itemDiv.setAttribute("className", styleToApply);
        itemDiv.title = POIClickLinkToShowHideIcons;
        SwapImage(imageId, imagePath1, imagePath2, isToggled);
    }

    function addShim(el) 
    { 
        var shim = document.createElement("iframe");
        shim.id = "myShim" + i;
        shim.frameBorder = "0";
        shim.style.position = "absolute";
        shim.style.zIndex = "1";
        shim.style.top  = el.offsetTop;
        shim.style.left = el.offsetLeft;
        shim.width  = el.offsetWidth - 10;
        shim.height = el.offsetHeight -10;
        el.shimElement = shim;
        el.parentNode.insertBefore(shim, el);
    }

    function hide_div_zoom_alert() {
        var div_zoom_alert = document.getElementById('div_maplevel_alert_message');
        if (div_zoom_alert == null) return;
        mapManager.Map.HideControl(div_zoom_alert);
    }

    /**
    * shows alert message and toggles poi to false
    *
    * @param epoiType type of poi
    */
    function showMaplevelAlert(epoiType){
        var div_zoom_alert = document.getElementById('div_maplevel_alert_message');

        div_zoom_alert.style.display = 'block';
        //div_zoom_alert.style.top = mapManager.Map.GetTop();

        //close the window after 5 seconds
        setTimeout(hide_div_zoom_alert, 5000);

        var div_maplevel_alert_message_text_close = document.getElementById('div_maplevel_alert_message_text_close');
        div_maplevel_alert_message_text_close.onclick = hide_div_zoom_alert;
        var div_maplevel_alert_message_right_quadrant = document.getElementById('div_maplevel_alert_message_right_quadrant');
        div_maplevel_alert_message_right_quadrant.onclick = hide_div_zoom_alert;

        //BUGFIX: this causes white background to left behind when user resizes the map, and we really don't need this
        //addShim(div_zoom_alert);

        mapManager.Map.ShowControl(div_zoom_alert);

        poiToggles[epoiType] = false;
    }


    function styleCarouselPoi(epoiType, itemDivId, isToggled, imageId, imagePath1, imagePath2) {
        //swap POI image
        if (imagePath1 != "") {
            //apply style based on selection or not
            this.ApplyStyleOnPoiItem(itemDivId, isToggled, imageId, imagePath1, imagePath2);
            poiItemStyles[epoiType] = new Array(itemDivId, imageId, imagePath1, imagePath2);
            //poiItemStyles[epoiType] = new Array(itemDivId, imageId, imagePath1, imagePath2);

        }
        //Go to find on a business and fill keyword if no image is provided
        else {
            TopNav("FindBusiness");
            document.getElementById('txtBusName').value = title;
            var center = mapManager.Map.GetCenter();


            document.getElementById('txtBusLocation').value = (Math.round(center.Latitude * 100) / 100) + ', ' + (Math.round(center.Longitude * 100) / 100);
            mapManager.NewFindBusiness(true);
        }

        // Hide current popup on POI changes  (optionally, only on isToggled == false)
        HideCurrentEro(null);
    }

    /**
     * handles the event when someone clicks one of the poi item
     *
     * @param epoiType type of poi
     * @param imageId the poi item's image element id
     * @param imagePath1 path to the default image
     * @param imagePath2 path to the selected image
     */
    function m_poiItemClickHandler(title,epoiType, imageId, imagePath1,imagePath2,itemDivId)
    {
        //the item has been clicked so we have to assume the toggle state has been reveresed
        var isToggled=!poiToggles[epoiType];

        if ((mapManager.Map.GetZoomLevel() < 12) && (isToggled)) {
            this.showMaplevelAlert(epoiType);            
            return;
        }

        this.styleCarouselPoi(epoiType, itemDivId, isToggled, imageId, imagePath1, imagePath2);
         
        //show POI on the map
        if((epoiType!=null) && (epoiType!=""))
        {
            TogglePOI(epoiType, isToggled);
        }
        
        // Attach to map events if not already done so
        if (!eventsAttached)
        {
            mapManager.Map.AttachEvent('onendpan',ShowToggledPOIsOnMap);
            mapManager.Map.AttachEvent('onendzoom',ShowToggledPOIsOnMap);
            
            eventsAttached = true;
        }
    }
    
    /**
     * Perform Driving Directions search with specified input from/to specific POI
     *
     * @param key - unique id of poi (\POI\d+||\d+\)
     */
     function GDDForPOIPopup(mode, key)
     //function GDDForPOIPopup(mode, index)
     {
        var startAddress;
        var endAddress;

        var indexTypeArray = key.match(/POI(\d+)\|\|(\d+)/i);
        var typeId = indexTypeArray[1];
        var index = indexTypeArray[2];

        if (g_POIs[typeId].length - 1 < index)
        //if (g_POIs.length - 1 <= index)
        {
            return;
        }
        var currentPOI = g_POIs[typeId][index];
        //var currentPOI = g_POIs.DataList[index];
        if (mode == 'TO')
        {
            startAddress = document.getElementById('p_toAddress' + key).value;
            //startAddress = document.getElementById('p_toAddress' + index).value;
            //replace new line characters with commas
            endAddress = currentPOI.Address.replace(/\r\n/g, ", ") + "@" + currentPOI.Latitude + "," + currentPOI.Longitude; 
            
            if (startAddress.trim() == '') return;
        } 
        else
        {
            endAddress = document.getElementById('p_fromAddress' + key).value;
            //endAddress = document.getElementById('p_fromAddress' + index).value;
            //replace new line characters with commas
            startAddress = currentPOI.Address.replace(/\r\n/g, ", ") + "@" + currentPOI.Latitude + "," + currentPOI.Longitude;
            
            if (endAddress.trim() == '') return;
        }
         
        // Hide current popup 
        HideCurrentEro(null);
        
        TopNav('DrivingDirections');
        document.getElementById("txtFrom").value = startAddress;
        document.getElementById("txtTo").value = endAddress;
        mapManager.GetNewDirections();
     }
     
     /** 
      * Get 'what's nearby' for specific POI
     *
     * @param key - unique id of poi (\POI\d+||\d+\)
     */
     function GNBForPOIPopup(key)
     //function GNBForPOIPopup(index)
     {
        var indexTypeArray = key.match(/POI(\d+)\|\|(\d+)/i);
        var typeId = indexTypeArray[1];
        var index = indexTypeArray[2];

        var txtNB = document.getElementById('p_nearby' + key).value;
        //var txtNB = document.getElementById('p_nearby' + index).value;
        if (txtNB.trim() == '')
        {
            return;
        }
        if (g_POIs[typeId].length - 1 < index)
        //if (g_POIs.length - 1 <= index)
        {
            return;
        }
        var currentPOI = g_POIs[typeId][index];

        document.getElementById('txtBusLocation').value = (Math.round(currentPOI.Latitude*100)/100) + ", " + (Math.round(currentPOI.Longitude*100)/100);
        document.getElementById('txtBusName').value = txtNB;
        mapManager.NewFindBusiness();
     }
     
    /**
    * Save POI Pin to user map
    *
    * @param key - unique id of poi (\POI\d+||\d+\)
    */
    function SavePOIToCustomMap(key,lat,lon,title,description,image)
    //function SavePOIToCustomMap(index,lat,lon,title,description,image)
    {
        var mapSelector = document.getElementById('mapSelect');
        var selectedMapId = mapSelector.options[mapSelector.selectedIndex].value;
      
        var indexTypeArray = key.match(/POI(\d+)\|\|(\d+)/i);
        var typeId = indexTypeArray[1];
        var index = indexTypeArray[2];

        if (typeof (g_POIs[typeId]) != 'undefined' && g_POIs[typeId].length > 0)
        //if (typeof (g_POIs) != 'undefined' && g_POIs.length > 0)
        {
            var currentPOI = g_POIs[typeId][index];
            PersistenceManager.SaveMapLocationDetailed(selectedMapId, currentPOI.Latitude, currentPOI.Longitude, 
                currentPOI.Name, currentPOI.Address, 'Images/' + GetIcon(currentPOI.POIType));
        }
        else if(lat != null && lon != null)
        {
            PersistenceManager.SaveMapLocationDetailed(selectedMapId, lat, lon, title, description, image);
        }
    }
}
