WoWInterface SVN MetaMapv4.0

[/] [trunk/] [MetaMap/] [MetaMap.lua] - Rev 164

Compare with Previous | Blame | View Log

--- MetaMap
--- Written by MetaHawk - aka Urshurak
--- Fan Update (hopefully temporary) by Charroux/Tallspirit
--- Fan Update (not temporary) by mbanks850 and Andymon

-- *** includes a fix for the taintLog bug described by http://us.battle.net/wow/en/forum/topic/6413024501 ***

METAMAP_TITLE = "MetaMap";
METAMAP_VERSION = GetAddOnMetadata("MetaMap", "Version");

METAMAP_NAME = METAMAP_TITLE.."  v"..METAMAP_VERSION;
METAMAPPOI_NAME = "MetaMapPOI";
METAMAP_ICON = "Interface\\WorldMap\\UI-World-Icon";
METAMAP_MAP_PATH = "Interface\\AddOns\\MetaMap\\Maps\\";
METAMAP_ICON_PATH = "Interface\\AddOns\\MetaMap\\Icons\\";
METAMAP_IMAGE_PATH = "Interface\\AddOns\\MetaMap\\Images\\"
METAMAP_SHADER_PATH = "Interface\\AddOns\\MetaMap\\Shaders\\"
METAMAP_MAPCREDITS = "Maps created by Nifl";
METAMAP_TITAN_ID = METAMAP_TITLE;
METAMAP_TITAN_FREQUENCY = 1;

METAMAP_MENUBUTTON_HEIGHT = 16;
METAMAP_LISTBUTTON_HEIGHT = 20;
METAMAP_LISTBUTTON_SHOWN = 30;
METAMAP_TT_NAME = nil;
METAMAP_POS_UPDATED = nil;

MetaMap_Details = {
        name = METAMAP_TITLE,
        description = METAMAP_DESC,
        version = METAMAP_VERSION,
        releaseDate = "November 21, 2010",
        author = "Mbanks850 (original by MetaHawk)",
        email = "mbanks850@gmail.com (original by admin@metaserve.org.uk)",
        website = "",
        category = MYADDONS_CATEGORY_MAP,
}

MetaMap_Continents = {};
MetaMap_Notes = {};
MetaMap_Lines = {};
MetaMap_MiniNote_Data = {};
MetaMap_NoteFilter = {};
local MetaMap_NoteList = {};
local MetaMap_Relocate = {};
local MetaMap_LastLineClick = {};
local MetaMap_PartyNoteData = {};
MetaMap_ZoneErrata = nil;

MetaMap_ListOffset = 0;
MetaMap_PingTime = 15;
MetaMap_gPingPOI = nil;
MetaMap_FullScreenMode = false;
MetaMapContainer_CurrentFrame = nil;
MetaMap_MenuParent = "cursor";
MetaMap_sortDone = true;
MetaMap_sortType = METAMAP_SORTBY_NAME;
MetaMap_Qnote = false;
MetaMap_PartyNoteSet = false;
MetaMap_LastLineClick.time = 0;
MetaMap_TempData_Id = "";
MetaMap_TempData_Zone = "";
MetaMap_TempData_Name = "";
MetaMap_TempData_Creator = "";
MetaMap_TempData_xPos = "";
MetaMap_TempData_yPos = "";
MetaMap_TempData_Icon = "";
MetaMap_TempData_TextColor = "";
MetaMap_TempData_Info1Color = "";
MetaMap_TempData_Info2Color = "";
MetaMap_TempData_LootID = nil;
MetaMap_MiniNote_IsInCity = false;
MetaMap_MiniNote_MapzoomInit = false;
MetaMap_SetNextAsMiniNote = 0;
MetaMap_Orphans = 0;
MetaMap_Timer_DelayWKB_AddUnitInfo = nil;

MetaMap_BaseMap = {};
MetaMap_CurrentMap = {};
local MetaMap_OldMap = {};
local MetaMap_SavedLook = {};
local MetaMap_SavedMap = {};
local MetaMap_SavedMapTime = 0;
local MetaMap_ReturnMap = {};
local MetaMap_QuestID = -1;
local MetaMap_SavedQuestID = -1;

local MetaMap_VarsLoaded = false;
local MetaMap_FilterName = "";
MetaMap_CurrentSaveSet = 1;
local MetaMap_StayOnMap = false;
local MetaMap_MapClick = false;
local MetaMap_NoOldMap = false;
local WORLD_MAP_UPDATE_event_restart = false;
local MetaMap_InstanceOff = false;
local MetaMap_MapRefresh = false;
local MetaMapTopFrame_Visible = false;
local MataMapMainMenu_Visible = false;

MetaMap_WorldMap_baseScale = 0;
local MetaMap_oldScale = 0;
local MetaMap_oldScrollH = 0;
local MetaMap_oldScrollV = 0;

MetaMap_CurrentAction = false;
local MetaMap_LastNote = 0;
local MetaMap_LastLine = 0;
local MetaMap_OrigChatFrame_OnEvent;
local MetaMap_MinDiff = 7
local MetaMap_vnote_xPos = nil;
local MetaMap_vnote_yPos = nil;
local MetaMap_Drawing = nil;
local MetaMap_Timer_DelayLoadModules = 5.0;
local MetaMap_Tracker = false;
local MetaMap_Reshow_BattlefiedMap;

MetaMap_time = 0;

-- *** taintLog fix ***
local MetaMap_taintLog_Set = "0";

MetaMap_Default = {
        ["SaveSet"] = 1,
        ["MetaMapAlpha1"] = 1.0,
        ["MetaMapAlpha2"] = 0.60,
        ["BDshader1"] = 0.0,
        ["BDshader2"] = 0.0,
        ["MetaMapPos1"] = { -1, -1 },
        ["MetaMapPos2"] = { -1, -1 },
        ["MetaMapScale1"] = 0.75,
        ["MetaMapScale2"] = 0.55,
        ["MetaMapTTScale1"] = 1.0,
        ["MetaMapTTScale2"] = 0.75,
        ["ContainerAlpha"] = 0,
        ["ActionMode1"] = false,
        ["ActionMode2"] = false,
        ["MetaMapButtonPosition"] = 138,
        ["MiniColor"] = 4,
        ["MenuFont"] = 10,
        ["MetaMapZone"] = nil,
        ["MetaMapCoords"] = true,
        ["MetaMapMiniCoords"] = true,
        ["MetaMapZoomIn"] = false,
        ["MetaMapButtonShown"] = true,
        ["MapChange"] = true,
        ["TooltipWrap"] = true,
        ["ShowCreator"] = true,
        ["MenuMode"] = false,
        ["ShowMapList"] = true,
        ["LastHighlight"] = true,
        ["LastMiniHighlight"] = true,
        ["NoteSize"] = 16,
        ["AcceptIncoming"] = true,
        ["MiniParty"] = true,
        ["ListColors"] = true,
        ["ZoneHeader"] = false,
        ["SortList"] = false,
        ["UsePOI"] = false,
        ["WKBalwaysOn"] = false,
        ["QSTalwaysOn"] = false,
        ["FWMalwaysOn"] = false,
        ["BWPalwaysOn"] = false,
        ["NBKalwaysOn"] = false,
        ["TRKalwaysOn"] = false,
}
MetaMap_MainMenuData = {
        [1]  = {text = METAMAP_MENU_MAPCRD,    opt = "MetaMapCoords",         ksoc = 1, mode = 1},
        [2]  = {text = METAMAP_MENU_MINCRD,    opt = "MetaMapMiniCoords",     ksoc = 1, mode = 1},
        [2]  = {text = METAMAP_MENU_ZOOMIN,    opt = "MetaMapZoomIn",         ksoc = 1, mode = 1},
        [3]  = {text = METAMAP_MENU_ACTION,    opt = "MetaMap_ActionToggle",  ksoc = 1, mode = 2},
        [4]  = {text = METAMAP_MENU_MAPSET,    opt = "MetaMapSaveSet_Toggle", ksoc = 1, mode = 2},
        [5]  = {text = METAMAP_MENU_FWMMOD,    opt = "MetaMap_LoadFWM",       ksoc = 1, mode = 2},
        [6]  = {text = METAMAP_MENU_TRKSET,    opt = "MetaMap_SetTracker",    ksoc = 1, mode = 2},
        [7]  = {text = "",                                                    ksoc = 1, nc = 1},
        [8]  = {text = METAMAP_MENU_FILTER,    opt = METAMAP_MENU_FILTER,     ksoc = 1, ha = 1},
        [9]  = {text = METAMAP_MENU_TRKFILTER, opt = METAMAP_MENU_TRKFILTER,  ksoc = 1, ha = 1},
        [10] = {text = "",                                                    ksoc = 1, nc = 1},
        [11] = {text = METAMAP_MENU_EXTOPT,    opt = "MetaMapExtOptions_Toggle",        mode = 2},
        [12] = {text = METAMAP_MENU_FLIGHT,    opt = "MetaMap_FlightMapOptions_Toggle",         mode = 2},
        [13] = {text = METAMAP_MENU_TRKMOD,    opt = "MetaMap_LoadTRK",                 mode = 2},
        [14] = {text = METAMAP_MENU_BWPMOD,    opt = "MetaMap_LoadBWP",                 mode = 2},
        [15] = {text = METAMAP_MENU_WKBMOD,    opt = "MetaMap_LoadWKB",                 mode = 2},
        [16] = {text = METAMAP_MENU_QSTMOD,    opt = "MetaMap_LoadQST",                 mode = 2},
        [17] = {text = METAMAP_MENU_NBKMOD,    opt = "MetaMap_LoadNBK",                 mode = 2},
};

function MetaMap_SetWorldMap()
        MiniMapWorldMapButton:Hide();

--old   hooksecurefunc("WorldMapFrame_ToggleWindowSize", MetaMap_FullScreenToggle);
        -- hooksecurefunc is not working for functions called directly by XML code, thats use additional:
        WorldMapFrame.BorderFrame.MaximizeMinimizeFrame.MinimizeButton:HookScript("OnClick", MetaMap_FullScreenToggle);
        WorldMapFrame.BorderFrame.MaximizeMinimizeFrame.MaximizeButton:HookScript("OnClick", MetaMap_FullScreenToggle);

        -- update the lines at change of the world map zoom
--old   WorldMapScrollFrame:HookScript("OnMouseWheel", MetaMap_MainMapUpdate);
        WorldMapFrame.ScrollContainer:HookScript("OnMouseWheel", MetaMap_MainMapUpdate);
        WorldMapFrame.ScrollContainer:HookScript("OnMouseDown", MetaMap_ProcessMapClick);

--old   MetaMap_SetFrameStrata();

        MetaMap_WorldMapFrame_OnKeyDown_old = WorldMapFrame:GetScript("OnKeyDown");
        MetaMap_FullScreenToggle();

        MetaMap_GameToolTip_OnShow_old = GameTooltip:GetScript("OnShow");
        if (MetaMap_GameToolTip_OnShow_old) then
                GameTooltip:SetScript("OnShow", function(self) METAMAP_TT_NAME = GameTooltipTextLeft1:GetText(); MetaMap_GameToolTip_OnShow_old(self); end);
        else
                GameTooltip:SetScript("OnShow", function(self) METAMAP_TT_NAME = GameTooltipTextLeft1:GetText(); end);
        end

-- executed to late:
--#     hooksecurefunc(GameTooltip,"Show", function(self) METAMAP_TT_NAME = GameTooltipTextLeft1:GetText(); end);

        --WorldMapFrame:HookScript("OnUpdate", function () MetaMapWorldMapFrame_OnUpdate() end);
        hooksecurefunc(WorldMapFrame, "Show", MetaMapTopFrame_OnShow);
        hooksecurefunc(WorldMapFrame, "Hide", MetaMapTopFrame_OnHide);

--old   MetaMap_SetMapToCurrentZone();
end

function MetaMapButton_OnClick()
        MetaMap_Debug_Print("MetaMapButton_OnClick",true);
        MetaMap_ToggleFrame(WorldMapFrame);
end

function MetaMap_OnLoad(self)
        hooksecurefunc("ToggleDropDownMenu", MetaMap_ToggleDropDownMenu);

--old   hooksecurefunc("WorldMapZoomOutButton_OnClick", MetaMap_WorldMapZoomOutButton_OnClick);
        WorldMapFrame.ScrollContainer:HookScript("OnMouseUp", MetaMap_WorldMapZoomOutButton_OnClick);
        QuestMapFrame:HookScript("OnMouseUp", MetaMap_QuestMapFrame_OnMouseUp);

--#     hooksecurefunc("QuestMapFrame_CloseQuestDetails", MetaMap_QuestMapFrame_CloseQuestDetails);
        QuestMapFrame.DetailsFrame.BackButton:HookScript("OnClick", MetaMap_QuestMapFrameDetailsFrameBackButton_OnClick);
--old   WorldMapScrollFrame:HookScript("OnMouseWheel", MetaMap_WorldMapScrollFrame_OnMouseWheel);
        WorldMapFrame.ScrollContainer:HookScript("OnMouseWheel", MetaMap_WorldMapScrollFrame_OnMouseWheel);
--old   hooksecurefunc("WorldMapScrollFrame_OnPan", MetaMap_WorldMapScrollFrame_OnPan);
--???   WorldMapFrame.ScrollContainer:HookScript("IsPanning", MetaMap_WorldMapScrollFrame_OnPan);

--old   hooksecurefunc("QuestLogQuests_GetHeaderButton", MetaMap_QuestLogQuests_GetHeaderButton);
--???
--old   hooksecurefunc("QuestLogQuests_GetTitleButton", MetaMap_QuestLogQuests_GetTitleButton);
--???

        hooksecurefunc("NavBar_ClearTrailingButtons", MetaMap_NavBar_ClearTrailingButtons);
--old   hooksecurefunc("WorldMapLevelButton_OnClick", MetaMap_WorldMapLevelButton_OnClick);

--old   AzerothButton:HookScript("OnClick", MetaMap_WorldMapAreaButton_OnClick);
--???
--old   OutlandButton:HookScript("OnClick", MetaMap_WorldMapAreaButton_OnClick);
--???
--old   DraenorButton:HookScript("OnClick", MetaMap_WorldMapAreaButton_OnClick);
--???

--old   TheMaelstromButton:HookScript("OnClick", MetaMap_WorldMapAreaButton_OnClick);
--???
--old   DeepholmButton:HookScript("OnClick",     MetaMap_WorldMapAreaButton_OnClick);
--???
--old   KezanButton:HookScript("OnClick",        MetaMap_WorldMapAreaButton_OnClick);
--???
--old   LostIslesButton:HookScript("OnClick",    MetaMap_WorldMapAreaButton_OnClick);
--???

        self:RegisterEvent("ADDON_LOADED");
        self:RegisterEvent("VARIABLES_LOADED");
        self:RegisterEvent("UPDATE_BINDINGS");
--old   self:RegisterEvent("WORLD_MAP_UPDATE");
        WorldMapFrame.ScrollContainer:HookScript("OnUpdate", MetaMap_WORLD_MAP_UPDATE);
        self:RegisterEvent("ZONE_CHANGED_NEW_AREA");
        self:RegisterEvent("ZONE_CHANGED");
        self:RegisterEvent("ZONE_CHANGED_INDOORS");
        self:RegisterEvent("PLAYER_ENTERING_WORLD");
        self:RegisterEvent("MINIMAP_UPDATE_ZOOM");
        self:RegisterEvent("CHAT_MSG_ADDON");
        self:RegisterEvent("PLAYER_LOGOUT");
        if(IsAddOnLoaded("FuBar")) then MetaMap_FuBar_OnLoad(); end

        -- *** taintLog fix ***
        MetaMap_UIDropDownMenu_GetSelectedID_Original = UIDropDownMenu_GetSelectedID;
        MetaMap_UIDropDownMenu_ClearAll_Original = UIDropDownMenu_ClearAll;
        if ( GetCVar("taintLog") ~= "0" ) then
                MetaMap_taintLog_Set = GetCVar("taintLog");
                UIDropDownMenu_GetSelectedID = MetaMap_UIDropDownMenu_GetSelectedID;
                UIDropDownMenu_ClearAll = MetaMap_UIDropDownMenu_ClearAll;
        end
end

-- *** taintLog fix *** this is a copy of original function UIDropDownMenu_ClearAll without modifications
function MetaMap_UIDropDownMenu_ClearAll(frame)
        -- Previous code refreshed the menu quite often and was a performance bottleneck
        frame.selectedID = nil;
        frame.selectedName = nil;
        frame.selectedValue = nil;
        UIDropDownMenu_SetText(frame, "");

        local button, checkImage, uncheckImage;
        for i=1, UIDROPDOWNMENU_MAXBUTTONS do
                button = _G["DropDownList"..UIDROPDOWNMENU_MENU_LEVEL.."Button"..i];
                button:UnlockHighlight();

                checkImage = _G["DropDownList"..UIDROPDOWNMENU_MENU_LEVEL.."Button"..i.."Check"];
                checkImage:Hide();
                uncheckImage = _G["DropDownList"..UIDROPDOWNMENU_MENU_LEVEL.."Button"..i.."UnCheck"];
                uncheckImage:Hide();
        end
end

-- *** taintLog fix *** this is a copy of original function UIDropDownMenu_GetSelectedID without modifications
function MetaMap_UIDropDownMenu_GetSelectedID(frame)
        if ( frame.selectedID ) then
                return frame.selectedID;
        else
                -- If no explicit selectedID then try to send the id of a selected value or name
                local button;
                for i=1, UIDROPDOWNMENU_MAXBUTTONS do
                        button = _G["DropDownList"..UIDROPDOWNMENU_MENU_LEVEL.."Button"..i];
                        -- See if checked or not
                        if ( UIDropDownMenu_GetSelectedName(frame) ) then
                                if ( button:GetText() == UIDropDownMenu_GetSelectedName(frame) ) then
                                        return i;
                                end
                        elseif ( UIDropDownMenu_GetSelectedValue(frame) ) then
                                if ( button.value == UIDropDownMenu_GetSelectedValue(frame) ) then
                                        return i;
                                end
                        end
                end
        end
end

function MetaMapContainerFrame_OnLoad(frame)
        frame:SetWidth(WorldMapFrame.ScrollContainer:GetWidth() - MetaMap_MapListFrame:GetWidth()-1);
        frame:SetHeight(WorldMapFrame.ScrollContainer:GetHeight()-41);
        frame:SetFrameLevel(frame:GetParent():GetFrameLevel()+3);
        MetaMapContainer_Header:SetFrameLevel(frame:GetFrameLevel()+2);
        MetaMapContainer_Footer:SetFrameLevel(frame:GetFrameLevel()+2);
        MetaMapContainer_CloseButton:SetFrameLevel(MetaMapContainer_Footer:GetFrameLevel()+2);
end

--[[ left for debugging
function MetaMapWorldMapFrame_OnUpdate(self,elapsed)
        -- MetaMap_Debug_Print("WorldMapFrame_OnUpdate:",true);
        point, relativeTo, relativePoint, xOfs, yOfs = WorldMapPing:GetPoint();
        if (relativeTo ~= nil) then
                DEFAULT_CHAT_FRAME:AddMessage("Ping: "..point..","..relativeTo:GetName()..","..relativePoint..","..xOfs..","..yOfs);
        end

        point, relativeTo, relativePoint, xOfs, yOfs = WorldMapPlayerLower:GetPoint();
        if (relativeTo ~= nil) then
                DEFAULT_CHAT_FRAME:AddMessage("Arrow: "..point..","..relativeTo:GetName()..","..relativePoint..","..xOfs..","..yOfs);
                WorldMapPlayerLower:ClearAllPoints();
                PositionWorldMapArrowFrame("center","WorldMapDetailFrame","topleft",xOfs,yOfs);
                WorldMapPlayerLower:ClearAllPoints();
                WorldMapPlayerLower:SetPoint("center",WorldMapDetailFrame,"topleft",500,-308);
                UpdateWorldMapArrow();
                point, relativeTo, relativePoint, xOfs, yOfs = WorldMapPlayerLower:GetPoint();
                DEFAULT_CHAT_FRAME:AddMessage("ArrowAfter: "..point..","..relativeTo:GetName()..","..relativePoint..","..xOfs..","..yOfs);
        end
end
]]--

function MetaMapTopFrame_OnShow(self)
        if ( MetaMapTopFrame_Visible ) then return; end
        if ( not MetaMapTopFrame_Visible ) then MetaMap_InitializeMenu(); end

        MetaMap_Debug_Print("MetaMapTopFrame_OnShow",true);

        if ( not MetaMap_FullScreenMode and not InCombatLockdown()) then
                MetaMap_ToggleDR(self,1);
                MiniMapWorldMapButton:Hide();
                MetaMapOptions_Init();
                MetaMapList_Init();
                MetaMap_InfoLineFrame:SetFrameLevel(WorldMapFrame:GetFrameLevel()+3);
                MetaMap_Debug_Print("MetaMapTopFrame_OnShow: Updating Quests",true);
        end
--old   WorldMapFrameTutorialButton:Hide();
        WorldMapFrame.BorderFrame.Tutorial:Hide();

        if (not MetaMap_VarsLoaded) then return; end

        if (BattlefieldMinimap and BattlefieldMinimap:IsVisible()) then
                if (not MetaMap_CombatLockdown_BattlefiedMap) then
                        MetaMap_Reshow_BattlefiedMap = time();
                else
                        MetaMap_CombatLockdown_BattlefiedMap = nil;
                        MetaMap_Reshow_BattlefiedMap = nil;
                end
                BattlefieldMinimap:Hide();
        end

        if ( not MetaMapTopFrame_Visible ) then
                StaticPopup1:SetFrameStrata("FULLSCREEN");
                if (MetaMap_FullScreenMode or InCombatLockdown()) then
                        MetaMapNotesEditFrame:SetParent(WorldMapFrame);
                        MetaMap_SendFrame:SetParent(WorldMapFrame);
                end
        end

        MetaMapTopFrame_Visible = true;

        MetaMap_SetMapToCurrentZone();
        MetaMap_MainMapUpdate();

        if ( MetaMapOptions.MetaMapZoomIn ) then MetaMap_WorldMapScrollFrame_MaxZoom(); end
end

function MetaMapTopFrame_OnHide(self)
        MetaMap_Debug_Print("MetaMapTopFrame_OnHide: SaveSet:"..MetaMap_CurrentSaveSet,true);

        MetaMapTopFrame_Visible = false;
        MataMapMainMenu_Visible = false;
        MetaMap_StayOnMap = false;
        MetaMap_MapClick = false;
        MetaMapOptions.SaveSet = MetaMap_CurrentSaveSet;

        MetaMap_CurrentMap = {};
        MetaMap_SavedLook = {};
        MetaMap_SavedMap = {};
        MetaMap_ReturnMap = {};
        MetaMap_WorldMapScrollFrame_ResetZoom();
        MetaMap_HideAll();

        MetaMap_ToggleDR(self,0);
        StaticPopup1:SetFrameStrata("DIALOG");
        MetaMapNotesEditFrame:SetParent(UIParent);
        MetaMapNotesEditFrame:SetFrameStrata("FULLSCREEN");
        MetaMap_SendFrame:SetParent(UIParent);
        MetaMap_SendFrame:SetFrameStrata("FULLSCREEN");
        MetaMap_SetMapToCurrentZone();

        if (BattlefieldMinimap and MetaMap_Reshow_BattlefiedMap) then
                MetaMap_Reshow_BattlefiedMap = nil;
                BattlefieldMinimap:Show();
        end
end

local MetaMapMenuInitialized = false;
function MetaMap_InitializeMenu()
        if ( MetaMapMenuInitialized == false ) then
                -- ### problematic with taintLog ###
                UIDropDownMenu_Initialize(MetaMap_MainMenu, MetaMap_MainMenu_Initialize, "MENU");
                -- ### problematic with taintLog ###
                UIDropDownMenu_Initialize(MetaMap_InstanceMenu, MetaMap_InstanceMenu_Initialize);
                --- Set the instance menu size
                UIDropDownMenu_SetWidth(MetaMap_InstanceMenu, 120);
                MetaMapMenuInitialized = true;
        end
end

function MetaMap_WORLD_MAP_UPDATE(self,elapsed)
        MetaMap_OnEvent(self, "WORLD_MAP_UPDATE");
end

local WORLD_MAP_UPDATE_event_look = false;
-- skip the required delay for map changes in case of a zone change
local MetaMap_ZONE_CHANGE = false;
function MetaMap_OnEvent(self, event, ...)
        local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11 = ...;
        if (event == "ADDON_LOADED" and arg1 == "MetaMap") then
                MetaMapOptions.ShowDNI = false;

                for option, value in pairs(MetaMap_Default) do
                        if (MetaMapOptions[option] == nil) then MetaMapOptions[option] = value; end
                end
                MetaMap_Default = nil;
                MetaMap_LoadZones();
                MetaMap_InitializeMenu();

        elseif (event == "VARIABLES_LOADED") then
                MetaMap_SetWorldMap();

--[[old
                -- Prevents taint from expanding menus past blizzard's MAXBUTTONS, also fixes an init issue with menus longer than 17.
                if ( UIDROPDOWNMENU_MAXBUTTONS < 29 ) then
                        local toggle;
                        if ( not WorldMapFrame:IsVisible() ) then
                                -- ### problematic with taintLog ###
                                ToggleFrame(WorldMapFrame);
                                toggle = true;
                        end
                        SetMapZoom(2);
                        if ( toggle ) then
                                -- ### problematic with taintLog ###
                                ToggleFrame(WorldMapFrame);
                        end
                end
--]]

                MetaMap_CurrentSaveSet = MetaMapOptions.SaveSet;
                MetaMap_ModeToggleButton:SetText(MetaMapOptions.SaveSet);

                if (myAddOnsFrame_Register) then
                        myAddOnsFrame_Register(MetaMap_Details);
                end
                if (MetaMap_MiniNote_Data.icon == "party") then
                        MetaMap_ClearMiniNote(true);
                end
                if (MetaMap_MiniNote_Data.icon ~= nil) then
                        MetaMap_MiniNoteTexture:SetTexture(METAMAP_ICON_PATH.."Icon"..MetaMap_MiniNote_Data.icon);
                end
                MetaMap_CommandsInit();

                MetaMap_WorldMapButton_OnClick_old = WorldMapButton_OnClick;
                WorldMapButton_OnClick = MetaMap_WorldMapButton_OnClick;

                MetaMap_OrigChatFrame_OnEvent = ChatFrame_MessageEventHandler;
                ChatFrame_MessageEventHandler = MetaMap_ChatFrame_OnEvent;

-- shifted to PLAYER_ENTERING_WORLD, because the worldMapFrame is not fully initialized yet
--old           MetaMap_MiniNote.TimeSinceLastUpdate = 0;
--old           for i=0, 9, 1 do
--old                   if (MetaMap_NoteFilter[i] == nil) then MetaMap_NoteFilter[i] = true; end
--old           end
--old           if (not MetaMapOptions.MetaMapZone) then
--old                   MetaMapOptions.MetaMapZone = MetaMap_ZoneTable[110][MetaMap_Locale];
--old           end
--old           if (not MetaMapOptions.MetaMapLevel) then MetaMapOptions.MetaMapLevel = 0; end
--old           if ( not MetaMapOptions.oldScrollH ) then MetaMapOptions.oldScrollH = 0; end
--old           if ( not MetaMapOptions.oldScrollV ) then MetaMapOptions.oldScrollV = 0; end
--old           if ( not MetaMapOptions.oldScale )   then MetaMapOptions.oldScale = WorldMapFrame:GetScale(); end
--old           MetaMap_ZoneCapture = nil;

-- shifted to PLAYER_ENTERING_WORLD, because the worldMapFrame is not fully initialized yet
--old           MetaMapOptions_Init();
--old           MetaMapList_Init();

--old           -- check if MobMap is installed and using its internal quest tracker
--old           if ( mobmap_use_questtracker ) then
--old                   MetaMap_Print(METAMAP_MOBMAP_QUESTTRACKER_WARNING, true, 1, 0, 0);
--old                   mobmap_use_questtracker = false;
--old                   MobMap_QuestTracker_Setup();
--old           end
                MetaMap_VarsLoaded = true;
        elseif (event == "WORLD_MAP_UPDATE") then
                if (not MetaMap_VarsLoaded) then return; end
                MetaMap_Debug_Print("WORLD_MAP_UPDATE", true);

                -- in case look is active, save map data for later execution
                if ( WorldMapFrame:IsVisible() and not MetaMapOptions.MapChange and (WORLD_MAP_UPDATE_event_look or WORLD_MAP_UPDATE_event_restart) ) then
                        MetaMap_SavedLook = MetaMap_SaveCurrentMapData();
                end

                -- look the routine, that only one instance is running at time
                if ( WORLD_MAP_UPDATE_event_look or WORLD_MAP_UPDATE_event_restart ) then return; end
                WORLD_MAP_UPDATE_event_look = true;

                if ( WorldMapFrame:IsVisible() ) then
                        local skip = false;
                        if ( MetaMap_NoOldMap ) then
                                if ( MetaMap_CurrentMap.Name == MetaMap_OldMap.Name ) then skip = true; end
                        end
                        if ( MetaMap_StayOnMap and not skip ) then
                                MetaMap_SavedMap = MetaMap_SetMapAfterRefresh(self);
                                if ( MataMapMainMenu_Visible ) then
                                        local listFrame = _G["DropDownList1"];
                                        if ( not listFrame:IsVisible() ) then
                                                ToggleDropDownMenu(nil, nil, MetaMap_MainMenu, MetaMap_MenuParent, 0, 0);
                                        end
                                end
                                if ( next(MetaMap_SavedMap) ) then
                                        if ( not MetaMap_ZONE_CHANGE ) then MetaMap_SavedMapTime = MetaMap_time + 2.0; end
                                        if ( MetaMap_SavedQuestID ~= -1 ) then
                                                QuestMapFrame_ShowQuestDetails(MetaMap_SavedQuestID);
                                        end
                                        if ( (MetaMap_QuestID ~= -1) and not MetaMap_MapClick ) then
                                                MetaMap_ReturnMap = MetaMap_CopyMapData(MetaMap_SavedMap);
                                                MetaMap_SavedLook = {};
                                                QuestMapFrame_ShowQuestDetails(MetaMap_QuestID);
                                                MetaMap_SavedQuestID = MetaMap_QuestID;
                                                MetaMap_QuestID = -1;
                                        end
                                        if ( next(MetaMap_SavedLook) ) then
                                                if ( MetaMap_NoOldMap ) then
                                                        if ( MetaMap_SavedLook.Name == MetaMap_OldMap.Name ) then skip = true; end
                                                end
                                                if ( not skip ) then
                                                        MetaMap_CurrentMap = MetaMap_CopyMapData(MetaMap_SavedLook);
                                                end
                                                MetaMap_SavedLook = {};
                                                WORLD_MAP_UPDATE_event_restart = true;
                                        end
                                        WORLD_MAP_UPDATE_event_look = false;
                                        return
                                end
                        end
                end

                if (MetaMapOptions.UsePOI) then MetaMapPOI_OnEvent(1); end
                if (not WorldMapFrame:IsVisible()) then
                        WORLD_MAP_UPDATE_event_look = false;
                        return;
                end

                -- activation of MetaMap_StayOnMap with MetaMap_BaseMap.ID or MetaMap_CurrentMap.ID is not possible,
                -- because this variables are set little later by other events (the WORLD_MAP_UPDATE event is to early)

                local _, _, zType = MetaMap_GetZoneTableEntry(MetaMap_GetRealZoneText());
                if ( not MetaMap_StayOnMap and (zType == "DNI" or zType == "BG" or zType == "SCN" or zType == "RDI") ) then
                        MetaMapOptions.ShowDNI = true;
                        MetaMap_ShowInstance(self, true);
                end

                if (IsAddOnLoaded("MetaMapWKB") and WKB_DisplayFrame:IsVisible()) then
                        WKB_OnEvent("INSTANCE_MAP_UPDATE");
                elseif (IsAddOnLoaded("MetaMapQST") and QST_DisplayFrame:IsVisible()) then
                        QST_OnEvent("INSTANCE_MAP_UPDATE");
                elseif (IsAddOnLoaded("MetaMapTRK") and TRK_DisplayFrame:IsVisible()) then
                        --- Maintain the display.
                else
                        MetaMapContainer_ShowFrame();
                end

                if (MetaMap_InfoLineFrame:IsVisible()) then
                        MetaMap_InfoLineUpdate();
                end
                MetaMap_MainMapUpdate();
                MetaMap_ZoneSearch();
                MetaMapOptions_Init();
                MetaMapList_Init();
                if (MetaMap_gPingPOI) then
                        MetaMapPing_OnUpdate(1);
                end

                local skip = false;
                if ( MetaMap_NoOldMap ) then
                        if ( MetaMap_SavedLook.Name == MetaMap_OldMap.Name ) then skip = true; end
                end
                if ( next(MetaMap_SavedLook) ) then
                        if ( not skip ) then
                                MetaMap_CurrentMap = MetaMap_CopyMapData(MetaMap_SavedLook);
                        end
                        MetaMap_SavedLook = {};
                        WORLD_MAP_UPDATE_event_restart = true;
                end
                WORLD_MAP_UPDATE_event_look = false;
        elseif (event == "ZONE_CHANGED_NEW_AREA" or event == "ZONE_CHANGED" or event == "ZONE_CHANGED_INDOORS") then
                MetaMap_Debug_Print("ZONE_CHANGED", true);
                if (not MetaMap_VarsLoaded) then return; end

                MetaMap_ZONE_CHANGE = true;
                MetaMap_SetMapToCurrentZone(self, true);
                MetaMap_ZONE_CHANGE = false;

                MetaMap_MiniNote_OnUpdate(0);
                if (MetaMapOptions.UsePOI) then
                        MetaMapPOI_OnEvent(2);
                end

                if (WorldMapFrame:IsVisible()) then
                        MetaMap_MainMapUpdate();
                end

                MetaMap_ZoneDisplay:SetText(METAMAP_CURZONE..MetaMap_GetRealZoneText());

                if ( not WorldMapFrame:IsVisible() or not MetaMap_StayOnMap ) then
                        MetaMap_HideAll();
                end
                MetaMap_Timer_DelayWKB_AddUnitInfo = 5.0;
        elseif (event == "PLAYER_ENTERING_WORLD") then
                if (not MetaMap_VarsLoaded) then return; end

                ShowUIPanel(WorldMapFrame);
                MetaMapOptions_Init();
                MetaMapList_Init();
                HideUIPanel(WorldMapFrame);

                MetaMap_MiniNote.TimeSinceLastUpdate = 0;
                for i=0, 9, 1 do
                        if (MetaMap_NoteFilter[i] == nil) then MetaMap_NoteFilter[i] = true; end
                end
                if (not MetaMapOptions.MetaMapZone) then
                        MetaMapOptions.MetaMapZone = MetaMap_ZoneTable[110][MetaMap_Locale];
                end
                MetaMap_oldScale = MetaMap_WorldMap_baseScale;
                if (not MetaMapOptions.MetaMapLevel) then MetaMapOptions.MetaMapLevel = 0; end
                if ( not MetaMapOptions.oldScrollH ) then MetaMapOptions.oldScrollH = 0; end
                if ( not MetaMapOptions.oldScrollV ) then MetaMapOptions.oldScrollV = 0; end
                if ( not MetaMapOptions.oldScale )   then MetaMapOptions.oldScale = MetaMap_oldScale; end
                MetaMap_ZoneCapture = nil;

--old           if (not MetaMap_GetRealZoneText()) then return; end

                MetaMap_SetMapToCurrentZone();

                if ( MetaMap_GetRealZoneText() ) then
                        MetaMap_ZoneDisplay:SetText(METAMAP_CURZONE..MetaMap_GetRealZoneText());
                end
                MetaMap_Timer_DelayWKB_AddUnitInfo = 5.0;
        elseif (event == "MINIMAP_UPDATE_ZOOM") then
                MetaMap_MinimapUpdateZoom();
        elseif (event == "CHAT_MSG_ADDON" and arg1 == "MetaMap:MN") then
                MetaMap_GetNoteFromChat(arg2, arg4);
        elseif ( event == "PLAYER_LOGOUT" ) then
                local point, _, relativePoint, xOffset, yOffset = WorldMapFrame:GetPoint(1);
                MetaMap_Options.WorldMapPoint = point;
                MetaMap_Options.WorldMapRelative = relativePoint;
                MetaMap_Options.WorldMapXoffset = xOffset;
                MetaMap_Options.WorldMapYoffset = yOffset;
        end
end

function MetaMap_ChatFrame_OnEvent(self, event, ...)
        local arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13 = ...;
        if (event == "CHAT_MSG_WHISPER" and string.find(arg1, "<MetaMap:MN>")) then
                if (arg2 ~= UnitName("player")) then
                        MetaMap_GetNoteFromChat(arg1, arg2);
                end
        elseif (event == "CHAT_MSG_WHISPER_INFORM" and string.find(arg1, "<MetaMap:MN>")) then
                --- Discard the return info
        else
                MetaMap_OrigChatFrame_OnEvent(self, event, ...);
        end
end

local MetaMap_RealZoneText = " ";
local MetaMap_IsInside = true;
local MetaMap_IsMicroDungeon = false;
local MetaMap_RealZoneTimer;
local MetaMap_WaitTimer = 1;
function MetaMap_OnUpdate(self, elapsed)
        if ( not MetaMap_VarsLoaded ) then return; end
        MetaMap_time = MetaMap_time + elapsed;

        -- *** taintLog fix ***
        if ( GetCVar("taintLog") ~= MetaMap_taintLog_Set ) then
                if ( GetCVar("taintLog") == "0") then
                        MetaMap_taintLog_Set = GetCVar("taintLog");
                        UIDropDownMenu_ClearAll = MetaMap_UIDropDownMenu_ClearAll_Original;
                        UIDropDownMenu_GetSelectedID = MetaMap_UIDropDownMenu_GetSelectedID_Original;
                else
                        MetaMap_taintLog_Set = GetCVar("taintLog");
                        UIDropDownMenu_GetSelectedID = MetaMap_UIDropDownMenu_GetSelectedID;
                        UIDropDownMenu_ClearAll = MetaMap_UIDropDownMenu_ClearAll;
                end
        end

        -- in case the option MetaMapOptions.MapChange is set, disable MetaMap_StayOnMap
        if ( MetaMapOptions.MapChange and MetaMap_StayOnMap ) then
                MataMapMainMenu_Visible = false;
                MetaMap_StayOnMap = false;
                MetaMap_MapClick = false;
                MetaMap_SavedMap = {};
        end

        -- process map clicks in case MetaMap_StayOnMap is active
        if ( MetaMap_StayOnMap and MetaMap_MapClick ) then
                if ( next(MetaMap_SavedMap) ) then
                        MetaMap_NoOldMap = true;
                        MetaMap_CurrentMap = MetaMap_CopyMapData(MetaMap_SavedMap);
                        MetaMap_HideAll();
                        MetaMap_SavedQuestID = -1;
                        MetaMap_MapClick = false;
                        if ( MetaMap_InstanceOff ) then MetaMapOptions.ShowDNI = false; end
                        MetaMap_InstanceOff = false;
                        MetaMap_MapRefresh = false;
                        MetaMap_OnEvent(self, "WORLD_MAP_UPDATE");
                        return;
                else
                        if ( MetaMap_MapRefresh ) then
                                MetaMap_OnEvent(self, "WORLD_MAP_UPDATE");
                                MetaMap_MapRefresh = false;
                                return;
                        end
                        MetaMap_ReturnMap = {};
                        MetaMap_SavedQuestID = -1;
                        MetaMap_MapClick = false;
                        MetaMap_InstanceOff = false;
                end
        end

        -- trigger the event WORLD_MAP_UPDATE if requested
        if ( WORLD_MAP_UPDATE_event_restart ) then
                if ( (MetaMap_SavedMapTime == 0) or (MetaMap_SavedMapTime - 1.0 < MetaMap_time) ) then
                        WORLD_MAP_UPDATE_event_restart = false;
                        MetaMap_OnEvent(self, "WORLD_MAP_UPDATE");
                        return;
                end
        end

        -- clear MetaMap_SavedMap after two seconds
        if ( (MetaMap_SavedMapTime > 0) and (MetaMap_SavedMapTime < MetaMap_time) ) then
                MetaMap_SavedMapTime = 0;
                MetaMap_MapClick = false;
                MetaMap_SavedMap = {};
                MetaMap_OldMap = MetaMap_CurrentMap;
                MetaMap_NoOldMap = false;
        end

        if ( not MetaMap_MiniNote_MapzoomInit ) then return; end

        if (MetaMap_Timer_DelayLoadModules) then
                MetaMap_Timer_DelayLoadModules = MetaMap_Timer_DelayLoadModules - elapsed;
                if (MetaMap_Timer_DelayLoadModules < 0) then
                        MetaMap_Timer_DelayLoadModules = nil;
                        MetaMap_LoadModules();
                end
        end

        if (MetaMap_Timer_DelayWKB_AddUnitInfo) then
                MetaMap_Timer_DelayWKB_AddUnitInfo = MetaMap_Timer_DelayWKB_AddUnitInfo - elapsed;
                if (MetaMap_Timer_DelayWKB_AddUnitInfo < 0) then
                        MetaMap_Timer_DelayWKB_AddUnitInfo = nil;
                end
        end

        -- check for a zone change without event
        local realZone = GetRealZoneText();
        if (MetaMap_RealZoneTimer) then
                MetaMap_RealZoneTimer = MetaMap_RealZoneTimer - elapsed;
        end

        -- execute only every second
        MetaMap_WaitTimer = MetaMap_WaitTimer - elapsed;
        if ( MetaMap_WaitTimer < 0 ) then
                MetaMap_WaitTimer = 1;
        else
                return;
        end

        if (realZone and realZone ~= MetaMap_RealZoneText) then
                MetaMap_RealZoneTimer = 3;
                MetaMap_RealZoneText = realZone;
        elseif ( MetaMap_MiniNote_IsInCity ~= MetaMap_IsInside ) then
                MetaMap_RealZoneTimer = 3;
                MetaMap_IsInside = MetaMap_MiniNote_IsInCity;
        end
        if (MetaMap_RealZoneTimer and MetaMap_RealZoneTimer < 0) then
                MetaMap_RealZoneTimer = nil;
                if (realZone) then
--old                   local _, _, _, isMicroDungeon = GetMapInfo();
                        for _, zoneTable in pairs(MetaMap_ZoneTable) do
                                if (zoneTable[MetaMap_Locale] == realZone) then
--old                                   if ( (zoneTable.ztype == "SZR") and not isMicroDungeon ) then
                                        if ( zoneTable.ztype == "SZR" ) then
                                                realZone = MetaMap_SplitZoneName(zoneTable.Location);
                                        end
                                end
                        end
                        local baseName = MetaMap_SplitZoneName(MetaMap_BaseMap.Name);
--old                   if ( (baseName ~= realZone) or (MetaMap_IsMicroDungeon ~= isMicroDungeon) ) then
                        if ( baseName ~= realZone ) then
--old                           MetaMap_IsMicroDungeon = isMicroDungeon;
                                MetaMap_IsMicroDungeon = false;
                                MetaMap_OnEvent(self, "ZONE_CHANGED");
                                MetaMap_Debug_Print("*** Event ZONE_CHANGED triggered by MetaMap_OnUpdate ***",true);
                        end
                end
        end

        if (WorldMapFrame:IsVisible()) then
                if (MetaMapOptions.MetaMapCoords) then MetaMap_MainCoordsUpdate(); end
                if ( MetaMapOptions.MetaMapMiniCoords and MetaMap_MiniCoords:IsVisible() ) then
                        MetaMap_MiniCoords:Hide();
                end
        else
                if (MetaMapOptions.MetaMapMiniCoords) then
                        if ( not MetaMap_MiniCoords:IsVisible() ) then
                                MetaMap_MiniCoords:Show();
                        end
                        MetaMap_MiniCoordsUpdate();
                end
        end

        if (MetaMap_MiniNote_Data.xPos) then
                MetaMap_MiniNote_OnUpdate(elapsed);
        end

--      if (MetaMap_gPingPOI) then
--              MetaMapPing_OnUpdate(0);
--      end
end

function MetaMap_LoadZones()
        if(MetaMap_Notes == nil) then MetaMap_Notes = {}; end
        if(MetaMap_Lines == nil) then MetaMap_Lines = {}; end

        for index, zoneTable in pairs(MetaMap_ZoneTable) do
                if (zoneTable.ztype == "RDI" or zoneTable.ztype == "DNI" or zoneTable.ztype == "BG" or zoneTable.ztype == "SCN" or zoneTable.ztype == "MSZ") then
                        local name = MetaMap_MergeZoneName(zoneTable);
                        if (MetaMap_Notes[name] == nil) then
                                MetaMap_Notes[name] = {};
                        end
                        if (MetaMap_Lines[name] == nil) then
                                MetaMap_Lines[name] = {};
                        end
                end
        end

        
        
        MetaMap_Continents[-1] = "The Cosmos";
        MetaMap_Continents[0] = "Azeroth";
        for cKey, cName in pairs(MetaMap_GetMapContinents()) do
                MetaMap_Continents[cKey] = cName;
                for zKey, zName in pairs(MetaMap_GetMapZones(cKey)) do
                        local name = zName;
                        for _, zoneTable in pairs(MetaMap_ZoneTable) do
                                if (zoneTable[MetaMap_Locale] == zName and zoneTable.Continent == cKey) then
                                        if (not zoneTable.zoneid or zoneTable.zoneid == zKey) then
                                                name = MetaMap_MergeZoneName(zoneTable);
                                        end
                                end
                        end
                        if (MetaMap_Notes[name] == nil) then
                                MetaMap_Notes[name] = {};
                        end
                        if (MetaMap_Lines[name] == nil) then
                                MetaMap_Lines[name] = {};
                        end
                        MetaMap_ZoneTableUpdate(name);
                end
        end
end

-- print(GetMapZones(1)); SetMapZoom(1,4);
-- the mapList used by SetMapZoom(continent,mapListNr) is a combination of 
-- GetMapZones(continent) and GetMapSubzones(mapid), but with dungeons removed
--[[
function MetaMap_SetMapZoomByName(name)
        if (not name or name == "") then SetMapZoom(-1,0); return; end
        local cKey, zKey = MetaMap_NameToZoneID(name);
        if (zKey == 0) then SetMapZoom(cKey,0); return; end
        if (cKey == -1 and type(zKey) == "number") then SetMapByID(zKey); return; end
        if (cKey > 0) then
                local mapid = MetaMap_GetMapZoneID(cKey,name)
                if (mapid) then SetMapByID(mapid); return; end
        end
        local c = MetaMap_GetMapContinents();
        for i = 1, #c do
                local mapid = MetaMap_GetMapZoneID(i,name)
                if (mapid) then SetMapByID(mapid); return; end
        end
        SetMapZoom(-1,0);
end
--]]

-- check if the zoneName is included in MetaMap_ZoneTable else add it
function MetaMap_ZoneTableUpdate(zoneName)
        local index = 0;
        for idx, zoneTable in pairs(MetaMap_ZoneTable) do
                if ( index < idx ) then index = idx; end
                local name = MetaMap_MergeZoneName(zoneTable);
                if (zoneTable.ztype == "SZ" and name == zoneName) then
                        return;
                end
        end

        index = index + 1;
        MetaMap_ZoneTable[index] = {ztype = "SZ", en = zoneName, de = zoneName, fr = zoneName, es = zoneName, ru = zoneName, llvl = 0, hlvl = 0, faction = "Unknown", scale = 0, xoffset = 0, yoffset = 0};
end

-- checks if the zone "zoneName" is located in the map "mapName"
function MetaMap_CheckRelatedZone(zoneName, mapName)
        if (zoneName == mapName) then return true; end

        if (mapName == MetaMap_Continents[-1]) then related = true; end --"The Cosmos"

        local _, zIndex, zType = MetaMap_GetZoneTableEntry(zoneName);
        if (zType == "RDI" or zType == "DNI" or zType == "BG" or zType == "SZR" or zType == "MSZ" or zType == "SCN") then
                local locName = MetaMap_ZoneTable[zIndex].Location;
                if (locName == mapName) then return true; end
        end

        local continent = MetaMap_NameToZoneID(zoneName);
        if (zType == "RDI" or zType == "DNI" or zType == "BG" or zType == "SZR" or zType == "MSZ" or zType == "SCN") then
                continent = MetaMap_ZoneTable[zIndex].Continent;
        end
        if (not continent or continent == -1) then return false; end -- The Cosmos do not direct include any maps

        if (mapName == MetaMap_Continents[continent]) then related = true; end
        if (mapName == MetaMap_Continents[0] and continent > 0 and continent ~= 3 ) then related = true; end
        return false;
end

local UseBattlefieldMiniMapInCombat = true; --use Battlefield minimap during combat lockdown
local MetaMap_CombatLockdown_BattlefiedMap = nil;

function MetaMap_ToggleFrame(frame)
        if (frame == nil) then
                frame = WorldMapFrame;
        end

        MetaMap_Debug_Print("MetaMap: MetaMap_ToggleFrame("..tostring(frame)..")");
        if (UseBattlefieldMiniMapInCombat and InCombatLockdown() and frame == WorldMapFrame) then --combat lockdown
                if (not BattlefieldMinimap) then BattlefieldMinimap_LoadUI(); end
                if (BattlefieldMinimap and BattlefieldMinimap:IsVisible()) then
                        if (MetaMap_CombatLockdown_BattlefiedMap) then --wasn't on before combat
                                BattlefieldMinimap:Hide();
                                --MetaMap_Reshow_BattlefiedMap = true;
                        end
                        MetaMap_CombatLockdown_BattlefiedMap = nil;
                elseif (BattlefieldMinimap) then
                        MetaMap_CombatLockdown_BattlefiedMap = true;
                        BattlefieldMinimap:Show();
                end
        elseif (MetaMap_CombatLockdown_BattlefiedMap and frame == WorldMapFrame) then
                MetaMap_CombatLockdown_BattlefiedMap = nil;
                BattlefieldMinimap:Hide();
        end
        if (frame:IsVisible()) then
                HideUIPanel(frame);
        else
                ShowUIPanel(frame);
        end
end

function MetaMapContainer_ShowFrame(frame, header, footer, info)
        if (not frame) then
                if (MetaMapContainer_CurrentFrame) then
                        MetaMapContainer_CurrentFrame:Hide();
                end
                MetaMapContainerFrame:Hide();
                return;
        end
        if (MetaMapContainer_CurrentFrame) then
                MetaMapContainer_CurrentFrame:Hide();
        end
        if (header ~= nil) then
                MetaMapContainer_HeaderText:SetText(header);
                MetaMapContainer_HeaderText:Show();
        else
                MetaMapContainer_HeaderText:Hide();
        end
        if (footer ~= nil) then
                MetaMapContainer_FooterText:SetText(footer);
                MetaMapContainer_FooterText:Show();
        else
                MetaMapContainer_FooterText:Hide();
        end
        if (info ~= nil) then
                MetaMapContainer_InfoText:SetText(info);
                MetaMapContainer_InfoText:Show();
        else
                MetaMapContainer_InfoText:Hide();
        end
        MetaMapContainer_CurrentFrame = frame;
        MetaMapContainer_CurrentFrame:Show();
        if (MetaMap_FullScreenMode) then
                MetaMapContainerFrame:SetScale(1.0);
        else
                MetaMapContainerFrame:SetScale(WORLDMAP_WINDOWED_SIZE);
        end
        MetaMapContainerFrame:Show();
        frame:SetAlpha(MetaMapContainerFrame:GetAlpha());
end

function MetaMap_LoadModules()
        if (MetaMapOptions.NBKalwaysOn) then MetaMap_LoadNBK(1); end
        if (MetaMapOptions.WKBalwaysOn) then MetaMap_LoadWKB(3); end
        if (MetaMapOptions.BWPalwaysOn) then MetaMap_LoadBWP(0, 3); end
        if (MetaMapOptions.FWMalwaysOn) then MetaMap_LoadFWM(); end
        if (MetaMapOptions.QSTalwaysOn) then MetaMap_LoadQST(2); end
        if (MetaMapOptions.TRKalwaysOn) then MetaMap_LoadTRK(2); end
end

function MetaMap_LoadHLP()
        if (not IsAddOnLoaded("MetaMapHLP")) then
                LoadAddOn("MetaMapHLP");
        end
        if (IsAddOnLoaded("MetaMapHLP")) then
                MetaMap_LoadHLPButton:Hide();
                return true;
        else
                MetaMap_OptionsInfo:SetText("MetaMapHLP "..METAMAP_NOMODULE);
        end
end

function MetaMap_LoadCVT()
        if (not IsAddOnLoaded("MetaMapCVT")) then
                LoadAddOn("MetaMapCVT");
        end
        if (IsAddOnLoaded("MetaMapCVT")) then
                MetaMapCVT_CheckData();
        else
                MetaMap_OptionsInfo:SetText("MetaMapCVT "..METAMAP_NOMODULE);
        end
end

function MetaMap_LoadEXP()
        if (not IsAddOnLoaded("MetaMapEXP")) then
                LoadAddOn("MetaMapEXP");
        end
        if (IsAddOnLoaded("MetaMapEXP")) then
                EXP_CheckData();
        else
                MetaMap_OptionsInfo:SetText("MetaMapEXP "..METAMAP_NOMODULE);
        end
end

function MetaMap_LoadBKP()
        if (not IsAddOnLoaded("MetaMapBKP")) then
                LoadAddOn("MetaMapBKP");
        end
        if (IsAddOnLoaded("MetaMapBKP")) then
                BKP_BackUpFrame:Show();
        else
                if (MetaMap_LoadBKP) then MetaMap_LoadBKP:Disable(); end
                if (MetaMap_GeneralDialog:IsVisible()) then
                        MetaMap_OptionsInfo:SetText("MetaMapBKP "..METAMAP_NOMODULE);
                else
                        MetaMap_Print("MetaMapBKP "..METAMAP_NOMODULE, true);
                end
        end
end

        
function MetaMap_LoadBWP(id, mode)
        if (not IsAddOnLoaded("MetaMapBWP")) then
                LoadAddOn("MetaMapBWP");
        end
        if (IsAddOnLoaded("MetaMapBWP")) then
                if (mode == nil) then
                        MetaMapBWPMenu_Init();
                elseif (mode == 1) then
                        MetaMap_KBMenu_RBSelect(id);
                elseif (mode == 2) then
                        MetaMapNotes_RBSelect(id);
                end
        else
                MetaMap_Print("MetaMapBWP "..METAMAP_NOMODULE, true);
        end
end

function MetaMap_LoadWKB(mode)
        if (not IsAddOnLoaded("MetaMapWKB")) then
                LoadAddOn("MetaMapWKB");
        end
        if (IsAddOnLoaded("MetaMapWKB")) then
                if (mode == nil or mode == 1) then
                        WKB_ToggleFrame(mode);
                elseif (mode == 2) then
                        WKB_UpdateKeySelectedUnit();
                end
        else
                MetaMap_Print("MetaMapWKB "..METAMAP_NOMODULE, true);
        end
end

function MetaMap_LoadQST(mode)
        if (not IsAddOnLoaded("MetaMapQST")) then
                LoadAddOn("MetaMapQST");
        end
        if (IsAddOnLoaded("MetaMapQST")) then
                QST_ToggleFrame(mode);
        else
                MetaMap_Print("MetaMapQST "..METAMAP_NOMODULE, true);
        end
end

function MetaMap_LoadNBK(mode)
        if (not IsAddOnLoaded("MetaMapNBK")) then
                LoadAddOn("MetaMapNBK");
        end
        if (IsAddOnLoaded("MetaMapNBK")) then
                if (not mode) then
                        MetaMap_ToggleFrame(NBK_NoteBookFrame);
                end
                return true;
        else
                MetaMap_Print("MetaMapNBK "..METAMAP_NOMODULE, true);
                return false;
        end
end

function MetaMap_LoadTRK(mode)
        if (not IsAddOnLoaded("MetaMapTRK")) then
                LoadAddOn("MetaMapTRK");
        end
        if (IsAddOnLoaded("MetaMapTRK")) then
                TRK_ToggleFrame(mode);
                MetaMap_Tracker = true;
                return true;
        else
                MetaMap_Print("MetaMapTRK "..METAMAP_NOMODULE, true);
                MetaMap_Tracker = false;
                return false;
        end
end

function MetaMap_LoadFWM(mode)
        if (not IsAddOnLoaded("MetaMapFWM")) then
                LoadAddOn("MetaMapFWM");
        end
        if (IsAddOnLoaded("MetaMapFWM")) then
                if (mode == nil) then
                        FWM_ShowUnexplored = not FWM_ShowUnexplored;
                else
                        FWM_ShowUnexplored = true;
                end 
                WorldMapFrame_Update();
        else
                if (MetaMap_ModulesDialog:IsVisible()) then
                        MetaMap_OptionsInfo:SetText("MetaMapFWM "..METAMAP_NOMODULE);
                else
                        MetaMap_Print("MetaMapFWM "..METAMAP_NOMODULE, true);
                end
        end
end

--- Init the tracker activation
function MetaMap_SetTracker()
        MetaMap_LoadTRK(2);
end

function MetaMap_CommandsInit()
        SlashCmdList["MAPNOTE"] = MetaMap_GetNoteBySlashCommand;
        for i = 1, #(METAMAP_ENABLE_COMMANDS) do
                setglobal("SLASH_MAPNOTE"..i, METAMAP_ENABLE_COMMANDS[i]);
        end
        SlashCmdList["MININOTE"] = MetaMap_NextMiniNote;
        for i = 1, #(METAMAP_MININOTE_COMMANDS) do
                setglobal("SLASH_MININOTE"..i, METAMAP_MININOTE_COMMANDS[i]);
        end
        SlashCmdList["MININOTEONLY"] = MetaMap_NextMiniNoteOnly;
        for i = 1, #(METAMAP_MININOTEONLY_COMMANDS) do
                setglobal("SLASH_MININOTEONLY"..i, METAMAP_MININOTEONLY_COMMANDS[i]);
        end
        SlashCmdList["MININOTEOFF"] = MetaMap_ClearMiniNote;
        for i = 1, #(METAMAP_MININOTEOFF_COMMANDS) do
                setglobal("SLASH_MININOTEOFF"..i, METAMAP_MININOTEOFF_COMMANDS[i]);
        end
        SlashCmdList["QUICKNOTE"] = MetaMap_Quicknote;
        for i = 1, #(METAMAP_QUICKNOTE_COMMANDS) do
                setglobal("SLASH_QUICKNOTE"..i, METAMAP_QUICKNOTE_COMMANDS[i]);
        end
end

function MetaMap_FullScreenToggle(self)
        MetaMap_Debug_Print("FullScreenToggle:", true);
        if ( InCombatLockdown() ) then return; end

        local mapid = WorldMapFrame:GetMapID();
        if ( not mapid ) then return; end
--old   local level = GetCurrentMapDungeonLevel();

--old   MetaMap_FullScreenMode = ( not WorldMapFrame_InWindowedMode() );
        MetaMap_FullScreenMode = WorldMapFrame.isMaximized;
        if (not MetaMap_FullScreenMode) then
                WorldMapFrame:SetScript("OnKeyDown", nil);
                MetaMapOptions_Init();
                MetaMapList_Init();
                if (MetaMapOptions.MetaMapCoords) then MetaMap_MainCoords:Show(); end
        else
                WorldMapFrame:SetScale(1.0);
                WorldMapFrame:SetScript("OnKeyDown", MetaMap_WorldMapFrame_OnKeyDown_old);
                MetaMap_MainCoords:Hide();
        end
--old   WorldMapFrameTutorialButton:Hide();

--old   local _, _, _, isMicroDungeon = GetMapInfo();
--old   if ( not isMicroDungeon ) then SetMapByID(mapid); end
        WorldMapFrame:SetMapID(mapid);
-- ??? MetaMapShown is undefined ???
--old   if (MetaMapShown) then MetaMap_ShowInstance(self, true); end
--old   if ( (level ~= 0) and not isMicroDungeon ) then SetDungeonMapLevel(level); end
end

function MetaMap_ShowInstance(self, show, basemap)
        MetaMap_Debug_Print("MetaMap_ShowInstance", true);
        local _, _, zType = MetaMap_GetZoneTableEntry(MetaMapOptions.MetaMapZone);

        MetaMapOptions.ShowDNI = show;

--old   local _, _, _, isMicroDungeon = GetMapInfo();
        if (basemap or not WorldMapFrame:IsVisible()) then
                if (show and (zType == "RDI" or zType == "DNI" or zType == "BG" or zType == "SCN")) then
--#?                    UIDropDownMenu_SetText(MetaMap_InstanceMenu, MetaMapOptions.MetaMapZone);
                else
--#?                    UIDropDownMenu_ClearAll(MetaMap_InstanceMenu);
--old                   if ( isMicroDungeon ) then
--old                           MetaMapOptions.MetaMapLevel = GetCurrentMapDungeonLevel();
--old                   else
                                MetaMapOptions.MetaMapZone = nil;
                                MetaMapOptions.MetaMapLevel = 0;
--old                   end
                        MetaMapOptions.oldScrollH = 0;
                        MetaMapOptions.oldScrollV = 0;
                        MetaMapOptions.oldScale = WorldFrame:GetScale();
                end
                return;
        end

        if (show and (zType == "DNI" or zType == "BG" or zType == "SCN" or zType == "RDI")) then
                -- set the map only if different to the shown map to prevent endless loop
                local map_isSet = false;
                local _, instance = MetaMap_NameToZoneID(MetaMapOptions.MetaMapZone);
                local location = WorldMapFrame:GetMapID();
                if (instance ~= location) then
                        -- to set the mapid to 611 does not work, but its the same map as 685
                        if (instance == 611) then
                                SetMapByID(685);
                        else
                                SetMapByID(instance);
                        end
                        map_isSet = true;
                end
                local level = MetaMapOptions.MetaMapLevel;
                location = MetaMap_GetCurrentMapDungeonLevel();
                if (level ~= 0 and level ~= location) then
                        SetDungeonMapLevel(MetaMapOptions.MetaMapLevel);
                        map_isSet = true;
                end
                if ( map_isSet and WorldMapFrame:IsVisible() and MetaMap_StayOnMap ) then
                        WorldMapDetailFrame:SetScale(MetaMapOptions.oldScale);
                        WorldMapScrollFrame:SetHorizontalScroll(MetaMapOptions.oldScrollH);
                        WorldMapScrollFrame:SetVerticalScroll(MetaMapOptions.oldScrollV);
                end
--#?            UIDropDownMenu_SetText(MetaMap_InstanceMenu, MetaMapOptions.MetaMapZone);
        else
                if (not show) then
--#?                    UIDropDownMenu_ClearAll(MetaMap_InstanceMenu);
--old                   if ( isMicroDungeon ) then
--old                           MetaMapOptions.MetaMapLevel = GetCurrentMapDungeonLevel();
--old                   else
                                MetaMapOptions.MetaMapZone = nil;
                                MetaMapOptions.MetaMapLevel = 0;
--old                   end
                        MetaMapOptions.oldScrollH = 0;
                        MetaMapOptions.oldScrollV = 0;
                        MetaMapOptions.oldScale = WorldFrame:GetScale();
                end
                if (WorldMapFrame:IsVisible()) then
                        if (IsAddOnLoaded("MetaMapWKB") and WKB_DisplayFrame:IsVisible()) then
                                WKB_OnEvent("INSTANCE_MAP_UPDATE");
                        elseif (IsAddOnLoaded("MetaMapQST") and QST_DisplayFrame:IsVisible()) then
                                QST_OnEvent("INSTANCE_MAP_UPDATE");
                        elseif (IsAddOnLoaded("MetaMapTRK") and TRK_DisplayFrame:IsVisible()) then
                                TRK_OnEvent("INSTANCE_MAP_UPDATE");
                        else
                                MetaMapContainer_ShowFrame();
                        end
                        if (MetaMap_InfoLineFrame:IsVisible()) then MetaMap_InfoLineUpdate(); end

                        MetaMap_MainMapUpdate();
                        MetaMap_ZoneSearch();
                        MetaMap_HideAll();
                        if (MetaMap_gPingPOI) then
                                MetaMapPing_OnUpdate(1);
                        end
                end
        end
end

function MetaMap_MiniCoordsUpdate()
        if (WorldMapFrame:IsVisible()) then return; end

--old   local px, py = GetPlayerMapPosition("player");
        local px, py = C_Map.GetBestMapForUnit("player");
        if (px == 0 and py == 0) then
                local _, _, zType = MetaMap_GetZoneTableEntry(MetaMap_GetRealZoneText());
                if (zType == "DN") then
                        MetaMapMiniCoords:SetText(METAMAP_INSTANCE);
                else
                        MetaMapMiniCoords:SetText("Dead Zone");
                end
        else
                if px==nil then px=0; end
                if py==nil then py=0; end
                MetaMapMiniCoords:SetText(format("%4.1f, %4.1f", px * 100, py * 100));
        end
end

-- Sets coords at the bottom of the map
function MetaMap_MainCoordsUpdate()
        local OFFSET_X = 0;
        local OFFSET_Y = 0;
        local centerX, centerY = WorldMapFrame.ScrollContainer:GetCenter()
        local width = WorldMapFrame.ScrollContainer:GetWidth()
        local height = WorldMapFrame.ScrollContainer:GetHeight()
        local x, y = GetCursorPosition()
        x = x / WorldMapFrame.ScrollContainer:GetEffectiveScale()
        y = y / WorldMapFrame.ScrollContainer:GetEffectiveScale()

        if (centerX == nil) then
                centerX = 0;
        end
        if (centerY == nil) then
                centerY = 0;
        end

        local adjustedX, adjustedY;
        if ( width ~= 0 ) then adjustedX = (x - (centerX - width/2)) / width; else adjustedX = 0; end
        if (height ~= 0 ) then adjustedY = (centerY + height/2 - y) / height; else adjustedY = 0; end
        x = 100 * (adjustedX + OFFSET_X);
        y = 100 * (adjustedY + OFFSET_Y);

        --MetaMap_Debug_Print("MainCoordsUpdate"..format("%d, %d", x, y),true);

        if (x < 0 or y < 0 or x > 100 or y > 100) then
                MetaMapCoordsCursor:SetText("");
        else
                MetaMapCoordsCursor:SetText("|cffffffff"..format("%4.1f, %4.1f", x, y));
        end

        local px, py = C_Map.GetBestMapForUnit("player");
        if(px==nil) then px=0; end
        if(py==nil) then py=0; end
        if (px == 0 and py == 0) then
                local _, _, zType = MetaMap_GetZoneTableEntry(MetaMap_GetRealZoneText());
                local continent, zone = MetaMap_NameToZoneID(MetaMap_GetRealZoneText());
                if (zType == "DN") then
                        MetaMapCoordsPlayer:SetText(METAMAP_INSTANCE_1);
--old           elseif (GetCurrentMapContinent() ~= continent or GetCurrentMapZone() ~= zone) then
                elseif (GetCurrentMapContinent() ~= continent or zone ~= 1) then
                        MetaMapCoordsPlayer:SetText("");
                else
                        MetaMapCoordsPlayer:SetText("|cff00ff00Dead Zone");
                end
        else
                if(px == nil) then
                  px=-1;
                end
                if(py == nil) then
                        py=-1;
                end
                
                MetaMapCoordsPlayer:SetText("|cff00ff00"..format("%4.1f, %4.1f", px * 100, py * 100));
        end
end

function MetaMap_InstanceMenu_Initialize(self)
        MetaMap_Debug_Print("MetaMap_InstanceMenu_Initialize:"..UIDROPDOWNMENU_MENU_LEVEL,true);

        if (UIDROPDOWNMENU_MENU_LEVEL == 1) then
                MetaMap_InstanceMenu_level1(700, METAMAP_INSTANCE_MENU_DUNGEONS);
                MetaMap_InstanceMenu_level1(600, METAMAP_INSTANCE_MENU_RAIDS);
                MetaMap_InstanceMenu_level1(800, METAMAP_INSTANCE_MENU_SCENARIOS);
                MetaMap_InstanceMenu_level1(999, METAMAP_BATTLEGROUNDS);

        elseif (UIDROPDOWNMENU_MENU_LEVEL == 2) then
                local menuVal = MetaMap_SubMenuFix(self);
                if (menuVal ~= nil) then
                        MetaMap_Debug_Print("MetaMap_SubMenuFix:"..UIDROPDOWNMENU_MENU_LEVEL.."="..menuVal,true);
                else
                        MetaMap_Debug_Print("MetaMap_SubMenuFix menuVal was nil", true);
                end

                if ( menuVal == 600 or menuVal == 700 or menuVal == 800 or menuVal == 999 ) then
                        MetaMap_InstanceMenu_level2(menuVal);
                end

        elseif (UIDROPDOWNMENU_MENU_LEVEL == 3) then
                local menuVal = MetaMap_SubMenuFix(self);
                if (menuVal ~= nil) then
                        MetaMap_Debug_Print("MetaMap_SubMenuFix:"..UIDROPDOWNMENU_MENU_LEVEL.."="..menuVal,true);
                else
                        MetaMap_Debug_Print("MetaMap_SubMenuFix menuVal was nil", true);
                end

                if (menuVal >= 800 and menuVal <= 810) then
                        MetaMap_InstanceMenu_level3("SCN", 800, menuVal);
                elseif (menuVal >= 700 and menuVal <= 710) then
                        MetaMap_InstanceMenu_level3("DNI", 700, menuVal);
                elseif (menuVal >= 600 and menuVal <= 610) then
                        MetaMap_InstanceMenu_level3("RDI", 600, menuVal);
                end 
        end
end

function MetaMap_InstanceMenu_level1(menuVal, text)
        local info = {};
        info.text = text;
        info.textHeight = MetaMapOptions.MenuFont;
        info.hasArrow = 1;
        info.notCheckable = 1;
        info.value = menuVal;
        info.notClickable = false;
        UIDropDownMenu_AddButton(info);
end

function MetaMap_InstanceMenu_level2(menuVal)
        if (menuVal == 999) then
                MetaMap_InstanceMenu_level3("BG", 900, menuVal);
                return;
        end 

        for index, cName in pairs(MetaMap_Continents) do
                if (index > 0) then
                        local info = {};
                        info.text = cName;
                        info.textHeight = MetaMapOptions.MenuFont;
                        info.hasArrow = 1;
                        info.notCheckable = 1;
                        info.value = menuVal + index;
                        info.disabled = false;
                        info.notClickable = false;
                        info.isTitle = false;
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                end
        end
end

function MetaMap_InstanceMenu_level3(ztype, basemenuval, menuVal)
        local menuList = {};
        for index, zoneTable in pairs(MetaMap_ZoneTable) do
                if ( zoneTable.ztype == ztype ) then
                        if ( (zoneTable.Continent == (menuVal - basemenuval)) or (menuVal == 999) ) then
                                local name = MetaMap_MergeZoneName(zoneTable);
                                table.insert(menuList, {location = name});
                        end
                end
        end

        local sort = MetaMap_sortType;
        MetaMap_sortType = METAMAP_SORTBY_LOCATION;
        table.sort(menuList, MetaMap_SortCriteria);
        MetaMap_sortType = sort;
        for zKey, zName in pairs(menuList) do
                local info = {};
                info.text = zName.location;
                info.textHeight = MetaMapOptions.MenuFont;
                info.checked = nil;
                info.notCheckable = 1;
                info.value = zName.location;
                info.func = MetaMap_InstanceMenu_OnClick;
                info.disabled = false;
                info.notClickable = false;
                info.isTitle = false;
                UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
        end
end

function MetaMap_InstanceMenu_OnClick(self)
        if ( not MetaMapOptions.MapChange ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
        end
        MetaMapOptions.MetaMapZone = self.value;
        MetaMapOptions.MetaMapLevel = 0;
        MetaMapOptions.oldScrollH = 0;
        MetaMapOptions.oldScrollV = 0;
        MetaMapOptions.oldScale = WorldFrame:GetScale();
        MetaMap_ShowInstance(self, true);

        MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();
end

function MetaMap_MainMenuSelect(parent, level)
        local x, y = 0, 0;
        if (parent) then
                if ( parent == "MetaMap_OptionsButton" and MetaMap_StayOnMap ) then
                        if ( MataMapMainMenu_Visible ) then
                                MataMapMainMenu_Visible = false;
                        else
                                MataMapMainMenu_Visible = true;
                        end
                end
                MetaMap_MenuParent = parent;
                if (parent == "FuBarPluginMetaMapFrame") then y = -10; end
        else
                MetaMap_MenuParent = "cursor";
        end
        -- ### problematic with taintLog ###
        ToggleDropDownMenu(nil, nil, MetaMap_MainMenu, MetaMap_MenuParent, x, y);
end

function MetaMap_MainMenu_Initialize(self)
        if (UIDROPDOWNMENU_MENU_LEVEL == 2) then
                local _, menuText = MetaMap_SubMenuFix(self);

                if (menuText == METAMAP_MENU_FILTER) then
                        local menuFrame = _G["DropDownList"..2];
                        local menuName = menuFrame:GetName();
                        local cText;
                        for i = 0, 9, 1 do
                                if (MetaMap_NoteFilter[i]) then
                                        cText = METAMAP_MAP_ICON_ON;
                                else
                                        cText = METAMAP_MAP_ICON_OFF;
                                end
                                local info = {
                                        checked = nil,
                                        notCheckable = 1,
                                        keepShownOnClick = 1,
                                        text = cText,
                                        textHeight = MetaMapOptions.MenuFont,
                                        icon = METAMAP_ICON_PATH.."Icon"..i,
                                        value = {mode = 2, func = "MetaMap_FilterNotes", cText = cText, args = i},
                                        func = MetaMap_MainMenu_OnClick;
                                };
                                UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                        end
                        local info = {
                                checked = nil,
                                notCheckable = 1,
                                keepShownOnClick = 1,
                                text = METAMAP_MENU_FILTER1,
                                textHeight = MetaMapOptions.MenuFont,
                                value = {mode = 2, func = "MetaMap_FilterNotes", args = 11},
                                func = MetaMap_MainMenu_OnClick;
                        };
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                        local info = {
                                checked = nil,
                                notCheckable = 1,
                                keepShownOnClick = 1,
                                text = METAMAP_MENU_FILTER2,
                                textHeight = MetaMapOptions.MenuFont,
                                value = {mode = 2, func = "MetaMap_FilterNotes", args = 12},
                                func = MetaMap_MainMenu_OnClick;
                        };
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                elseif (menuText == METAMAP_MENU_TRKFILTER) then
                        local cText = METAMAP_MENU_OFF.."   ";
                        if (TRK_Options.FilterHerb) then cText = METAMAP_MENU_ON.."   "; end
                        local info = {
                                checked = nil,
                                notCheckable = 1,
                                keepShownOnClick = 1,
                                text = cText..TRK_FILTER_HERB,
                                textHeight = MetaMapOptions.MenuFont,
                                value = "FilterHerb",
                                func = TRK_MetaMapMenuOnClick;
                        };
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                        cText = METAMAP_MENU_OFF.."   ";
                        if (TRK_Options.FilterOre) then cText = METAMAP_MENU_ON.."   "; end
                        local info = {
                                checked = nil,
                                notCheckable = 1,
                                keepShownOnClick = 1,
                                text = cText..TRK_FILTER_ORE,
                                textHeight = MetaMapOptions.MenuFont,
                                value = "FilterOre",
                                func = TRK_MetaMapMenuOnClick;
                        };
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                        cText = METAMAP_MENU_OFF.."   ";
                        if (TRK_Options.FilterTreasure) then cText = METAMAP_MENU_ON.."   "; end
                        local info = {
                                checked = nil,
                                notCheckable = 1,
                                keepShownOnClick = 1,
                                text = cText..TRK_FILTER_TREASURE,
                                textHeight = MetaMapOptions.MenuFont,
                                value = "FilterTreasure",
                                func = TRK_MetaMapMenuOnClick;
                        };
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                        cText = METAMAP_MENU_OFF.."   ";
                        if (TRK_Options.FilterMisc) then cText = METAMAP_MENU_ON.."   "; end
                        local info = {
                                checked = nil,
                                notCheckable = 1,
                                keepShownOnClick = 1,
                                text = cText..TRK_FILTER_MISC,
                                textHeight = MetaMapOptions.MenuFont,
                                value = "FilterMisc",
                                func = TRK_MetaMapMenuOnClick;
                        };
                        UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                end
        else
                local info = {
                        notCheckable = 1,
                        isTitle = 1,
                        text = METAMAP_NAME.."\n\n",
                        textHeight = MetaMapOptions.MenuFont + 1;
                }
                UIDropDownMenu_AddButton(info);
                for index, value in ipairs(MetaMap_MainMenuData) do
                        local toggle = "";
                        local showitem = true;
                        local cText = value.text;
                        if (cText == METAMAP_MENU_TRKFILTER and not IsAddOnLoaded("MetaMapTRK")) then showitem = false; end
                        if (cText == METAMAP_MENU_FLIGHT and not IsAddOnLoaded("FlightMap")) then showitem = false; end
                        if (cText == METAMAP_MENU_ACTION and MetaMap_CurrentAction) then
                                cText = METAMAP_MENU_ON.."    "..value.text;
                        elseif (cText == METAMAP_MENU_ACTION and not MetaMap_CurrentAction) then
                                cText = METAMAP_MENU_OFF.."    "..value.text;
                        elseif (cText == METAMAP_MENU_FWMMOD and FWM_ShowUnexplored) then
                                cText = METAMAP_MENU_ON.."    "..value.text;
                        elseif (cText == METAMAP_MENU_FWMMOD and not FWM_ShowUnexplored) then
                                cText = METAMAP_MENU_OFF.."    "..value.text;
                        elseif (cText == METAMAP_MENU_TRKSET) then
                                if ( MetaMap_Tracker ) then
                                        cText = METAMAP_MENU_ON.."    "..value.text;
                                else
                                        cText = METAMAP_MENU_OFF.."    "..value.text;
                                end
                        elseif (cText == METAMAP_MENU_MAPSET) then
                                cText = "|cff00FFFF  "..MetaMap_CurrentSaveSet.."|r     "..value.text;
                        elseif (value.mode == 1 and MetaMapOptions[value.opt]) then
                                cText = METAMAP_MENU_ON.."    "..value.text;
                        elseif (value.mode == 1 and not MetaMapOptions[value.opt]) then
                                cText = METAMAP_MENU_OFF.."   "..value.text;
                        end
                        if (showitem) then
                                local info = {
                                        keepShownOnClick = value.ksoc,
                                        checked = nil,
                                        notCheckable = 1,
                                        hasArrow = value.ha,
                                        notClickable = value.nc,
                                        text = cText,
                                        textHeight = MetaMapOptions.MenuFont,
                                        value = {mode = value.mode, func = value.opt, args = ""},
                                        func = MetaMap_MainMenu_OnClick;
                                }
                                UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL);
                        end
                end
        end
end

function MetaMap_MainMenu_OnClick(self)
        if (not self.value.mode) then return; end
        if ( MetaMap_StayOnMap and not self.keepShownOnClick ) then
                MataMapMainMenu_Visible = false;
        end
        local button;
        if (self.value.mode == 1) then
                MetaMap_ToggleOptions(self.value.func);
                MetaMapList_Init();
        else
                RunScript(self.value.func.."("..self.value.args..")");
        end
        local txt = self:GetText();
        if (string.find(txt, METAMAP_MENU_ON)) then
                txt = string.gsub(txt, METAMAP_MENU_ON, METAMAP_MENU_OFF);
        elseif (string.find(txt, METAMAP_MENU_OFF)) then
                txt = string.gsub(txt, METAMAP_MENU_OFF, METAMAP_MENU_ON);
        elseif (string.find(txt, "1")) then
                txt = string.gsub(txt, "1", "2");
                button = _G[self:GetParent():GetName().."Button"..self:GetID() - 1];
        elseif (string.find(txt, "2")) then
                txt = string.gsub(txt, "2", "1");
                button = _G[self:GetParent():GetName().."Button"..self:GetID() - 1];
        end
        if (button and MetaMap_CurrentAction) then
                button:SetText(METAMAP_MENU_ON.."    "..METAMAP_MENU_ACTION);
        elseif (button and not MetaMap_CurrentAction) then
                button:SetText(METAMAP_MENU_OFF.."    "..METAMAP_MENU_ACTION);
        end
        self:SetText(txt);
        self.checked = not self.checked;
end

function MetaMap_FilterNotes(args)
        if (args == 11) then
                for i = 0, 9, 1 do
                        local index = i +1;
                        local button = _G["DropDownList2Button"..index];
                        button:SetText(string.gsub(button:GetText(), METAMAP_MENU_OFF, METAMAP_MENU_ON));
                        MetaMap_NoteFilter[i] = true;
                end
        elseif (args == 12) then
                for i = 0, 9, 1 do
                        local index = i +1;
                        local button = _G["DropDownList2Button"..index];
                        button:SetText(string.gsub(button:GetText(), METAMAP_MENU_ON, METAMAP_MENU_OFF));
                        MetaMap_NoteFilter[i] = false;
                end
        else
                MetaMap_NoteFilter[args] = not MetaMap_NoteFilter[args];
        end
        MetaMap_MainMapUpdate();
end

function MetaMapExtOptions_Toggle()
        if (MetaMap_DialogFrame:IsVisible()) then
                HideUIPanel(MetaMap_DialogFrame);
        else
                if (MetaMap_FullScreenMode) then
                        MetaMap_DialogFrame:SetParent(WorldMapFrame);
                else
                        MetaMap_DialogFrame:SetParent(UIParent);
                        MetaMap_DialogFrame:SetFrameStrata("FULLSCREEN");
                end
                ShowUIPanel(MetaMap_DialogFrame);
        end
end

function MetaMapSaveSet_Toggle()
        if (MetaMapOptions.SaveSet == 1) then
                MetaMapOptions.SaveSet = 2;
        else
                MetaMapOptions.SaveSet = 1;
        end

        MetaMap_ModeToggleButton:SetText(MetaMapOptions.SaveSet);

        MetaMapOptions_Init();
        MetaMapList_Init();
end

function MetaMap_MapModeToggle(mode)
        MetaMapOptions.SaveSet = mode;
        MetaMap_ToggleFrame(WorldMapFrame);
end

function MetaMap_ActionToggle()
        MetaMap_ToggleOptions("ActionMode"..MetaMapOptions.SaveSet);
        MetaMapList_Init();
end

function MetaMap_ButtonTooltip()
        GameTooltip_SetDefaultAnchor(GameTooltip, UIParent);
        GameTooltip:SetText(METAMAP_TITLE, 0, 1, 0);
        GameTooltip:AddLine(METAMAP_BUTTON_TOOLTIP1, 1, 1, 1);
        if (MetaMapOptions.MenuMode) then
                GameTooltip:AddLine(METAMAP_BUTTON_TOOLTIP2, 1, 1, 1);
        end
        GameTooltip:Show();
end

function MetaMap_MiniMapCoords_OnClick(button)
        if (IsShiftKeyDown()) then
                if (not ChatEdit_GetActiveWindow()) then ChatFrame_OpenChat(""); end
                local ChatFrameEditBox = ChatEdit_GetActiveWindow();
                if (not ChatFrameEditBox:IsVisible()) then ChatFrameEditBox:Show(); end
                local msg = METAMAP_MYLOCATION..MetaMap_GetRealZoneText().." ("..MetaMapMiniCoords:GetText()..")";
                ChatFrameEditBox:Insert(msg);
        elseif (IsControlKeyDown()) then
                if (MetaMapOptions.MiniColor == 9) then
                        MetaMapOptions.MiniColor = 0;
                else
                        MetaMapOptions.MiniColor = MetaMapOptions.MiniColor + 1;
                end
                local color = MetaMap_Colors[MetaMapOptions.MiniColor];
                MetaMapMiniCoords:SetTextColor(color.r, color.g, color.b);
        end
end

function MetaMap_MiniMapCoords_OnEnter(self)
        MetaMap_SetTTInfoLine(MetaMap_GetRealZoneText(), self, GameTooltip);
        GameTooltip:AddLine(METAMAP_INFOLINE_HINT5, 0.75, 0, 0.75, false);
        GameTooltip:AddLine(METAMAP_INFOLINE_HINT6, 0.75, 0, 0.75, false);
        GameTooltip:Show();
end

function MetaMap_ShowLocation(self, zoneName, zoneLevel, noteName, noteID)
        if (not zoneName) then return; end

        local _, _, zType = MetaMap_GetZoneTableEntry(zoneName);
        if ( zType == "MSZ" ) then return; end
        MetaMapContainer_ShowFrame();
        ShowUIPanel(WorldMapFrame);

        MetaMapOptions.MetaMapZone = zoneName;
        if (zoneLevel and type(zoneLevel) == "number") then
                MetaMapOptions.MetaMapLevel = zoneLevel;
        else
                MetaMapOptions.MetaMapLevel = 0;
        end
        MetaMapOptions.oldScrollH = 0;
        MetaMapOptions.oldScrollV = 0;
        MetaMapOptions.oldScale = WorldFrame:GetScale();
        if (zType == "RDI" or zType == "DNI" or zType == "BG" or zType == "SCN") then
                MetaMap_ShowInstance(self, true);
        else
                MetaMap_ShowInstance(self, false);
--              SetMapZoom(MetaMap_NameToZoneID(zoneName));
--old           MetaMap_SetMapZoomByName(zoneName);
                WorldMapFrame:SetMapID(MetaMap_NameToZoneID(zoneName));
        end

        MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();

        if (not noteName) then return; end

        local dataZone = MetaMap_Notes[zoneName];
        if (not noteID) then
                for index, value in ipairs(dataZone) do
                        if (dataZone[index].name == noteName) then
                                noteID = index;
                                break;
                        end
                end
        end
        if (noteID) then
                MetaMapPing_SetPing(dataZone, noteID);
        end
end

function MetaMapList_Init()
        if (not MetaMapOptions.ShowMapList) then
                MetaMap_MapListFrame:Hide();
                return;
        end

        if (MetaMapOptions.SortList) then
                MetaMapList_Header:SetText(METAMAPLIST_UNSORTED);
        else
                MetaMapList_Header:SetText(METAMAPLIST_SORTED);
        end
        if (MetaMap_FullScreenMode) then
                MetaMap_MapListFrame:SetScale(1.0);
        else
                MetaMap_MapListFrame:SetScale(WORLDMAP_WINDOWED_SIZE);
        end
        MetaMap_MapListFrame:Show();
        FauxScrollFrame_SetOffset(MetaMapList_ScrollFrame, MetaMap_ListOffset);
        MetaMapList_BuildList();
        if (not MetaMap_NoteList[1]) then
                MetaMap_MapListFrame:Hide();
                return;
        end
        MetaMapList_UpdateScroll();
end

-- This gets called from WorldMapFrame.lua when user left clicks on the map.
--old local MetaMap_ProcessMapClick_old = ProcessMapClick;
--old function ProcessMapClick(...)
function MetaMap_ProcessMapClick(self, button)
        MetaMap_Debug_Print("MetaMap_ProcessMapClick", true);

        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();

        if (not MetaMap_FramesHidden()) then return; end

        if (BattlefieldMinimap and BattlefieldMinimap:IsVisible() ) then
                if (not MetaMap_CombatLockdown_BattlefiedMap) then
                        MetaMap_Reshow_BattlefiedMap = time();
                end
                MetaMap_CombatLockdown_BattlefiedMap = nil;
                BattlefieldMinimap:Hide(); --BattlefieldMinimap screws up the map selection
        end

        if (mapName and MetaMap_Relocate.id) then
                if (not IsControlKeyDown() and not IsShiftKeyDown()) then
                        MetaMap_MoveNote(MetaMap_Relocate.mapName, MetaMap_Relocate.id);
                        MetaMap_Relocate = {};
                        return;
                end
        end

        if (mapName) then 
                local _, _, ztype = MetaMap_GetZoneTableEntry(mapName);
                if (not ztype == "SZ") then
                        MetaMap_Debug_Print("mapName: " .. tostring(mapName) , true);
                        MetaMap_Debug_Print("dataZone: " .. tostring(dataZone) , true);
                        MetaMap_Debug_Print("realZoneText: " .. tostring(MetaMap_GetRealZoneText()) , true);
                        MetaMap_Debug_Print("MetaMapOptions.MetaMapZone:"..tostring(MetaMapOptions.MetaMapZone), true);
                end
        else
                MetaMap_Debug_Print("realZoneText: " .. tostring(MetaMap_GetRealZoneText()) , true);
        end

        if ( (IsControlKeyDown() or IsShiftKeyDown() or IsAltKeyDown()) and mapName and dataZone ) then
                if (mapName or MetaMapOptions.ShowDNI) then
                        local centerX, centerY = WorldMapFrame.ScrollContainer:GetCenter();
                        local width = WorldMapFrame.ScrollContainer:GetWidth();
                        local height = WorldMapFrame.ScrollContainer:GetHeight();
                        local x, y = GetCursorPosition();
                        x = x / WorldMapFrame.ScrollContainer:GetEffectiveScale();
                        y = y / WorldMapFrame.ScrollContainer:GetEffectiveScale();

                        if (centerX == nil) then
                                centerX = 0;
                        end
                        if (centerY == nil) then
                                centerY = 0;
                        end

                        local adjustedY = (centerY + height/2 - y) / height;
                        local adjustedX = (x - (centerX - width/2)) / width;

                        if (IsShiftKeyDown()) then
                                MetaMap_SetPartyNote(adjustedX, adjustedY);
                        elseif (IsControlKeyDown()) then
                                local _, _, dataZone = MetaMap_GetCurrentMapInfo();
                                if (dataZone) then MetaMap_EditNewNote(adjustedX, adjustedY); end
                        elseif (IsAltKeyDown() and MetaMap_GetCurrentMapInfo() == MetaMap_GetRealZoneText()) then
                                MetaMap_LoadBWP(0, 3);
                                if (IsAddOnLoaded("MetaMapBWP")) then
                                        BWP_LocCommand(format("%d, %d", 100 * adjustedX, 100 * adjustedY));
                                end
                        end
                end
        else
                MetaMap_Debug_Print("--------click mark-------",true);
--old           MetaMap_ProcessMapClick_old(...);

                if ( not MetaMapOptions.MapChange ) then
                        MetaMap_StayOnMap = true;
                        MetaMap_MapClick = true;
                end
                if ( not next(MetaMap_SavedMap) ) then MetaMap_OnEvent(self, "WORLD_MAP_UPDATE"); end

                MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();

                -- set drop down menu text of instance menu to current map
                mapName = MetaMap_GetCurrentMapInfo();
                if (mapName) then
                        local cKey, zKey = MetaMap_NameToZoneID(mapName);
                        if ( (cKey == -1) and (type(zKey) == "number") and (zKey > 0) ) then
--#?                            UIDropDownMenu_SetText(MetaMap_InstanceMenu, MetaMapOptions.MetaMapZone);
                        elseif ( cKey ~= -1 or (type(zKey) == "number" and zKey == 0) or isMicroDungeon ) then
--#?                            UIDropDownMenu_ClearAll(MetaMap_InstanceMenu);
                        end
                end
        end
end

-- The buttons in the navigation bar
function MetaMap_NavBar_ClearTrailingButtons(list, freeList, button)
        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
                MetaMapOptions.ShowDNI = false;
                MetaMap_InstanceOff = true;
        end
end

-- The drop down list with the levels
function MetaMap_WorldMapLevelButton_OnClick(self)
        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
        end
end

-- map frame zoom in/out
function MetaMap_WorldMapScrollFrame_OnMouseWheel(self, delta)
        if ( WorldMapFrame.isMaximized ) then return; end

        local newScale = WorldMapFrame.ScrollContainer.currentScale;
        if ( newScale == MetaMap_oldScale ) then return; end

--[[old
        local scrollFrame = WorldMapFrame.ScrollContainer;
        local relativeFrame = UIParent;

        local myScale = scrollFrame:GetScale();
        local relativeFrameScale = relativeFrame:GetScale();

        -- get the mouse position on the frame, with 0,0 at top left
        local cursorX, cursorY = GetCursorPosition();
        cursorX = cursorX / myScale; cursorY = cursorY / myScale;
        local frameX = cursorX / relativeFrameScale - scrollFrame:GetLeft();
        local frameY = scrollFrame:GetTop() - cursorY / relativeFrameScale;

        -- figure out new scroll values
        local scaleChange = newScale / MetaMap_oldScale;
        local newScrollH = scaleChange * ( frameX + MetaMap_oldScrollH ) - frameX;
        local newScrollV = scaleChange * ( frameY + MetaMap_oldScrollV ) - frameY;
        -- clamp scroll values
        newScrollH = min(newScrollH, scrollFrame.maxX);
        newScrollH = max(0, newScrollH);
        newScrollV = min(newScrollV, scrollFrame.maxY);
        newScrollV = max(0, newScrollV);
        -- set scroll values
        scrollFrame:SetHorizontalScroll(newScrollH);
        scrollFrame:SetVerticalScroll(newScrollV);
--]]

        --save values
        MetaMap_oldScale = newScale;
--old   MetaMap_oldScrollH = newScrollH;
        MetaMap_oldScrollH = WorldMapFrame.ScrollContainer.currentScrollX;
--old   MetaMap_oldScrollV = newScrollV;
        MetaMap_oldScrollV = WorldMapFrame.ScrollContainer.currentScrollY;
end

-- reset local variables related to map zoom
function MetaMap_WorldMapScrollFrame_ResetZoom()
        MetaMap_oldScrollH = 0;
        MetaMap_oldScrollV = 0;
        MetaMap_oldScale = MetaMap_WorldMap_baseScale;
end

-- the zoomed world map is moved
function MetaMap_WorldMapScrollFrame_OnPan()
--old   MetaMap_oldScrollH = WorldMapScrollFrame:GetHorizontalScroll();
        MetaMap_oldScrollH = WorldMapFrame.ScrollContainer.currentScrollX;
--old   MetaMap_oldScrollV = WorldMapScrollFrame:GetVerticalScroll();
        MetaMap_oldScrollV = WorldMapFrame.ScrollContainer.currentScrollY;
end

-- max. zoom world map at player position
function MetaMap_WorldMapScrollFrame_MaxZoom()
        local px, py = GetPlayerMapPosition("player");
        WorldMapScrollFrame_OnMouseWheel(WorldMapScrollFrame, 9.0);
        local maxscrollx = WorldMapScrollFrame.maxX;
        local maxscrolly = WorldMapScrollFrame.maxY;
        local frameSizeX = WorldMapScrollFrame:GetRight() - WorldMapScrollFrame:GetLeft();
        local frameSizeY = WorldMapScrollFrame:GetTop() - WorldMapScrollFrame:GetBottom();
        local mapSizeX = frameSizeX + maxscrollx;
        local mapSizeY = frameSizeY + maxscrolly;
        local movex = -math.max(math.min(mapSizeX * px - frameSizeX / 2, maxscrollx), 0);
        local movey = math.max(math.min(mapSizeY * py - frameSizeY / 2, maxscrolly), 0);
        -- initialization of a few variables required for WorldMapScrollFrame_OnPan
        WorldMapScrollFrame.cursorX = 0;
        WorldMapScrollFrame.cursorY = 0;
        WorldMapScrollFrame.x = 0;
        WorldMapScrollFrame.y = 0;
        WorldMapScrollFrame_OnPan(movex, movey);
end

-- the back button in the quest detail list
function MetaMap_QuestMapFrameDetailsFrameBackButton_OnClick()
        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
                MetaMap_SavedLook = {};
                MetaMap_SavedMap = MetaMap_CopyMapData(MetaMap_ReturnMap);
                MetaMap_ReturnMap = {};
                MetaMap_ShowInstance(nil, false);
        end
end

-- quest location in the quest list
function MetaMap_QuestLogQuests_GetHeaderButton(index)
        local headers = QuestMapFrame.QuestsFrame.Contents.Headers;
        if ( headers[index] ) then
                headers[index]:SetScript("OnMouseUp", MetaMap_QuestLogQuests_HeaderButton_OnMouseUp);
        end
end

function MetaMap_QuestLogQuests_HeaderButton_OnMouseUp()
        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
        end
end

-- quest location in the quest list
function MetaMap_QuestLogQuests_GetTitleButton(index)
        local titles = QuestMapFrame.QuestsFrame.Contents.Titles;
        if ( titles[index] ) then
                titles[index]:SetScript("OnMouseUp", MetaMap_QuestMapLogTitleButton_OnMouseUp);
        end
end

function MetaMap_QuestMapLogTitleButton_OnMouseUp(self)
        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() ) then
                MetaMap_QuestID = self.questID;
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
        end
end

-- Any click at the quest log in the world map frame
function MetaMap_QuestMapFrame_OnMouseUp(self, button)
        if ( not MetaMapOptions.MapChange and (button == "RightButton") ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
        end
end

-- left click handler for maps with special buttons, like "The Cosmos" map
function MetaMap_WorldMapAreaButton_OnClick()
        MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();
        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
                MetaMap_MapRefresh = true;
        end
end

-- The function WorldMapLevelUpDown_OnClick registers changes of the map level
function MetaMap_WorldMapLevelUpDown_OnClick()
        MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();
end

-- *** Allow zoom out from all dungeons and BGs ***
-- This gets called from WorldMapFrame.lua when user right clicks on the map or
--      gets called from WorldMapFrame.xml if the "WorldMapZoomOutButton" is clicked
function MetaMap_WorldMapZoomOutButton_OnClick(self, button)
        if ( button ~= "RightButton" ) then return; end
        MetaMap_Debug_Print("MetaMap_WorldMapZoomOutButton_OnClick", true);
        if ( not MetaMapOptions.MapChange ) then
                MetaMap_StayOnMap = true;
                MetaMap_MapClick = true;
        end
        if (MetaMapOptions.MetaMapZone) then
                local _, zIndex = MetaMap_GetZoneTableEntry(MetaMapOptions.MetaMapZone);
                MetaMapOptions.ShowDNI = false;
                local mapName;
                if (zIndex) then mapName = MetaMap_ZoneTable[zIndex].Location; end
                if (mapName) then
                        local _, _, _, mapid = MetaMap_GetZoneTableEntry(mapName);
                        if (mapid ~= 0) then
                                SetMapByID(mapid);
                        else
--                              SetMapZoom(MetaMap_NameToZoneID(mapName));
--old                           MetaMap_SetMapZoomByName(mapName);
                                WorldMapFrame:SetMapID(MetaMap_NameToZoneID(zoneName));
                        end
                        MetaMapOptions.MetaMapZone = mapName;
                else
                        -- zoom out from BGs
                        local continent;
                        if (zIndex) then continent = MetaMap_ZoneTable[zIndex].Continent; end
                        if (not continent) then continent = -1; end
--old                   SetMapZoom(continent, 0);
--old                   MetaMapOptions.MetaMapZone = MetaMap_ZoneIDToName(continent, 0);
                end
                MetaMap_ShowInstance(nil, false);
                MetaMap_MainMapUpdate();
        end

        MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();
end

function MetaMapList_Highlight_Note(self)
        for i = 1, MetaMap_NoteList.lastEntry, 1 do
                _G["MetaMapNotesPOI"..i.."Highlight"]:Hide();
        end

        local lastNote = MetaMap_NoteList[self:GetID() + MetaMap_ListOffset].id;
        if (_G["MetaMapNotesPOI"..lastNote]:IsVisible()) then
                _G["MetaMapNotesPOI"..lastNote.."Highlight"]:SetTexture(METAMAP_ICON_PATH.."IconGlowRed");
                _G["MetaMapNotesPOI"..lastNote.."Highlight"]:Show();
        end
end

function MetaMapList_OnClick(self, button, id)
        MetaMap_Debug_Print("MetaMapList_OnClick", true);
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        --MetaMapList_Highlight_Note(self);
        if (button == "LeftButton") then
                if (IsShiftKeyDown()) then
                        if (not dataZone) then return; end
                        if (not ChatEdit_GetActiveWindow()) then ChatFrame_OpenChat(""); end
                        local ChatFrameEditBox = ChatEdit_GetActiveWindow();
                        if (not ChatFrameEditBox:IsVisible()) then ChatFrameEditBox:Show(); end
                        local tinf1 = dataZone[id].inf1;
                        local coords = format("%d, %d", dataZone[id].xPos *100, dataZone[id].yPos *100);
                        if (strlen(tinf1) > 0) then tinf1 = " ["..tinf1.."] "; end
                        local msg = dataZone[id].name.." "..tinf1.." ("..mapName.." - "..coords..")";
                        ChatFrameEditBox:Insert(msg);
                elseif (id == 0) then
                        MetaMapPing_SetPing(dataZone, id);
                else
                        MetaMapPing_SetPing(dataZone, MetaMap_NoteList[self:GetID() + MetaMap_ListOffset].id);
                end
        elseif (button == "RightButton") then
                if (IsControlKeyDown()) then
                        MetaMap_LoadBWP(id, 2);
                elseif (IsShiftKeyDown() and MetaMap_LoadNBK(1)) then
                        NBK_SetTargetNote(dataZone[id].name);
                else
                        MetaMap_MapNote_OnClick(self,"LeftButton", id);
                end
        end
end

function MetaMapList_BuildList()
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        MetaMap_NoteList = {};
        MetaMapList_InfoText:Hide();
        MetaMapList_PlayerButton:Hide();
        if (mapName == MetaMap_GetRealZoneText() ) then
                _G["MetaMapList_PlayerButton".."Name"]:SetText(UnitName("Player"));
                MetaMapList_PlayerButton:Show();
        end
        if (not dataZone) then
                MetaMap_MapListFrame:Hide();
        else
                local index = 1;
                for i, value in ipairs(dataZone) do
                        if (MetaMap_NoteFilter[dataZone[i].icon]) then
                                MetaMap_NoteList[index] = {};
                                MetaMap_NoteList[index]["name"] = dataZone[i]["name"];
                                MetaMap_NoteList[index]["xPos"] = dataZone[i]["xPos"];
                                MetaMap_NoteList[index]["yPos"] = dataZone[i]["yPos"];
                                MetaMap_NoteList[index]["ncol"] = dataZone[i]["ncol"];
                                MetaMap_NoteList[index]["icon"] = dataZone[i]["icon"];
                                MetaMap_NoteList[index]["id"] = i;
                                MetaMap_NoteList.lastEntry = index;
                                index = index + 1;
                        end
                end
                if (MetaMapOptions.SortList) then
                        local sort = MetaMap_sortType;
                        MetaMap_sortType = METAMAP_SORTBY_NAME;
                        table.sort(MetaMap_NoteList, MetaMap_SortCriteria);
                        MetaMap_sortType = sort;
                end
        end
end

function MetaMapList_UpdateScroll()
        for i = 1, METAMAP_LISTBUTTON_SHOWN, 1 do
                local buttonIndex = i + FauxScrollFrame_GetOffset(MetaMapList_ScrollFrame);
                local scrollFrameButton = _G["MetaMapList_ScrollFrameButton"..i];
                local NameButton = _G["MetaMapList_ScrollFrameButton"..i.."Name"];
                if (buttonIndex < MetaMap_NoteList.lastEntry + 1) then
                        MetaMap_ListOffset = buttonIndex - i;
                        NameButton:SetText(MetaMap_NoteList[buttonIndex]["name"]);
                        _G["MetaMapList_ScrollFrameButton"..i.."NoteID"]:SetText(MetaMap_NoteList[buttonIndex]["id"]);
                        if (MetaMapOptions.ListColors) then
                                local cNr = MetaMap_NoteList[buttonIndex]["ncol"];
                                NameButton:SetTextColor(MetaMap_Colors[cNr].r, MetaMap_Colors[cNr].g, MetaMap_Colors[cNr].b);
                        else
                                NameButton:SetTextColor(MetaMap_Colors[0].r, MetaMap_Colors[0].g, MetaMap_Colors[0].b);
                        end
                        scrollFrameButton:Show();
                else
                        scrollFrameButton:Hide();
                end
        end
        FauxScrollFrame_Update(MetaMapList_ScrollFrame, MetaMap_NoteList.lastEntry, METAMAP_LISTBUTTON_SHOWN, METAMAP_LISTBUTTON_HEIGHT);
end

function MetaMapPing_SetPing(dataZone, id)
        if (id == 0) then
                if (WorldMapPing:IsShown()) then
                        WorldMapPing:Hide();
                else
                        WorldMapPing:Show();
                end
                return;
        end
        if (MetaMap_gPingPOI and MetaMap_gPingPOI:IsShown()) then
                MetaMapPing_OnUpdate(1);
        end
        MetaMap_Debug_Print("MetaMapPing_SetPing: "..id, true);

        MetaMap_gPingPOI = _G["MetaMapNotesPOI"..id.."Ping"];
        if ( MetaMap_gPingPOI ) then
                MetaMap_gPingPOI:SetTexture(METAMAP_ICON_PATH.."IconPing");
                UIFrameFlash(MetaMap_gPingPOI, 0.25, 0.25, 20, false, 0.15, 0.15);
                PlaySound(SOUNDKIT.MAP_PING);
        end
end

function MetaMapPing_OnUpdate(rem)
        MetaMap_Debug_Print("MetaMapPing_OnUpdate: "..rem, true);
        if (rem) then
                -- or not UIFrameIsFading(MetaMap_PingPOI)
                UIFrameFlashStop(MetaMap_gPingPOI);
                MetaMap_gPingPOI:Hide();
                MetaMap_gPingPOI = nil;
        end
end

function MetaMap_ZoneSearch()
        if (MetaMap_NotesDialog:IsVisible()) then
                local mapName = MetaMap_GetCurrentMapInfo();
                MetaMap_ZoneSearchResult:SetText(format(METAMAP_ZONESEARCH_TEXT, mapName));
        end
end

function MetaMap_HelpOnEnter(self, header, args)
        local myArgs = {args};
        GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
        GameTooltip:SetText(header, 0.2, 0.5, 1, true);
        for i, string in pairs(myArgs) do
                GameTooltip:AddLine(string, 1, 1, 1, true);
        end
        GameTooltip:Show();
end

function MetaMap_Print(msg, display, r, g, b)
        if (not display) then return; end
        if (msg == nil) then msg = "Nil Value"; end
        if (type(msg) == "table") then msg = "Table Value"; end
        msg = "<"..METAMAP_TITLE..">: "..msg;
        if (DEFAULT_CHAT_FRAME) then
                if (r == nil or g == nil or b == nil) then
                        r = 0.60; g = 0.80; b = 1.00;
                end
                DEFAULT_CHAT_FRAME:AddMessage(msg, r, g, b);
        end
end

function MetaMap_Debug_Print(msg, display, r, g, b)
        if (not MetaMapOptions["Debug"]) then return; end
        if (not display) then return; end
        if (msg == nil) then msg = "Nil Value"; end
        if (type(msg) == "table") then msg = "Table Value"; end
        msg = "["..date("%m/%d/%y %H:%M:%S").."]".."<"..METAMAP_TITLE..">: "..msg;
        if (DEFAULT_CHAT_FRAME) then
                if(r == nil or g == nil or b == nil) then
                        r = 0.60; g = 0.80; b = 1.00;
                end
                DEFAULT_CHAT_FRAME:AddMessage(msg, r, g, b);
        end
end

function MetaMap_ToggleDR(self, mode)
        if (mode == 1) then
                DressUpFrame:SetMovable(true);
                DressUpFrame:SetFrameStrata("FULLSCREEN_DIALOG");
                DressUpFrame:SetScript("OnMouseDown", function() if (arg1 == "LeftButton") then self:StartMoving(); self.isMoving = true; end end);
                DressUpFrame:SetScript("OnMouseUp", function() if (self.isMoving) then self:StopMovingOrSizing(); self.isMoving = false; end end);
        else
                DressUpFrame:SetMovable(false);
                DressUpFrame:SetFrameStrata("HIGH");
                DressUpFrame:SetScript("OnMouseDown", nil);
                DressUpFrame:SetScript("OnMouseUp", nil);
        end
end

local function MetaMap_CreateNoteObject(noteNumber)
        local button;
        if (_G["MetaMapNotesPOI"..noteNumber]) then
                button = _G["MetaMapNotesPOI"..noteNumber];
        else
                button = CreateFrame("Button" ,"MetaMapNotesPOI"..noteNumber, WorldMapFrame.ScrollContainer.Child, "MetaMapNotes_NoteTemplate");
                MetaMap_LastNote = MetaMap_LastNote + 1;
        end
        button:SetWidth(MetaMapOptions.NoteSize);
        button:SetHeight(MetaMapOptions.NoteSize);
        button:SetID(noteNumber);
        return button;
end

local function MetaMap_CreateLineObject(lineNumber)
        local line;
        if (_G["MetaMapNotesLines_"..lineNumber]) then
                line = _G["MetaMapNotesLines_"..lineNumber];
        else
                MetaMapNotesLinesFrame:CreateTexture("MetaMapNotesLines_"..lineNumber, "ARTWORK");
                line = _G["MetaMapNotesLines_"..lineNumber];
                MetaMap_LastLine = MetaMap_LastLine + 1;
        end
        return line;
end

local function MetaMap_AddMiniNote(id, mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c)
        local dataZone = MetaMap_Notes[mapName][id];
        MetaMap_MiniNote_Data.id = id;
        MetaMap_MiniNote_Data.zonetext = mapName;
        MetaMap_MiniNote_Data.inf1 = "";
        MetaMap_MiniNote_Data.inf2 = "";
        MetaMap_MiniNote_Data.in1c = 1;
        MetaMap_MiniNote_Data.in2c = 1;
        MetaMap_MiniNote_Data.color = 0;
        MetaMap_MiniNote_Data.creator = creator;
        if (id == 0) then
                MetaMap_MiniNote_Data.xPos = xPos;
                MetaMap_MiniNote_Data.yPos = yPos;
                MetaMap_MiniNote_Data.name = name;
                MetaMap_MiniNote_Data.inf1 = inf1;
                MetaMap_MiniNote_Data.inf2 = inf2;
                MetaMap_MiniNote_Data.in1c = in1c;
                MetaMap_MiniNote_Data.in2c = in2c;
                MetaMap_MiniNote_Data.color = ncol;
                MetaMap_MiniNote_Data.icon = icon;
        elseif (id == -1) then
                MetaMap_MiniNote_Data.xPos = MetaMap_PartyNoteData.xPos;
                MetaMap_MiniNote_Data.yPos = MetaMap_PartyNoteData.yPos;
                MetaMap_MiniNote_Data.name = METAMAP_PARTYNOTE;
                MetaMap_MiniNote_Data.icon = "party";
        elseif (id > 0) then
                MetaMap_MiniNote_Data.xPos = dataZone.xPos;
                MetaMap_MiniNote_Data.yPos = dataZone.yPos;
                MetaMap_MiniNote_Data.name = dataZone.name;
                MetaMap_MiniNote_Data.inf1 = dataZone.inf1;
                MetaMap_MiniNote_Data.inf2 = dataZone.inf2;
                MetaMap_MiniNote_Data.in1c = dataZone.in1c;
                MetaMap_MiniNote_Data.in2c = dataZone.in2c;
                MetaMap_MiniNote_Data.color = dataZone.ncol;
                MetaMap_MiniNote_Data.icon = dataZone.icon;
                MetaMap_MiniNote_Data.creator = dataZone.creator;
        end
        MetaMap_MiniNoteTexture:SetTexture(METAMAP_ICON_PATH.."Icon"..MetaMap_MiniNote_Data.icon);
        MetaMap_MiniNote:Show();
        MetaMap_SetNextAsMiniNote = 0;
        MetaMapNotesButtonMiniNoteOff:Enable();
        MetaMap_MainMapUpdate();
end

local function MetaMap_CheckNearNotes(mapName, xPos, yPos)
        local dataZone = MetaMap_Notes[mapName];
        if (dataZone == nil) then return; end
        for i, value in pairs(dataZone) do
                local deltax = abs(dataZone[i].xPos - xPos);
                local deltay = abs(dataZone[i].yPos - yPos);
                if (deltax <= 0.0009765625 * MetaMap_MinDiff and deltay <= 0.0013020833 * MetaMap_MinDiff) then
                        return i;
                end
        end
        return false;
end

local function MetaMap_AddNewNote(mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c, mininote, mLevel)
        if (xPos == 0 and yPos == 0) then
                MetaMap_Print(METAMAP_INVALIDZONE, true);
                return;
        end
        if (not MetaMap_Notes[mapName] or name == nil) then return false; end
        if (inf1 == nil) then inf1 = ""; end
        if (inf2 == nil) then inf2 = ""; end
        if (icon == nil) then icon = 0; end
        if (ncol == nil) then ncol = 0; end
        if (in1c == nil) then in1c = 0; end
        if (in2c == nil) then in2c = 0; end
        if (creator == nil) then creator = UnitName("player"); end
        local id = 0;
        local checkNote;
        local returnValue = true;
        local dataZone = MetaMap_Notes[mapName];
        local index = #(dataZone);
        if (mininote == 0 or mininote == nil) then
                MetaMap_SetNextAsMiniNote = 0;
        elseif (mininote == 1) then
                MetaMap_SetNextAsMiniNote = 1;
        elseif (mininote == 2) then
                MetaMap_SetNextAsMiniNote = 2;
        end             

        if (MetaMap_SetNextAsMiniNote ~= 2) then
                checkNote = MetaMap_CheckNearNotes(mapName, xPos, yPos);
                if (checkNote) then
                        returnValue = false;
                else
                        MetaMap_TempData_Id = index + 1
                        dataZone[MetaMap_TempData_Id] = {};
                        dataZone[MetaMap_TempData_Id].name = name;
                        dataZone[MetaMap_TempData_Id].ncol = ncol;
                        dataZone[MetaMap_TempData_Id].inf1 = inf1;
                        dataZone[MetaMap_TempData_Id].in1c = in1c;
                        dataZone[MetaMap_TempData_Id].inf2 = inf2;
                        dataZone[MetaMap_TempData_Id].in2c = in2c;
                        dataZone[MetaMap_TempData_Id].creator = creator;
                        dataZone[MetaMap_TempData_Id].icon = icon;
                        dataZone[MetaMap_TempData_Id].xPos = xPos;
                        dataZone[MetaMap_TempData_Id].yPos = yPos;
                        dataZone[MetaMap_TempData_Id].mLevel = mLevel;
                        id = MetaMap_TempData_Id;
                        if (MetaMap_MiniNote_Data ~= nil and MetaMap_MiniNote_Data.name == name) then
                                MetaMap_MiniNote_Data.id = id;
                        end
                        returnValue = true;
                        checkNote = id;
                end
        end
        if (MetaMap_SetNextAsMiniNote ~= 0) then
                for i = 0, index, 1 do
                        if (dataZone[i] ~= nil) then
                                if (dataZone[i].name == name and dataZone[i].xPos == xPos and dataZone[i].yPos == yPos) then
                                        id = i;
                                        break;
                                end
                        end
                end
                MetaMap_AddMiniNote(id, mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c);
                returnValue = returnValue;
        end
        MetaMap_MainMapUpdate();
        return returnValue, checkNote;
end

local function MetaMap_DeleteMapNote(id, mapName)
        MetaMap_HideAll();
        if id == 0 then
                MetaMap_vnote_xPos = nil;
                MetaMap_vnote_yPos = nil;
                MetaMap_MainMapUpdate();
                return;
        elseif (id == -1) then
                MetaMap_PartyNoteData.xPos = nil;
                MetaMap_PartyNoteData.yPos = nil;
                MetaMap_PartyNoteData.mapName = nil;
                if(MetaMap_MiniNote_Data.id == -1) then
                        MetaMap_MiniNote_Data = {};
                end
                MetaMap_MainMapUpdate();
                return;
        end

        local TempData = {};
        TempData[mapName] = {};
        local dataZone = MetaMap_Notes[mapName][id];
        local lastEntry = #(MetaMap_Notes[mapName]);
        if (dataZone) then
                MetaMap_DeleteLines(mapName, dataZone.xPos, dataZone.yPos);
        end
        if (lastEntry ~= 0 and id <= lastEntry) then
                TempData[mapName] = MetaMap_Notes[mapName];
                MetaMap_Notes[mapName] = {};
                local newZone = TempData[mapName];
                for index, indexTable in ipairs(newZone) do
                        if (index ~= id) then
                                local oldData = newZone[index];
                                MetaMap_AddNewNote(mapName, oldData.xPos, oldData.yPos, oldData.name, oldData.inf1, oldData.inf2, oldData.creator, oldData.icon, oldData.ncol, oldData.in1c, oldData.in2c, nil, oldData.mLevel);
                        end
                end
        end
        if (MetaMap_MiniNote_Data.id == id) then
                MetaMap_ClearMiniNote(true);
        end
        MetaMap_MainMapUpdate();
end

function MetaMap_GenerateSendString(version)
        -- <MetaMap:MN> z<1> x<0.123123> y<0.123123> t<> i1<> i2<> cr<> i<8> tf<3> i1f<5> i2f<6>
        local text = "";
        local pName = UnitName("player");
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        if (not dataZone) then return; end
        if (version == 1) then text = "<MetaMap:MN>"; end
        text = text.." z<"..mapName..">";

        if (MetaMap_PartyNoteSet) then
                local xPos = floor(MetaMap_PartyNoteData.xPos * 1000000)/1000000;
                local yPos = floor(MetaMap_PartyNoteData.yPos * 1000000)/1000000;
                text = text.." x<"..xPos.."> y<"..yPos..">";
                text = text.." t<"..METAMAP_PARTYNOTE..">";
                text = text.." i1<>";
                text = text.." i2<>";
                text = text.." cr<"..pName..">";
                text = text.." i<0>";
                text = text.." tf<0>";
                text = text.." i1f<0>";
                text = text.." i2f<0>";
                text = text.." p<1>";
        elseif (MetaMap_MiniNote_Data.id == 0) then
                local xPos = floor(MetaMap_MiniNote_Data.xPos * 1000000)/1000000;
                local yPos = floor(MetaMap_MiniNote_Data.yPos * 1000000)/1000000;
                text = text.." x<"..xPos.."> y<"..yPos..">";
                text = text.." t<"..MetaMap_EliminateUsedChars(MetaMap_MiniNote_Data.name)..">";
                text = text.." i1<"..MetaMap_EliminateUsedChars(MetaMap_MiniNote_Data.inf1)..">";
                text = text.." i2<"..MetaMap_EliminateUsedChars(MetaMap_MiniNote_Data.inf2)..">";
                text = text.." cr<"..MetaMap_MiniNote_Data.creator..">";
                text = text.." i<"..MetaMap_MiniNote_Data.icon..">";
                text = text.." tf<"..MetaMap_MiniNote_Data.color..">";
                text = text.." i1f<"..MetaMap_MiniNote_Data.in1c..">";
                text = text.." i2f<"..MetaMap_MiniNote_Data.in2c..">";
        else
                if (not dataZone[MetaMap_TempData_Id].creator) then
                        dataZone[MetaMap_TempData_Id].creator = pName;
                end
                local xPos = floor(dataZone[MetaMap_TempData_Id].xPos * 1000000)/1000000; --cut to six digits behind the 0
                local yPos = floor(dataZone[MetaMap_TempData_Id].yPos * 1000000)/1000000;
                text = text.." x<"..xPos.."> y<"..yPos..">";
                text = text.." t<"..MetaMap_EliminateUsedChars(dataZone[MetaMap_TempData_Id].name)..">";
                text = text.." i1<"..MetaMap_EliminateUsedChars(dataZone[MetaMap_TempData_Id].inf1)..">";
                text = text.." i2<"..MetaMap_EliminateUsedChars(dataZone[MetaMap_TempData_Id].inf2)..">";
                text = text.." cr<"..dataZone[MetaMap_TempData_Id].creator..">";
                text = text.." i<"..dataZone[MetaMap_TempData_Id].icon..">";
                text = text.." tf<"..dataZone[MetaMap_TempData_Id].ncol..">";
                text = text.." i1f<"..dataZone[MetaMap_TempData_Id].in1c..">";
                text = text.." i2f<"..dataZone[MetaMap_TempData_Id].in2c..">";
        end
        MetaMap_PartyNoteSet = false;
        return text;
end

function MetaMap_EliminateUsedChars(text)
        text = string.gsub(text, "<", "");
        text = string.gsub(text, ">", "");
        return text;
end

function MetaMap_GetSendString(msg, who)
        local zone = gsub(msg,".*<MetaMap:MN> z<([^>]*)>.*","%1",1);
        local xPos = gsub(msg,".*<MetaMap:MN>%s+%w+.*x<([^>]*)>.*","%1",1)+0;
        local yPos = gsub(msg,".*<MetaMap:MN>%s+%w+.*y<([^>]*)>.*","%1",1)+0;
        local name = gsub(msg,".*<MetaMap:MN>%s+%w+.*t<([^>]*)>.*","%1",1);
        local inf1 = gsub(msg,".*<MetaMap:MN>%s+%w+.*i1<([^>]*)>.*","%1",1);
        local inf2 = gsub(msg,".*<MetaMap:MN>%s+%w+.*i2<([^>]*)>.*","%1",1);
        local creator = gsub(msg,".*<MetaMap:MN>%s+%w+.*cr<([^>]*)>.*","%1",1);
        local icon = gsub(msg,".*<MetaMap:MN>%s+%w+.*i<([^>]*)>.*","%1",1)+0;
        local ncol = gsub(msg,".*<MetaMap:MN>%s+%w+.*tf<([^>]*)>.*","%1",1)+0;
        local in1c = gsub(msg,".*<MetaMap:MN>%s+%w+.*i1f<([^>]*)>.*","%1",1)+0;
        local in2c = gsub(msg,".*<MetaMap:MN>%s+%w+.*i2f<([^>]*)>.*","%1",1)+0;
        local mLevel = gsub(msg,".*<MetaMap:MN>%s+%w+.*m<([^>]*)>.*","%1",1)+0;

        local mapName = MetaMap_GetZoneTableEntry(zone);
        local noteAdded, noteID = MetaMap_AddNewNote(mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c, MetaMap_SetNextAsMiniNote, mLevel);
        if (who == nil) then
                if (noteAdded) then
                        MetaMap_Print(format(METAMAP_ACCEPT_NOTE, mapName), true);
                else
                        MetaMap_Print(format(METAMAP_DECLINE_NOTE, MetaMap_Notes[mapName][noteID].name, mapName), true);
                end
        else
                if (noteAdded) then
                        MetaMap_Print(format(METAMAP_ACCEPT_GET, who, mapName), true);
                else
                        MetaMap_Print(format(METAMAP_DECLINE_GET, who, mapName, MetaMap_Notes[mapName][noteID].name), true);
                end
        end
        return noteAdded;
end

function MetaMap_Quicknote(msg)
        MetaMap_SetMapToCurrentZone();

        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        local px, py = C_Map.GetBestMapForUnit("player");
        if (not dataZone or px == 0 or px == nil) then
                MetaMap_Print(METAMAP_INVALIDZONE, true);
                return;
        end
        local name = METAMAP_QUICKNOTE_DEFAULTNAME;
        if (msg ~= "" and msg ~= nil) then
                if (strlen(msg) == 1) then
                        mode = tonumber(strsub(msg, 1, 1));
                        msg = "";
                else
                        local mCheck = strsub(msg, 1, 2);
                        if (mCheck == "1 " or mCheck == "2 " or mCheck == "3 ") then
                                mode = tonumber(strsub(msg, 1, 1));
                                msg = strsub(msg, 3);
                        else
                                mode = MetaMap_SetNextAsMiniNote;
                        end
                end
        else
                mode = MetaMap_SetNextAsMiniNote;
        end
        local i, j, x, y, tmp = string.find(msg,"%s*(%d+)%s*[,.]%s*(%d+)%s*([^%c]*)");
        if (x ~= nil and y ~= nil) then
                px = x / 100;
                py = y / 100;
                msg = tmp;
        end
        if (mode == 3) then
                MetaMap_vnote_xPos = px;
                MetaMap_vnote_yPos = py;
                MetaMap_Print(METAMAP_VNOTE_SET, true);
                return;
        end
        if (msg ~= "" and msg ~= nil) then
                name = string.sub(msg,string.find(msg,"%s*([^%c]*)"));
        end
        local noteAdded, noteID = MetaMap_AddNewNote(mapName, px, py, name, "", "", UnitName("player"), 0, 0, 0, 0, mode, MetaMap_GetCurrentMapDungeonLevel());
        if (noteAdded) then
                if (mode ~= 2) then
                        MetaMap_Print(format(METAMAP_ACCEPT_NOTE, MetaMap_GetRealZoneText()), true);
                end
        else
                MetaMap_Print(format(METAMAP_DECLINE_NOTE, dataZone[noteID].name, MetaMap_GetRealZoneText()), true);
        end
        if (mode > 0) then
                MetaMap_Print(format(METAMAP_ACCEPT_MININOTE, MetaMap_GetRealZoneText()), true);
        end
        MetaMap_Qnote = false;
end

function MetaMap_QuickNoteShow()
        local x, y = C_Map.GetBestMapForUnit("player");
        local coords = format("%d, %d", x * 100, y * 100);
        Coords_EditBox:SetText(coords);
        MiniNote_CheckButton:SetChecked(false);
        MetaMap_Qnote = true;
end

function MetaMap_SetQuickNote(mode)
        local msg;
        if (mode == 1) then
                msg = Coords_EditBox:GetText().." "..Note_EditBox:GetText();
        else
                msg = "3 "..Coords_EditBox:GetText();
        end
        MetaMap_Quicknote(msg);
end

function MetaMap_GetNoteFromChat(msg, who)
        if (not MetaMapOptions.AcceptIncoming) then
                MetaMap_Print(format(METAMAP_DISABLED_GET, who), true);
                return;
        end
        if (gsub(msg,".*<MetaMap:MN>%s+%w+.*p<([^>]*)>.*","%1",1) == "1") then -- Party Note
                local id = -1;
                local zone = gsub(msg,".*<MetaMap:MN>%s+%w+.*z<([^>]*)>.*","%1",1);
                local xPos = gsub(msg,".*<MetaMap:MN>%s+%w+.*x<([^>]*)>.*","%1",1)+0;
                local yPos = gsub(msg,".*<MetaMap:MN>%s+%w+.*y<([^>]*)>.*","%1",1)+0;
                local icon = "party";
                local mapName = MetaMap_GetZoneTableEntry(zone);
                MetaMap_PartyNoteData.zone = mapName;
                MetaMap_PartyNoteData.xPos = xPos;
                MetaMap_PartyNoteData.yPos = yPos;
                if (MetaMapOptions.MiniParty) then
                        MetaMap_AddMiniNote(id, mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c);
                        MetaMap_Print(format(METAMAP_PARTY_GET, who, mapName), true);
                end
        else
                MetaMap_GetSendString(msg, who);
        end
end

function MetaMap_GetNoteBySlashCommand(msg)
        if (msg and msg ~= "") then
                msg = "<MetaMap:MN> "..msg;
                return MetaMap_GetSendString(msg);
        else
                MetaMap_Print(METAMAP_MAPNOTEHELP, true);
                return false;
        end
end

function MetaMap_Misc_OnClick(self, button)
        if (not MetaMap_FramesHidden()) then return; end
        if (button == "LeftButton") then
                if (self:GetID() == 0) then
                        MetaMap_TempData_Id = 0;
                        MetaMap_EditExistingNote(MetaMap_TempData_Id);
                elseif (self:GetID() == 1) then
                        MetaMap_PartyNoteSet = true;
                        MetaMap_TempData_Id = -1;
                        MetaMap_ShowSendFrame(0);
                end
        end
end

function MetaMap_NextMiniNote(msg)
        msg = string.lower(msg);
        if (msg == "on") then
                MetaMap_SetNextAsMiniNote = 1;
        elseif (msg == "off") then
                MetaMap_SetNextAsMiniNote = 0;
        elseif (MetaMap_SetNextAsMiniNote == 1) then
                MetaMap_SetNextAsMiniNote = 0;
        else
                MetaMap_SetNextAsMiniNote = 1;
        end
end

function MetaMap_NextMiniNoteOnly(msg)
        msg = string.lower(msg);
        if (msg == "on") then
                MetaMap_SetNextAsMiniNote = 2;
        elseif (msg == "off") then
                MetaMap_SetNextAsMiniNote = 0;
        elseif (MetaMap_SetNextAsMiniNote == 2) then
                MetaMap_SetNextAsMiniNote = 0;
        else
                MetaMap_SetNextAsMiniNote = 2;
        end
end

function MetaMap_MinimapUpdateZoom()
        if (MetaMap_MiniNote_MapzoomInit) then
                if (MetaMap_MiniNote_IsInCity) then
                        MetaMap_MiniNote_IsInCity = false;
                else
                        MetaMap_MiniNote_IsInCity = true;
                end
        else
                local tempzoom = 0;
                if (GetCVar("minimapZoom") == GetCVar("minimapInsideZoom")) then
                        if (GetCVar("minimapInsideZoom") + 0 >= 3) then
                                Minimap:SetZoom(Minimap:GetZoom() - 1);
                                tempzoom = 1;
                        else
                                Minimap:SetZoom(Minimap:GetZoom() + 1);
                                tempzoom = - 1;
                        end
                end

                if (GetCVar("minimapInsideZoom") + 0 == Minimap:GetZoom()) then
                        MetaMap_MiniNote_IsInCity = true;
                else
                        MetaMap_MiniNote_IsInCity = false;
                end

                Minimap:SetZoom(Minimap:GetZoom() + tempzoom);
                MetaMap_IsInside = MetaMap_MiniNote_IsInCity;
--old           local _, _, _, isMicroDungeon = GetMapInfo();
--old           MetaMap_IsMicroDungeon = isMicroDungeon;
                MetaMap_MiniNote_MapzoomInit = true;
        end
end

function MetaMap_MiniNote_OnUpdate(elapsed)
        if (MetaMap_GetRealZoneText() ~= MetaMap_MiniNote_Data.zonetext) then
                MetaMap_MiniNote:Hide();
                return;
        end
        local zName, zIndex = MetaMap_GetZoneTableEntry(MetaMap_GetRealZoneText());
        local continent, zone = MetaMap_NameToZoneID(MetaMap_GetRealZoneText());
--old   if (not zIndex or continent ~= GetCurrentMapContinent() or zone ~= GetCurrentMapZone()) then return; end
        if (not zIndex or continent ~= GetCurrentMapContinent() or zone ~= 1) then return; end
        local x, y = C_Map.GetBestMapForUnit("player");
        if (x == 0 and y == 0) then return; end
        local currentSet = MetaMap_ZoneTable[zIndex];
        local currentZoom = Minimap:GetZoom();
        local xscale, yscale;
        if (zone >= 0) then
                xscale = MetaMap_MapScale[continent][currentZoom].xscale;
                yscale = MetaMap_MapScale[continent][currentZoom].yscale;
        else
                xscale = currentSet.xscale;
                yscale = currentSet.yscale;
        end
        if (MetaMap_MiniNote_IsInCity) then
                xscale = xscale * MetaMap_MapScale.cityscale[currentZoom];
                yscale = yscale * MetaMap_MapScale.cityscale[currentZoom];
        end
        local xpos = MetaMap_MiniNote_Data.xPos * currentSet.scale + currentSet.xoffset;
        local ypos = MetaMap_MiniNote_Data.yPos * currentSet.scale + currentSet.yoffset;
        x = x * currentSet.scale + currentSet.xoffset;
        y = y * currentSet.scale + currentSet.yoffset;
        local deltax = (xpos - x) * xscale;
        local deltay = (ypos - y) * yscale;
        if (sqrt( (deltax * deltax) + (deltay * deltay) ) > 56.5) then
                local adjust = 1;
                if (deltax == 0) then
                        deltax = deltax + 0.0000000001;
                elseif (deltax < 0) then
                        adjust = - 1;
                end
                local m = math.atan(deltay / deltax);
                deltax = math.cos(m) * 57 * adjust;
                deltay = math.sin(m) * 57 * adjust;
        end
        MetaMap_MiniNote:SetPoint("CENTER", MinimapCluster, "TOPLEFT", 105 + deltax, -93 - deltay);
        MetaMap_MiniNote:Show();
end

function MetaMap_MiniNote_OnClick(self, arg1)
        if (arg1 == "LeftButton" and IsShiftKeyDown()) then
                if (not ChatEdit_GetActiveWindow()) then ChatFrame_OpenChat(""); end
                local ChatFrameEditBox = ChatEdit_GetActiveWindow();
                if (not ChatFrameEditBox:IsVisible()) then ChatFrameEditBox:Show(); end
                local coords = format("%d, %d", MetaMap_MiniNote_Data.xPos *100, MetaMap_MiniNote_Data.yPos *100);
                local msg = MetaMap_MiniNote_Data.name.." ("..MetaMap_GetRealZoneText().." - "..coords..")";
                ChatFrameEditBox:Insert(msg);
        else
                if (MetaMap_MiniNote_Data.id > 0) then
                        MetaMap_SetMapToCurrentZone();
                        if (not WorldMapFrame:IsVisible()) then
                                MetaMapNotesEditFrame:SetParent(UIParent);
                        end
                        MetaMap_EditExistingNote(MetaMap_MiniNote_Data.id);
                elseif (MetaMap_MiniNote_Data.id == 0) then
                        MetaMap_TempData_Id = 0;
                        MetaMap_ShowSendFrame(0);
                else
                        MetaMap_PartyNoteSet = true;
                        MetaMap_TempData_Id = -1;
                        MetaMap_ShowSendFrame(0);
                end
        end
end

function MetaMap_EditNewNote(ax, ay)
        if (not MetaMap_FramesHidden()) then return; end
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        local width = WorldMapFrame.ScrollContainer:GetWidth();
        local height = WorldMapFrame.ScrollContainer:GetHeight();
        local xOffset,yOffset;
        MetaMap_TempData_xPos = ax;
        MetaMap_TempData_yPos = ay;
        MetaMap_TempData_Id = nil;
        if (ax*1002 >= (1002 - 195)) then
                xOffset = ax * width - 176;
        else
                xOffset = ax * width;
        end
        if (ay*668 <= (668 - 156)) then
                yOffset = -(ay * height) - 75;
        else
                yOffset = -(ay * height) + 87;
        end
        if (MetaMap_TempData_Id == 0) then
                MetaMap_vnote_xPos = nil;
                MetaMap_vnote_yPos = nil;
        end
        MetaMap_TempData_Id = #(dataZone) + 1;
        MetaMap_TempData_Creator = UnitName("player");
        MetaMap_Edit_SetIcon(0);
        MetaMap_Edit_SetTextColor(0);
        MetaMap_Edit_SetInfo1Color(0);
        MetaMap_Edit_SetInfo2Color(0);
        TitleWideEditBox:SetText("");
        Info1WideEditBox:SetText("");
        Info2WideEditBox:SetText("");
        if(MetaMapOptions["AutoFillCoords"]) then
                TitleWideEditBox:SetText(format("%d, %d", ax*100, ay *100));
        else
                TitleWideEditBox:SetText("");
        end

        CreatorWideEditBox:SetText(MetaMap_TempData_Creator);
        MetaMap_HideAll();
        MetaMapNotesButtonMiniNoteOff:Disable();
        MetaMapNotesButtonMiniNoteOn:Disable();
        MetaMapNotesButtonDeleteNote:Disable();
        MetaMapNotesButtonToggleLine:Disable();
        MetaMap_SendNoteButton:Disable();
        MetaMapNotesButtonMoveNote:Disable();
        MetaMapNotesEditFrameTitle:SetText(METAMAP_NEW_NOTE);
        MetaMapNotesEditFrame:Show();
end

function MetaMap_EditExistingNote(id)
        MetaMap_HideAll();
        MetaMapNotesEditFrameTitle:SetText(METAMAP_EDIT_NOTE);
        if (MetaMap_MiniNote_Data.xPos == nil) then
                MetaMapNotesButtonMiniNoteOff:Disable();
        else
                MetaMapNotesButtonMiniNoteOff:Enable();
        end
        MetaMapNotesButtonMiniNoteOn:Enable();
        MetaMapNotesButtonDeleteNote:Enable();
        MetaMapNotesButtonToggleLine:Enable();
        MetaMapNotesButtonMoveNote:Enable();

        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        MetaMap_TempData_Id = id;

        if (id == 0) then
--old           WorldMapPOIFrame.allowBlobTooltip = true;
                WorldMapTooltip:Hide();
                MetaMap_EditNewNote(MetaMap_vnote_xPos, MetaMap_vnote_yPos);
                return;
        elseif (id == -1) then
--old           WorldMapPOIFrame.allowBlobTooltip = true;
                WorldMapTooltip:Hide();
                MetaMap_EditNewNote(MetaMap_PartyNoteData.xPos, MetaMap_PartyNoteData.yPos);
                return;
        end
        MetaMap_TempData_LootID = nil;
        if (dataZone[MetaMap_TempData_Id].lootid ~= nil) then
                MetaMap_TempData_LootID = dataZone[MetaMap_TempData_Id].lootid;
        end
        MetaMap_TempData_Zone = mapName;
        MetaMap_TempData_Name = dataZone[MetaMap_TempData_Id].name;
        MetaMap_TempData_Creator = dataZone[MetaMap_TempData_Id].creator;
        MetaMap_TempData_xPos = dataZone[MetaMap_TempData_Id].xPos;
        MetaMap_TempData_yPos = dataZone[MetaMap_TempData_Id].yPos;
        MetaMap_Edit_SetIcon(dataZone[MetaMap_TempData_Id].icon);
        MetaMap_Edit_SetTextColor(dataZone[MetaMap_TempData_Id].ncol);
        MetaMap_Edit_SetInfo1Color(dataZone[MetaMap_TempData_Id].in1c);
        MetaMap_Edit_SetInfo2Color(dataZone[MetaMap_TempData_Id].in2c);
        TitleWideEditBox:SetText(dataZone[MetaMap_TempData_Id].name);
        Info1WideEditBox:SetText(dataZone[MetaMap_TempData_Id].inf1);
        Info2WideEditBox:SetText(dataZone[MetaMap_TempData_Id].inf2);
        CreatorWideEditBox:SetText(dataZone[MetaMap_TempData_Id].creator);
        MetaMapNotesEditFrame:Show();
end

function MetaMap_NoteEditorSave()
        MetaMap_HideAll();
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        if (not dataZone) then return; end
        dataZone[MetaMap_TempData_Id] = {};
        dataZone[MetaMap_TempData_Id].name = TitleWideEditBox:GetText();
        dataZone[MetaMap_TempData_Id].ncol = MetaMap_TempData_TextColor;
        dataZone[MetaMap_TempData_Id].inf1 = Info1WideEditBox:GetText();
        dataZone[MetaMap_TempData_Id].in1c = MetaMap_TempData_Info1Color;
        dataZone[MetaMap_TempData_Id].inf2 = Info2WideEditBox:GetText();
        dataZone[MetaMap_TempData_Id].in2c = MetaMap_TempData_Info2Color;
        dataZone[MetaMap_TempData_Id].creator = CreatorWideEditBox:GetText();
        dataZone[MetaMap_TempData_Id].icon = MetaMap_TempData_Icon;
        dataZone[MetaMap_TempData_Id].xPos = MetaMap_TempData_xPos;
        dataZone[MetaMap_TempData_Id].yPos = MetaMap_TempData_yPos;
        dataZone[MetaMap_TempData_Id].mLevel = MetaMap_GetCurrentMapDungeonLevel();

        if (MetaMap_TempData_LootID ~= nil) then
                dataZone[MetaMap_TempData_Id].lootid = MetaMap_TempData_LootID;
                MetaMap_TempData_LootID = nil;
        end
        if (mapName == MetaMap_MiniNote_Data.zonetext and MetaMap_MiniNote_Data.id == MetaMap_TempData_Id) then
                MetaMap_MiniNote_Data.zonetext = mapName;
                MetaMap_MiniNote_Data.name = TitleWideEditBox:GetText();
                MetaMap_MiniNote_Data.icon = MetaMap_TempData_Icon;
                MetaMap_MiniNoteTexture:SetTexture(METAMAP_ICON_PATH.."Icon"..MetaMap_MiniNote_Data.icon);
                MetaMap_MiniNote_Data.inf1 = Info1WideEditBox:GetText();
                MetaMap_MiniNote_Data.inf2 = Info2WideEditBox:GetText();
                MetaMap_MiniNote_Data.in1c = MetaMap_TempData_Info1Color;
                MetaMap_MiniNote_Data.in2c = MetaMap_TempData_Info2Color;
                MetaMap_MiniNote_Data.color = MetaMap_TempData_TextColor;
                MetaMap_MiniNote_Data.creator = CreatorWideEditBox:GetText();
        end
        if (MetaMap_vnote_xPos == MetaMap_TempData_xPos and MetaMap_vnote_yPos == MetaMap_TempData_yPos) then
                MetaMap_vnote_xPos = nil;
                MetaMap_vnote_yPos = nil;
        end
        MetaMap_MainMapUpdate();
end

function MetaMap_ShowSendFrame(mode)
        MetaMap_SendPlayer:Disable();
        MetaMap_SendParty:Disable();
        MetaMap_SendGuild:Disable();
        MetaMap_ChangeSendFrame:Enable();
        SendWideEditBox:Show();
        MetaMap_SendFramePlayer:Show();
        MetaMap_DeletePartyNote:Hide();
        if (mode == 0) then
                if (GetNumSubgroupMembers() > 0 or IsInRaid()) then MetaMap_SendParty:Enable(); end
                if (IsInGuild()) then MetaMap_SendGuild:Enable(); end
                MetaMap_DeletePartyNote:Show();
                MetaMap_ChangeSendFrame:Disable();
                MetaMap_SendFramePlayer:Hide();
                SendWideEditBox:Hide();
        elseif (mode == 1) then
                MetaMap_ToggleSendValue = 2;
                if (GetNumSubgroupMembers() > 0 or IsInRaid()) then MetaMap_SendParty:Enable(); end
                if (IsInGuild()) then MetaMap_SendGuild:Enable(); end
                SendWideEditBox:SetText("");
                MetaMap_SendFrameTitle:SetText(METAMAP_SEND_NOTE);
                MetaMap_SendFrameTip:SetText(METAMAP_SEND_TIP);
                MetaMap_SendFramePlayer:SetText(METAMAP_SEND_PLAYER);
                MetaMap_ChangeSendFrame:SetText(METAMAP_SLASHCOMMAND);
        elseif (mode == 2) then
                MetaMap_ToggleSendValue = 1;
                MetaMap_SendFrameTitle:SetText(METAMAP_SEND_SLASHTITLE);
                MetaMap_SendFrameTip:SetText(METAMAP_SEND_SLASHTIP);
                MetaMap_SendFramePlayer:SetText(METAMAP_SEND_SLASHCOMMAND);
                MetaMap_ChangeSendFrame:SetText(METAMAP_SHOWSEND);
                SendWideEditBox:SetText("/mapnote"..MetaMap_GenerateSendString(2));
        end
        if (not MetaMap_SendFrame:IsVisible()) then
                MetaMap_HideAll();
                MetaMap_SendFrame:Show();
        end
end

function MetaMap_Edit_SetIcon(icon)
        MetaMap_TempData_Icon = icon;
        IconOverlay:SetPoint("TOPLEFT", "EditIcon"..icon, "TOPLEFT", -3, 3);
end

function MetaMap_Edit_SetTextColor(color)
        MetaMap_TempData_TextColor = color;
        TextColorOverlay:SetPoint("TOPLEFT", "TextColor"..color, "TOPLEFT", -3, 3);
end

function MetaMap_Edit_SetInfo1Color(color)
        MetaMap_TempData_Info1Color = color;
        Info1ColorOverlay:SetPoint("TOPLEFT", "Info1Color"..color, "TOPLEFT", -3, 3);
end

function MetaMap_Edit_SetInfo2Color(color)
        MetaMap_TempData_Info2Color = color;
        Info2ColorOverlay:SetPoint("TOPLEFT", "Info2Color"..color, "TOPLEFT", -3, 3);
end

function MetaMap_SendNote(self,mode)
        if (mode == 1) then
                if (strlen(SendWideEditBox:GetText()) > 1) then
                        SendChatMessage(MetaMap_GenerateSendString(1), "WHISPER", self.language, SendWideEditBox:GetText());
                        MetaMap_Print(format(METAMAP_NOTE_SENT, SendWideEditBox:GetText()), true);
                else
                        MetaMap_Print(METAMAP_NOPLAYER, true);
                end
        elseif (mode == 2) then
                if (IsInRaid()) then
                        SendAddonMessage("MetaMap:MN", MetaMap_GenerateSendString(1), "RAID");
                        MetaMap_Print(METAMAP_RAIDSENT, true);
                elseif (GetNumSubgroupMembers() > 0) then
                        SendAddonMessage("MetaMap:MN", MetaMap_GenerateSendString(1), "PARTY");
                        MetaMap_Print(METAMAP_PARTYSENT, true);
                else
                        MetaMap_Print(METAMAP_NOPARTY, true);
                end
        elseif (mode == 3) then
                if (IsInGuild()) then
                        SendAddonMessage("MetaMap:MN", MetaMap_GenerateSendString(1), "GUILD");
                        MetaMap_Print(METAMAP_GUILDSENT, true);
                else
                        MetaMap_Print(METAMAP_NOGUILD, true);
                end
        end
        MetaMap_HideAll();
end

function MetaMap_ClearMiniNote(skipMapUpdate)
        MetaMap_MiniNote_Data = {};
        if (MetaMap_PartyNoteData ~= nil) then
                MetaMap_DeleteMapNote(-1);
        end
        MetaMap_MiniNote:Hide();
        MetaMapNotesButtonMiniNoteOff:Disable();
        if not skipMapUpdate then
                MetaMap_MainMapUpdate();
        end
end

function MetaMap_MainMapUpdate()
        MetaMap_Debug_Print("MetaMap_MainMapUpdate", true);
        if (WorldMapFrame.ScrollContainer:IsVisible()) then
                MetaMap_WorldMapButton_OnUpdate();
        end
        if (Minimap:IsVisible() and MinimapPing_OnUpdate ~= nil) then
                MinimapPing_OnUpdate(Minimap, 0); --3.0.2
        end
end

function MetaMap_HideAll()
        MetaMapNotesEditFrame:Hide();
        MetaMap_SendFrame:Hide();
        MetaMap_QuickNoteFrame:Hide();
        MetaMap_ClearGUI();
end

function MetaMap_FramesHidden()
        if (MetaMapNotesEditFrame:IsVisible()) then return false; end
        if (MetaMap_SendFrame:IsVisible()) then return false; end
        if (MetaMap_QuickNoteFrame:IsVisible()) then return false; end
        return true;
end

function MetaMap_MapNoteOnEnter(self,id)
        --MetaMap_Debug_Print("MapNoteOnEnter", true);
        if (MetaMap_FramesHidden()) then
                --MetaMap_Debug_Print("MapNoteOnEnter:Showing", true);
                local x, y = self:GetCenter();
                local x2, y2 = WorldMapFrame.ScrollContainer:GetCenter();
                local anchor = "";
                if (x > x2) then
                        anchor = "ANCHOR_LEFT";
                else
                        anchor = "ANCHOR_RIGHT";
                end
                WorldMapTooltip:SetOwner(self, anchor);
                if (id  == 0) then
                        WorldMapTooltip:SetText(METAMAP_VNOTE_DEFAULTNAME);
                elseif (id == -1) then
                        WorldMapTooltip:SetText(METAMAP_PARTYNOTE);
                else
                        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
                        if (not dataZone or not dataZone[id]) then return; end
                        local blt = "";
                        local cNr = dataZone[id].ncol;
                        WorldMapTooltip:AddDoubleLine(dataZone[id].name, blt, MetaMap_Colors[cNr].r, MetaMap_Colors[cNr].g, MetaMap_Colors[cNr].b, MetaMapOptions.TooltipWrap);
                        if (dataZone[id].inf1 ~= nil and dataZone[id].inf1 ~= "") then
                                cNr = dataZone[id].in1c;
                                WorldMapTooltip:AddLine(dataZone[id].inf1, MetaMap_Colors[cNr].r, MetaMap_Colors[cNr].g, MetaMap_Colors[cNr].b, MetaMapOptions.TooltipWrap);
                        end
                        if (dataZone[id].inf2 ~= nil and dataZone[id].inf2 ~= "") then
                                cNr = dataZone[id].in2c;
                                WorldMapTooltip:AddLine(dataZone[id].inf2, MetaMap_Colors[cNr].r, MetaMap_Colors[cNr].g, MetaMap_Colors[cNr].b, MetaMapOptions.TooltipWrap);
                        end
                        if (dataZone[id].creator ~= nil and dataZone[id].creator ~= "" and MetaMapOptions.ShowCreator) then
                                WorldMapTooltip:AddDoubleLine(METAMAP_CREATEDBY, dataZone[id].creator, 0, 0.75, 0.85, 0, 0.75, 0.85);
                        end
                end
--old           WorldMapPOIFrame.allowBlobTooltip = false;
                WorldMapTooltip:Show();
        else
--old           WorldMapPOIFrame.allowBlobTooltip = true;
                WorldMapTooltip:Hide();
        end
end

function MetaMap_MiniNote_OnEnter(self)
        GameTooltip:SetOwner(self, "ANCHOR_CURSOR");
        if(MetaMap_MiniNote_Data.id == -1) then
                GameTooltip:SetText(METAMAP_PARTYNOTE);
        else
                local color = MetaMap_Colors[MetaMap_MiniNote_Data.color];
                GameTooltip:SetText(MetaMap_MiniNote_Data.name, color.r, color.g, color.b, MetaMapOptions.TooltipWrap);
                local in1c = MetaMap_Colors[MetaMap_MiniNote_Data.in1c];
                GameTooltip:AddLine(MetaMap_MiniNote_Data.inf1, in1c.r, in1c.g, in1c.b, MetaMapOptions.TooltipWrap);
                local in2c = MetaMap_Colors[MetaMap_MiniNote_Data.in2c];
                GameTooltip:AddLine(MetaMap_MiniNote_Data.inf2, in2c.r, in2c.g, in2c.b, MetaMapOptions.TooltipWrap);
                if (MetaMap_MiniNote_Data.creator ~= nil and MetaMap_MiniNote_Data.creator ~= "" and MetaMapOptions.ShowCreator) then
                        GameTooltip:AddDoubleLine(METAMAP_CREATEDBY, MetaMap_MiniNote_Data.creator, 0, 0.75, 0.85, 0, 0.75, 0.85);
                end
        end
        GameTooltip:Show();
end

function MetaMap_MapNote_OnClick(self, button, id)
        if (not MetaMap_FramesHidden()) then return; end
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        if (not dataZone) then return; end

        if (MetaMap_LastLineClick.GUIactive) then
                id = id + 0;
                local ax = dataZone[id].xPos;
                local ay = dataZone[id].yPos;
                if ( (MetaMap_LastLineClick.x ~= ax or MetaMap_LastLineClick.y ~= ay) and MetaMap_LastLineClick.mapName == mapName) then
                        MetaMap_ToggleLine(mapName, ax, ay, MetaMap_LastLineClick.x, MetaMap_LastLineClick.y);
                end
                MetaMap_ClearGUI();
        elseif (button == "LeftButton") then
                if (IsShiftKeyDown()) then
                        if (not ChatEdit_GetActiveWindow()) then ChatFrame_OpenChat(""); end
                        local ChatFrameEditBox = ChatEdit_GetActiveWindow();
                        if (not ChatFrameEditBox:IsVisible()) then ChatFrameEditBox:Show(); end
                        local mode = 1;
                        local tinf1 = dataZone[id].inf1;
                        local coords = format("%d, %d", dataZone[id].xPos *100, dataZone[id].yPos *100);
                        if (strlen(tinf1) > 0) then tinf1 = " ["..tinf1.."] "; end
                        local msg = dataZone[id].name.." "..tinf1.." ("..mapName.." - "..coords..")";
                        ChatFrameEditBox:Insert(msg);
                elseif (dataZone[id].icon ~= 10) then
                        local width = WorldMapFrame.ScrollContainer:GetWidth();
                        local height = WorldMapFrame.ScrollContainer:GetHeight();
                        id = id + 0;
                        MetaMap_TempData_Id = id;
                        local ax = dataZone[id].xPos;
                        local ay = dataZone[id].yPos;
                        if (ax*1002 >= (1002 - 195)) then
                                xOffset = ax * width - 176;
                        else
                                xOffset = ax * width;
                        end
                        if (ay*668 <= (668 - 156)) then
                                yOffset = -(ay * height) - 75;
                        else
                                yOffset = -(ay * height) + 113;
                        end
                        MetaMap_SendNoteButton:Enable();
--old                   WorldMapPOIFrame.allowBlobTooltip = true;                       
                        WorldMapTooltip:Hide();
                        MetaMap_EditExistingNote(MetaMap_TempData_Id);
                end
        elseif (button == "RightButton") then
                if (IsControlKeyDown()) then
                        MetaMapNotes_CRBSelect(id);
                elseif (IsShiftKeyDown() and MetaMap_LoadNBK(1)) then
                        NBK_SetTargetNote(dataZone[id].name);
                else
                        MetaMap_LoadBWP(self:GetID(), 2);
                end
        end
end

function MetaMap_StartGUIToggleLine()
        MetaMap_HideAll();
        MetaMapText_NoteTotals:SetText("|cffffffff"..METAMAP_CLICK_ON_SECOND_NOTE);
        MetaMap_LastLineClick.GUIactive = true;
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        MetaMap_LastLineClick.x = dataZone[MetaMap_TempData_Id].xPos;
        MetaMap_LastLineClick.y = dataZone[MetaMap_TempData_Id].yPos;
        MetaMap_LastLineClick.mapName = mapName;
end

function MetaMap_StartMoveNote(ID)
        MetaMap_HideAll();
        MetaMapText_NoteTotals:SetText("|cffffffff"..METAMAP_CLICK_ON_LOCATION);
        local mapName = MetaMap_GetCurrentMapInfo();
        MetaMap_Relocate.mapName = mapName;
        MetaMap_Relocate.id = ID;
end

function MetaMap_MoveNote(mapName, id)
        local zoneTable = MetaMap_Lines[mapName];
        local lineCount = #(zoneTable);
        local currentX = MetaMap_Notes[mapName][id].xPos;
        local currentY = MetaMap_Notes[mapName][id].yPos;
        local centerX, centerY = WorldMapFrame.ScrollContainer:GetCenter();
        local width = WorldMapFrame.ScrollContainer:GetWidth();
        local height = WorldMapFrame.ScrollContainer:GetHeight();
        local x, y = GetCursorPosition();
        x = x / WorldMapFrame.ScrollContainer:GetEffectiveScale();
        y = y / WorldMapFrame.ScrollContainer:GetEffectiveScale();

        if (centerX == nil) then
                centerX = 0;
        end
        if (centerY == nil) then
                centerY = 0;
        end

        local adjustedY = (centerY + height/2 - y) / height;
        local adjustedX = (x - (centerX - width/2)) / width;
        MetaMap_Notes[mapName][id].xPos = adjustedX;
        MetaMap_Notes[mapName][id].yPos = adjustedY;
        if (MetaMap_MiniNote_Data.id == id) then
                MetaMap_MiniNote_Data.xPos = adjustedX;
                MetaMap_MiniNote_Data.yPos = adjustedY;
        end
        for i = 1, lineCount, 1 do
                if (i <= lineCount) then
                        if (zoneTable[i].x1 == currentX and zoneTable[i].y1 == currentY) then
                                zoneTable[i].x1 = adjustedX;
                                zoneTable[i].y1 = adjustedY;
                        elseif (zoneTable[i].x2 == currentX and zoneTable[i].y2 == currentY) then
                                zoneTable[i].x2 = adjustedX;
                                zoneTable[i].y2 = adjustedY;
                        end
                end
        end
        MetaMap_MainMapUpdate();
end

function MetaMap_ClearGUI()
        MetaMap_LastLineClick.GUIactive = false;
        MetaMap_Relocate = {};
end

function MetaMap_DrawLine(id, x1, y1, x2, y2)
        assert(x1 and y1 and x2 and y2); -- shows a default error message if false
        local MetaMapNotesLine = MetaMap_CreateLineObject(id);
        local positiveSlopeTexture = METAMAP_IMAGE_PATH.."LineTemplatePositive256";
        local negativeSlopeTexture = METAMAP_IMAGE_PATH.."LineTemplateNegative256";
        local width = WorldMapFrame.ScrollContainer.Child:GetWidth();
        local height = WorldMapFrame.ScrollContainer.Child:GetHeight();
        local deltax = math.abs((x1 - x2) * width);
        local deltay = math.abs((y1 - y2) * height);
--old   local xOffset = math.min(x1,x2) * width;
--old   local yOffset = -(math.min(y1,y2) * height);
        local xOffset1 = math.min(x1,x2) * width;
        local yOffset1 = -(math.min(y1,y2) * height);
        local xOffset2 = math.max(x1,x2) * width;
        local yOffset2 = -(math.max(y1,y2) * height);

        local lowerpixel = math.min(deltax, deltay);
        lowerpixel = lowerpixel / 256;
        if (lowerpixel > 1) then
                lowerpixel = 1;
        end
        if (x1 - x2 == 0) then
                deltax = 2;
                MetaMapNotesLine:SetTexture(0, 0, 0);
                MetaMapNotesLine:SetTexCoord(0, 1, 0, 1);
        elseif (y1 - y2 == 0) then
                deltay = 2;
                MetaMapNotesLine:SetTexture(0, 0, 0);
                MetaMapNotesLine:SetTexCoord(0, 1, 0, 1);
        elseif (x1 - x2 < 0) then
                if (y1 - y2 < 0) then
                        MetaMapNotesLine:SetTexture(negativeSlopeTexture);
                        MetaMapNotesLine:SetTexCoord(0, lowerpixel, 0, lowerpixel);
                else
                        MetaMapNotesLine:SetTexture(positiveSlopeTexture);
                        MetaMapNotesLine:SetTexCoord(0, lowerpixel, 1-lowerpixel, 1);
                end
        else
                if (y1 - y2 < 0) then
                        MetaMapNotesLine:SetTexture(positiveSlopeTexture);
                        MetaMapNotesLine:SetTexCoord(0, lowerpixel, 1-lowerpixel, 1);
                else
                        MetaMapNotesLine:SetTexture(negativeSlopeTexture);
                        MetaMapNotesLine:SetTexCoord(0, lowerpixel, 0, lowerpixel);
                end
        end

        MetaMapNotesLine:SetParent(WorldMapFrame.ScrollContainer.Child);
        MetaMapNotesLine:SetPoint("TOPLEFT", WorldMapFrame.ScrollContainer.Child, "TOPLEFT", xOffset1, yOffset1);
        MetaMapNotesLine:SetPoint("BOTTOMRIGHT", WorldMapFrame.ScrollContainer.Child, "TOPLEFT", xOffset2, yOffset2);

--old   MetaMapNotesLine:SetWidth(deltax);
--old   MetaMapNotesLine:SetHeight(deltay);
        MetaMapNotesLine:Show();
end

function MetaMap_ToggleLine(mapName, x1, y1, x2, y2)
        local newline = true;
        local lineTable = MetaMap_Lines[mapName];
        local lineCount = #(lineTable);

        for i = 1, lineCount, 1 do
                if (i <= lineCount) then
                        if ( (lineTable[i].x1 == x1 and lineTable[i].y1 == y1 and
                              lineTable[i].x2 == x2 and lineTable[i].y2 == y2) or
                             (lineTable[i].x1 == x2 and lineTable[i].y1 == y2 and
                              lineTable[i].x2 == x1 and lineTable[i].y2 == y1) ) then
                                for j = i, lineCount-1, 1 do
                                        lineTable[j].x1 = lineTable[j+1].x1;
                                        lineTable[j].x2 = lineTable[j+1].x2;
                                        lineTable[j].y1 = lineTable[j+1].y1;
                                        lineTable[j].y2 = lineTable[j+1].y2;
                                end
                                lineTable[lineCount] = nil;
                                PlaySound(SOUNDKIT.IG_MAINMENU_OPTION);
                                newline = false;
                                lineCount = lineCount - 1;
                        end
                end
        end
        if (newline) then
                lineTable[lineCount+1] = {};
                lineTable[lineCount+1].x1 = x1;
                lineTable[lineCount+1].x2 = x2;
                lineTable[lineCount+1].y1 = y1;
                lineTable[lineCount+1].y2 = y2;
        end
        MetaMap_LastLineClick.zone = 0;
        MetaMap_MainMapUpdate();
end

function MetaMap_SetPartyNote(xPos, yPos)
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        xPos = floor(xPos * 1000000) / 1000000;
        yPos = floor(yPos * 1000000) / 1000000;
        MetaMap_PartyNoteData.mapName = mapName;
        MetaMap_PartyNoteData.xPos = xPos;
        MetaMap_PartyNoteData.yPos = yPos;
        if (MetaMap_MiniNote_Data.icon == "party" or MetaMapOptions.MiniParty) then
                MetaMap_MiniNote_Data.zonetext = mapName;
                MetaMap_MiniNote_Data.id = -1;
                MetaMap_MiniNote_Data.xPos = xPos;
                MetaMap_MiniNote_Data.yPos = yPos;
                MetaMap_MiniNote_Data.name = METAMAP_PARTYNOTE;
                MetaMap_MiniNote_Data.color = 0;
                MetaMap_MiniNote_Data.icon = "party"
                MetaMap_MiniNoteTexture:SetTexture(METAMAP_ICON_PATH.."Icon"..MetaMap_MiniNote_Data.icon);
                MetaMap_MiniNote:Show();
        end
        MetaMap_MainMapUpdate();
end

function MetaMap_WorldMapButton_OnClick(frame, button)
        MetaMap_Debug_Print("MetaMap_WorldMapButton_OnClick", true);
        if (not MetaMap_FramesHidden()) then return; end

        if (BattlefieldMinimap and BattlefieldMinimap:IsVisible() ) then
                if (not MetaMap_CombatLockdown_BattlefiedMap) then
                        MetaMap_Reshow_BattlefiedMap = time();
                end
                MetaMap_CombatLockdown_BattlefiedMap = nil;
                BattlefieldMinimap:Hide(); --BattlefieldMinimap screws up the map selection
        end

        local mapName = MetaMap_GetCurrentMapInfo();
        if (mapName and MetaMap_Relocate.id) then
                if (button == "LeftButton" and not IsControlKeyDown() and not IsShiftKeyDown()) then
                        MetaMap_MoveNote(MetaMap_Relocate.mapName, MetaMap_Relocate.id);
                        MetaMap_Relocate = {};
                        return;
                end
        end

        if (button == "LeftButton" and (IsControlKeyDown() or IsShiftKeyDown() or IsAltKeyDown())) then
                if (mapName  or MetaMapOptions.ShowDNI) then
                        local centerX, centerY = WorldMapFrame.ScrollContainer:GetCenter();
                        local width = WorldMapFrame.ScrollContainer:GetWidth();
                        local height = WorldMapFrame.ScrollContainer:GetHeight();
                        local x, y = GetCursorPosition();
                        x = x / WorldMapFrame.ScrollContainer:GetEffectiveScale();
                        y = y / WorldMapFrame.ScrollContainer:GetEffectiveScale();

                        if (centerX == nil) then
                                centerX = 0;
                        end
                        if (centerY == nil) then
                                centerY = 0;
                        end

                        local adjustedY = (centerY + height/2 - y) / height;
                        local adjustedX = (x - (centerX - width/2)) / width;

                        if (IsShiftKeyDown()) then
                                MetaMap_SetPartyNote(adjustedX, adjustedY);
                        elseif (IsControlKeyDown()) then
                                local _, _, dataZone = MetaMap_GetCurrentMapInfo();
                                if (dataZone) then MetaMap_EditNewNote(adjustedX, adjustedY); end
                        elseif (IsAltKeyDown() and MetaMap_GetCurrentMapInfo() == MetaMap_GetRealZoneText()) then
                                MetaMap_LoadBWP(0, 3);
                                if (IsAddOnLoaded("MetaMapBWP")) then
                                        BWP_LocCommand(format("%d, %d", 100 * adjustedX, 100 * adjustedY));
                                end
                        end
                end
--      elseif (button == "RightButton" and MetaMapFrame:IsVisible()) then
--              local _, zIndex = MetaMap_GetZoneTableEntry(MetaMapOptions.MetaMapZone);
--              local mapName = MetaMap_ZoneTable[zIndex].Location;
--              MetaMapOptions.MetaMapZone = mapName;
--              MetaMap_ShowInstance(frame, false);
--              SetMapZoom(MetaMap_NameToZoneID(mapName)); 
--
--              MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();
        else
                MetaMap_WorldMapButton_OnClick_old(frame, button);
        end
end

function MetaMap_WorldMapButton_OnUpdate()
        if (not MetaMap_VarsLoaded or MetaMap_Drawing) then return; end
        local lastNote = 0;
        local lastLine = 0;
        local showLine = true;
        local xOffset,yOffset = 0;
        local currentLineZone;
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        MetaMap_Drawing = true;
        if (dataZone) then
                currentLineZone = MetaMap_Lines[mapName];
                if (currentLineZone) then
                        for i, line in ipairs(currentLineZone) do
                                MetaMap_DrawLine(i, line.x1, line.y1, line.x2, line.y2);
                                lastLine = i;
                        end
                end
                for i, value in ipairs(dataZone) do
                        local temp = MetaMap_CreateNoteObject(i);
                        local xPos = dataZone[i].xPos;
                        local yPos = dataZone[i].yPos;
                        local xOffset = xPos * WorldMapFrame.ScrollContainer.Child:GetWidth();
                        local yOffset = -yPos * WorldMapFrame.ScrollContainer.Child:GetHeight();

                        temp:SetParent(WorldMapFrame.ScrollContainer.Child); -- ##### self:GetMap():GetCanvasContainer()
                        temp:SetPoint("CENTER", WorldMapFrame.ScrollContainer.Child, "TOPLEFT", xOffset, yOffset);

                        _G["MetaMapNotesPOI"..i.."Texture"]:SetTexture(METAMAP_ICON_PATH.."Icon"..dataZone[i].icon);
                        _G["MetaMapNotesPOI"..i.."Highlight"]:Hide();
--[[old
                        for landmarkIndex = 1, GetNumMapLandmarks(), 1 do
                                local worldMapPOI = _G["WorldMapFramePOI"..landmarkIndex];
                                if (worldMapPOI == nil) then break; end
                                local metaMapPOI = _G["MetaMapNotesPOI"..i];
                                local name, unknown, textureIndex, x, y = GetMapLandmarkInfo(landmarkIndex);
                                local xPosmin = xPos - 2; local xPosmax = xPos + 2;
                                local yPosmin = yPos - 2; local yPosmax = yPos + 2;
                                if(x~=nil and y ~=nil and (x > xPosmin and x < xPosmax) and (y > yPosmin and y < yPosmax)) then
                                        metaMapPOI:SetFrameLevel(WorldMapFrame.ScrollContainer.Child:GetFrameLevel() + 1);
                                end
                        end
--]]

                        if (dataZone[i].icon == 10) then
                                if (dataZone[i].name == MetaMap_FilterName) then
                                        temp:Hide();
                                        showLine = false;
                                else
                                        temp:Show();
                                end
                        elseif (MetaMap_NoteFilter[dataZone[i].icon] and (dataZone[i].mLevel == nil or dataZone[i].mLevel == MetaMap_GetCurrentMapDungeonLevel())) then
                                temp:Show();
                        else
                                MetaMap_FilterName = dataZone[i].name;
                                temp:Hide();
                                showLine = false;
                        end
                        if (not showLine) then
                                for line = 1, lastLine, 1 do
                                        if (currentLineZone[line].x1 == xPos and currentLineZone[line].y1 == yPos) then
                                                _G["MetaMapNotesLines_"..line]:Hide();
                                        elseif (currentLineZone[line].x2 == xPos and currentLineZone[line].y2 == yPos) then
                                                _G["MetaMapNotesLines_"..line]:Hide();
                                        end
                                end
                        end

                        lastNote = i;
                end
                if (MetaMapOptions.LastHighlight and lastNote ~= 0 and dataZone[lastNote].icon ~= 10) then
                        if (_G["MetaMapNotesPOI"..lastNote]:IsVisible()) then
                                _G["MetaMapNotesPOI"..lastNote.."Highlight"]:SetTexture(METAMAP_ICON_PATH.."IconGlowRed");
                                _G["MetaMapNotesPOI"..lastNote.."Highlight"]:Show();
                        end
                end
                if (MetaMapOptions.LastMiniHighlight and MetaMap_MiniNote_Data.zonetext == mapName and MetaMap_MiniNote_Data.id > 0) then
                        _G["MetaMapNotesPOI"..MetaMap_MiniNote_Data.id.."Highlight"]:SetTexture(METAMAP_ICON_PATH.."IconGlowBlue");
                        _G["MetaMapNotesPOI"..MetaMap_MiniNote_Data.id.."Highlight"]:Show();
                end
                for i = lastNote + 1, MetaMap_LastNote, 1 do
                        _G["MetaMapNotesPOI"..i]:Hide();
                end
                for i = lastLine + 1, MetaMap_LastLine, 1 do
                        _G["MetaMapNotesLines_"..i]:Hide();
                end
        else
                for i = 1, MetaMap_LastNote, 1 do
                        _G["MetaMapNotesPOI"..i]:Hide();
                end

                for i = 1, MetaMap_LastLine, 1 do
                        _G["MetaMapNotesLines_"..i]:Hide();
                end
        end

        if (dataZone) then
                -- vNote button
                if (mapName and MetaMap_vnote_xPos ~= nil) then
                        xOffset = MetaMap_vnote_xPos * WorldMapFrame.ScrollContainer.Child:GetWidth();
                        yOffset = -MetaMap_vnote_yPos * WorldMapFrame.ScrollContainer.Child:GetHeight();
                        MetaMapNotesPOIvNote:SetPoint("CENTER", WorldMapFrame.ScrollContainer.Child, "TOPLEFT", xOffset, yOffset);
                        
                        MetaMapNotesPOIvNote:Show();
                else
                        MetaMapNotesPOIvNote:Hide();
                end

                -- party note
                if (MetaMap_PartyNoteData.xPos ~= nil and mapName == MetaMap_PartyNoteData.mapName) then
                        if (MetaMapOptions.LastMiniHighlight and MetaMap_MiniNote_Data.icon == "party") then
                                MetaMapNotesPOIpartyTexture:SetTexture(METAMAP_ICON_PATH.."Iconpartyblue");
                        else
                                MetaMapNotesPOIpartyTexture:SetTexture(METAMAP_ICON_PATH.."Iconparty");
                        end
                        xOffset = MetaMap_PartyNoteData.xPos * WorldMapFrame.ScrollContainer.Child:GetWidth();
                        yOffset = -MetaMap_PartyNoteData.yPos * WorldMapFrame.ScrollContainer.Child:GetHeight();
                        MetaMapNotesPOIparty:SetParent(WorldMapFrame.ScrollContainer.Child);
                        MetaMapNotesPOIparty:SetPoint("CENTER", WorldMapFrame.ScrollContainer.Child, "TOPLEFT", xOffset, yOffset);
                        
                        MetaMapNotesPOIparty:Show();
                else
                        MetaMapNotesPOIparty:Hide();
                end
        end
        MetaMap_Drawing = nil;
        MetaMapText_NoteTotals:SetText("|cff00ff00"..METAMAP_NOTES_SHOWN..": ".."|cffffffff"..(lastNote).."  ".."|cff00ff00"..METAMAP_LINES_SHOWN..": ".."|cffffffff"..(lastLine));
        MetaMapText_NoteTotals:Show();
        MetaMapList_Init();
        MetaMap_FilterName = "";
        if (IsAddOnLoaded("MetaMapTRK")) then
                TRK_DisplayNodes(mapName, MetaMap_GetCurrentMapDungeonLevel());
        end
end

function MetaMap_CheckLinks(id)
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        local name = dataZone[id].name;
        local count = 0;
        for i = 1, 4, 1 do
                if (dataZone[id+i] ~= nil and dataZone[id+i].name == name and dataZone[id+i].icon == 10) then
                        count = count +1;
                end
        end
        for i = 1, count + 1, 1 do
                MetaMap_DeleteMapNote(id, mapName);
        end
end

function MetaMap_DeleteLines(mapName, x, y)
        if (not x or not y) then return; end
        local lineTable = MetaMap_Lines[mapName];
        local lineCount = #(lineTable);
        local offset = 0;
        for i = 1, lineCount, 1 do
                if ( (lineTable[i-offset].x1 == x and lineTable[i-offset].y1 == y) or (lineTable[i-offset].x2 == x and lineTable[i-offset].y2 == y) ) then
                        for j = i, lineCount-1, 1 do
                                lineTable[j-offset].x1 = lineTable[j+1-offset].x1;
                                lineTable[j-offset].x2 = lineTable[j+1-offset].x2;
                                lineTable[j-offset].y1 = lineTable[j+1-offset].y1;
                                lineTable[j-offset].y2 = lineTable[j+1-offset].y2;
                        end
                        lineTable[lineCount-offset] = nil;
                        offset = offset + 1;
                end
        end
        MetaMap_LastLineClick.zone = 0;
end

function MetaMapPOI_OnEvent(mode)
--old   if (GetCurrentMapZone() == 0) then return; end
        local mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
        local noteAdded1, noteAdded2;
        local name, unknown, textureIndex, x, y;
        local icon = 7; --was 8
        for landmarkIndex = 1, GetNumMapLandmarks(), 1 do
                name, unknown, textureIndex, x, y = GetMapLandmarkInfo(landmarkIndex);
                if (textureIndex == 15) then
                        icon = 7; --was 5
                elseif (textureIndex == 6) then
                        icon = 6;
                end
                if (mode == 1) then
                        if (textureIndex==6) then
                                noteAdded1 = MetaMap_AddNewNote(mapName, x, y, name, "", "", METAMAPPOI_NAME, icon, 6, 0, 0,nil,MetaMap_GetCurrentMapDungeonLevel());
                        end
                else
                        noteAdded2 = MetaMap_AddNewNote(mapName, x, y, name, "", "", METAMAPPOI_NAME, icon, 6, 0, 0,nil,MetaMap_GetCurrentMapDungeonLevel());
                end
        end
        if (noteAdded1 and noteAdded2) then
                MetaMap_Print("MetaMapPOI updated map notes for "..MetaMap_GetRealZoneText(), true);
        else
                if (noteAdded2) then
                        MetaMap_Print("MetaMapPOI updated map notes for "..MetaMap_GetRealZoneText(), true);
                end
                if (noteAdded1) then
                        MetaMap_Print("MetaMapPOI set Guard note for "..name, true);
                end
        end
end

function MetaMap_InvertList(list)
        local newlist = {};
        local count = #(list);
        for i = 1, count do
                table.insert(newlist, list[(count + 1) - i]);
        end
        return newlist;
end

function MetaMap_InfoLine(button)
        MetaMap_Debug_Print("MetaMap_InfoLine"..button,true);
        if (button == "RightButton") then
                MetaMapOptions.ShowMapList = not MetaMapOptions.ShowMapList;
                MetaMapOptions_Init();
                MetaMapList_Init();
                return;
        end

        if (MetaMap_InfoLineFrame:IsVisible()) then
                MetaMapContainer_ShowFrame();
                return;
        end
        MetaMap_InfoLineUpdate();
end

function MetaMap_InfoLineUpdate()
        local header = "";
        local zName, zIndex, zType = MetaMap_GetZoneTableEntry(MetaMap_GetCurrentMapInfo());
        if (zType == "RDI" or zType == "DNI" or zType == "SCN") then
                local zoneTable = MetaMap_ZoneTable[zIndex];
                header = METAMAP_STRING_LOCATION..": ".."|cffffffff"..zoneTable.Location.."|r";
                header = header.."   "..METAMAP_STRING_LEVELRANGE..": ".."|cffffffff"..zoneTable.LevelRange.."|r";
                header = header.."   "..METAMAP_STRING_PLAYERLIMIT..": ".."|cffffffff"..zoneTable.PlayerLimit.."|r";
                MetaMap_InfoLineFrameText:SetText(zoneTable.infoline);
        else
                header = "|cffffffff"..MetaMap_GetCurrentMapInfo().."|r";
                MetaMap_InfoLineFrameText:SetText(METAMAP_FURINF);
        end
        MetaMapContainer_ShowFrame(MetaMap_InfoLineFrame, header);
end

function MetaMap_InfoLineOnEnter(self)
        MetaMap_SetTTInfoLine(MetaMap_GetCurrentMapInfo(), self, WorldMapTooltip);
        WorldMapTooltip:AddLine(METAMAP_INFOLINE_HINT1, 0.75, 0, 0.75, false);
        WorldMapTooltip:AddLine(METAMAP_INFOLINE_HINT2, 0.75, 0, 0.75, false);
        WorldMapTooltip:AddLine(" ");
        WorldMapTooltip:AddLine(METAMAP_INFOLINE_HINT3, 0.40, 0.40, 0.40, false);
        WorldMapTooltip:AddLine(METAMAP_INFOLINE_HINT4, 0.40, 0.40, 0.40, false);

--old   WorldMapPOIFrame.allowBlobTooltip = false;
        WorldMapTooltip:Show();
        --WorldMapTooltip:SetFrameLevel(WorldMapFrame:GetFrameLevel() + 20);
end

function MetaMap_SetTTInfoLine(zoneName, Button, Tooltip)
        local zName, zIndex, zType = MetaMap_GetZoneTableEntry(zoneName);
        Tooltip:SetOwner(Button, "ANCHOR_BOTTOMLEFT");
        if (zType == "RDI" or zType == "DNI" or zType == "SCN") then
                local zoneTable = MetaMap_ZoneTable[zIndex];
                Tooltip:SetText(zName, 1, 1, 0, false);
                Tooltip:AddLine(METAMAP_STRING_LOCATION..": ".."|cffffffff"..zoneTable.Location, 1, 1, 0, false);
                Tooltip:AddLine(METAMAP_STRING_LEVELRANGE..": ".."|cffffffff"..zoneTable.LevelRange, 1, 1, 0, false);
                Tooltip:AddLine(METAMAP_STRING_PLAYERLIMIT..": ".."|cffffffff"..zoneTable.PlayerLimit, 1, 1, 0, false);
                Tooltip:AddLine(" ");
                Tooltip:AddDoubleLine(METAMAP_SEVEDINSTANCES, "ID:");
                if (GetNumSavedInstances() > 0) then
                        for i = 1, GetNumSavedInstances() do
                                local name, ID, remaining = GetSavedInstanceInfo(i);
                                remaining = SecondsToTime(remaining);
                                Tooltip:AddDoubleLine(name, "|cffffffff"..ID, 0, 1, 0, false);
                                Tooltip:AddLine("|cffffffff"..remaining);
                        end
                else
                        Tooltip:AddLine(METAMAP_NO_SAVED_INSTANCES);
                end
        elseif (zType == "SZ" or zType == "MSZ" or zType == "SZR" or zType == "BG") then
                local zoneTable = MetaMap_ZoneTable[zIndex];
                local fColor = {}; local lColor = {};
                local Neutral = { r = 0.9, g = 0.8, b = 0.2 };
                local Friendly = { r = 0.2, g = 0.9, b = 0.2 };
                local Hostile = { r = 0.9, g = 0.2, b = 0.2 };
                local Contested = { r = 0.8, g = 0.6, b = 0.4 };
                local player_faction = UnitFactionGroup("player");
                local faction = zoneTable.faction;
                if (faction == "Contested") then
                        fColor = Contested;                             
                elseif (faction == "Neutral") then
                        fColor = Neutral;
                elseif (faction == player_faction) then
                        fColor = Friendly;
                else
                        fColor = Hostile;
                end
                if (UnitLevel("player") > zoneTable.hlvl) then
                        lColor = { r = 0.5, g = 0.5, b = 0.5 };                         
                elseif (UnitLevel("player") < zoneTable.llvl) then
                        lColor = Hostile;
                else
                        lColor = Friendly;
                end
                local faction_lc;
                if (faction == "Contested") then faction_lc = METAMAP_FACTION_CONTESTED; end
                if (faction == "Neutral") then faction_lc = METAMAP_FACTION_NEUTRAL; end
                if (faction == "Alliance") then faction_lc = FACTION_ALLIANCE; end
                if (faction == "Horde") then faction_lc = FACTION_HORDE; end
                Tooltip:AddDoubleLine(zName, faction_lc, fColor.r, fColor.g, fColor.b, fColor.r, fColor.g, fColor.b, false);
                Tooltip:AddDoubleLine(METAMAP_STRING_LEVELRANGE, zoneTable.llvl.." - "..zoneTable.hlvl, 1, 1, 0, lColor.r, lColor.g, lColor.b, false);
        else
                Tooltip:SetText(zoneName, 1, 1, 1, false);
        end
        Tooltip:AddLine(" ");

        Tooltip:Show();
end

function MetaMap_ColorSelect(self)
        local R, G, B = unpack(self.color);
        ColorPickerFrame.func = MetaMap_SetColor;
        ColorPickerFrame.cancelFunc = MetaMap_CancelColor;
        ColorPickerFrame.func2 = self.func;
        ColorPickerFrame.option = self.option;
        ColorPickerFrame.previousValues = {R, G, B};
        ColorPickerFrame:SetFrameStrata("FULLSCREEN");
        ColorPickerFrame:Show();
        ColorPickerFrame:SetColorRGB(R, G, B);
end

function MetaMap_SetColor()
        local R, G, B = ColorPickerFrame:GetColorRGB();
        ColorPickerFrame.func2(ColorPickerFrame.option, R, G, B);
end

function MetaMap_CancelColor(prevColors)
        local R, G, B = unpack(prevColors);
        ColorPickerFrame.func2(ColorPickerFrame.option, R, G, B);
end

function MetaMap_ContextHelp(title)
        if (not MetaMap_DialogFrame:IsVisible()) then
                MetaMapExtOptions_Toggle();
        end
        PanelTemplates_SetTab(MetaMap_DialogFrame, 6);
        if (MetaMap_LoadHLP()) then
                MetaMap_ToggleDialog("MetaMap_HelpDialog");
                HLP_DisplayOption(HLP_HelpData.Modules[title], 2, title);
                UIDropDownMenu_SetText(HLP_MenuSelect, title);
        end
end

function MetaMap_DevTools()
        if (not IsAddOnLoaded("MetaMapXTM")) then
                LoadAddOn("MetaMapXTM");
        end
        if (IsAddOnLoaded("MetaMapXTM")) then
                XTM_MenuSelect();
        end
end

----------------
-- FuBar Support
----------------
function MetaMap_FuBar_OnLoad()
        if (AceLibrary("AceAddon-2.0") == nil) then return; end
        MetaMapFu = AceLibrary("AceAddon-2.0"):new("FuBarPlugin-2.0");
        MetaMapFu.hasIcon = METAMAP_ICON;
        MetaMapFu.name = METAMAP_TITLE;
        MetaMapFu.version = METAMAP_VERSION;
        MetaMapFu.description = METAMAP_DESC;
        MetaMapFu.category = "Map";
        MetaMapFu.hasNoText = true;
        MetaMapFu.description = METAMAP_DESC;

        function MetaMapFu:OnInitialize()
                if (FuBar2DB.profiles.Default.detached.MetaMap) then
                        MetaMapFu.hideWithoutStandby = true;
                end
        end

        function MetaMapFu:OnClick()
                if (IsControlKeyDown()) then
                        MetaMap_DevTools();
                else
                        MetaMap_ToggleFrame(WorldMapFrame);
                end
        end

        function MetaMapFu:OnTooltipUpdate()
                GameTooltip:Hide();
                MetaMap_MainMenuSelect("FuBarPluginMetaMapFrame");
        end
end

----------------
-- Titan Support
----------------
function MetaMap_TitanPanelButton_OnLoad(self)
        self.registry = { 
                id = METAMAP_TITAN_ID,
                version = METAMAP_VERSION,
                menuText = METAMAP_TITLE,
                category = METAMAP_CATEGORY,
                tooltipTitle = METAMAP_TITLE ,
                tooltipTextFunction = "MetaMap_TitanPanelButton_GetTooltipText",
                frequency = METAMAP_TITAN_FREQUENCY, 
                icon = METAMAP_ICON,
                iconWidth = 16,
                savedVariables = {
                ShowIcon = 1,
                }
        };
end

function MetaMap_TitanPanelButton_GetTooltipText()
        if (MetaMapOptions.MenuMode) then
                retText = METAMAP_BUTTON_TOOLTIP1.."\n"..METAMAP_BUTTON_TOOLTIP2;
                return retText;
        end
end

function MetaMap_TitanPanelButton_OnClick(button)
        if ( button == "LeftButton" ) then
                MetaMap_ToggleFrame(WorldMapFrame);
        end
end

-----------
-- FlightMap
-----------
function MetaMap_FlightMapOptions_Toggle()
        FlightMapOptionsFrame:SetFrameStrata("FULLSCREEN");
        MetaMap_ToggleFrame(FlightMapOptionsFrame);
end

------------------------------------------------------------
--- The following functions are available for external calls
--- It is global so, simply CALL the function.
--- No need for hooking, unless stated otherwise. :)
------------------------------------------------------------
function MetaMap_SetNewNote(mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c, mininote, mLevel)
        local noteAdded, noteID = MetaMap_AddNewNote(mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c, mininote, mLevel);
        return noteAdded, noteID;
--Note accepted: noteAdded is returned as true, noteID  returns the NEW note index number.
--              Note rejected: noteAdded is returned as false, noteID returns the NEAR note index number.
--              The optional [mininote] parameter sets a Mininote as follows:
--              0 - Sets Mapnote only
--              1 - Sets Mapnote + Mininote
--              2 - Sets Mininote only
--              Nil or any other value defaults to value 0
end

function MetaMap_SetMiniNote(id, mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c)
        MetaMap_AddMiniNote(id, mapName, xPos, yPos, name, inf1, inf2, creator, icon, ncol, in1c, in2c);
end

function MetaMap_RemoveMapNote(id, mapName)
        MetaMap_DeleteMapNote(id, mapName);
end

function MetaMap_KBMenu_RBSelect(id)
        -- Initiated when RightClicking on KB display item.
        -- Slot assigned to MetaMapBWP.
end

function MetaMap_KBMenu_CRBSelect(id)
        -- Available for other mods to run their own routine.
        -- Initiated when CTRL+RightClicking on KB display item.
        -- Usage: MetaMap_KBMenu_CRBSelect = MyFunction
end

function MetaMap_KBMenu_SRBSelect(id)
        -- Available for other mods to run their own routine.
        -- Initiated when Shift+RightClicking on KB display item.
        -- Usage: MetaMap_KBMenu_SRBSelect = MyFunction
end

function MetaMapNotes_RBSelect(id)
        -- Initiated when RightClicking on a map note.
        -- Slot assigned to MetaMapBWP.
end

function MetaMapNotes_CRBSelect(id)
        -- Available for other mods to run their own routine.
        -- Initiated when CTRL+RightClicking on a map note.
        -- Usage: MetaMapNotes_CRBSelect = MyFunction
end

function MetaMapNotes_SRBSelect(id)
        -- Available for other mods to run their own routine.
        -- Initiated when Shift+RightClicking on a map note.
        -- Usage: MetaMapNotes_SRBSelect = MyFunction
end

-- manual fix for re-positioning of Stormwind City notes
-- ONLY EXECUTE THE FOLLOWING SLASH COMMAND IF YOU NEED -ALL- OF YOUR STORMWIND CITY NOTES ADJUSTING
-- Your Stormwind City note positions will be scaled and shifted to account for the new city map
-- This function for Stormwind map adjustments was borrowed from MapNotes
function MetaMapStormwindFix(again)
        if (again and again ~= "again") then again = nil; end
        if (not again and MetaMap_Notes and MetaMap_Notes.StormwindFixed) then
                MetaMap_Print(" The Stormwind City map notes were previously adjusted.", 1);
                MetaMap_Print(" If you are absolutely sure of what you are doing, you can force the adjustment again by typing"..
                        " \'/script MetaMapStormwindFix(\"again\")\'", 1);      
                return;
        end
        local x, y;
        local moved = 0;
        if (MetaMap_Notes == nil) then MetaMap_Notes = {}; end
        for i, n in pairs(MetaMap_Notes["Stormwind City"]) do
                x = n.xPos * 0.76 + 0.203;
                if ( x > 0.9999 ) then x = 0.9999; end
                y = n.yPos * 0.76 + 0.253;
                if ( y > 0.9999 ) then y = 0.9999; end
                n.xPos = x;
                n.yPos = y;
                moved = moved + 1;
        end
        MetaMap_Print(moved.." Stormwind City map notes were adjusted.", 1); -- msg, display, r, g, b
        MetaMap_Notes.StormwindFixed = nil; --removed due to it causeing MetaMapEXP errors
end

function MetaMapStormwindUnfix(again)
        if (again and again ~= "again") then again = nil; end
        if (not again and MetaMap_Notes and MetaMap_Notes.StormwindFixed) then
                MetaMap_Print(" The Stormwind City map notes were previously un-adjusted.", 1);
                MetaMap_Print(" If you are absolutely sure of what you are doing, you can force the un-adjustment again by typing"..
                        " \'/script MetaMapStormwindunfix(\"again\")\'", 1);    
                return;
        end
        local x, y;
        local moved = 0;
        if (MetaMap_Notes == nil) then MetaMap_Notes = {}; end
        for i, n in pairs(MetaMap_Notes["Stormwind City"]) do
                x = (n.xPos - 0.203 ) / 0.76;
                if ( x > 0.9999 ) then x = 0.9999; end
                y = (n.yPos - 0.253) / 0.76;
                if ( y > 0.9999 ) then y = 0.9999; end
                n.xPos = x;     n.yPos = y;
                moved = moved + 1;
        end
        MetaMap_Print(moved.." Stormwind City map notes were un-adjusted.", 1); -- msg, display, r, g, b
        MetaMap_Notes.StormwindFixed = nil; --removed due to it causeing MetaMapEXP errors
end

-- move list frame to stay inside the screen
function MetaMap_ToggleDropDownMenu()
        local listFrame2 = _G["DropDownList2"];
        local listFrame3 = _G["DropDownList3"];
        local shown2 = listFrame2:IsShown();
        local shown3 = false;
        if (listFrame3 and listFrame3:IsShown()) then shown3 = true; end
        if ( WorldMapFrame:IsVisible() and shown2 and not shown3 ) then
                local top = listFrame2:GetTop();
                local shift = top - GetScreenHeight();
                if (shift > 0) then
                        local point, relativeTo, relativePoint, xOffset, yOffset = listFrame2:GetPoint(1);
                        listFrame2:ClearAllPoints();
                        listFrame2:SetPoint(point, relativeTo, relativePoint, xOffset, yOffset - shift);
                end
        end
end

-- link pre-instances (like BlackRock, Maraudon) to maps (normally the continent map is shown)
function MetaMap_SetMapToCurrentZone(self, mapReset)
        MetaMap_Debug_Print("MetaMap_SetMapToCurrentZone", true);
        if ( not mapReset ) then
                MataMapMainMenu_Visible = false;
                MetaMap_StayOnMap = false;
                MetaMap_MapClick = false;
        end
--old   SetMapToCurrentZone();
        local realID = C_Map.GetBestMapForUnit("player");
        if ( not realID ) then return; end
        WorldMapFrame:SetMapID(realID);

        local realZone = GetRealZoneText();
--old   local _, _, _, isMicroDungeon = GetMapInfo();
        if (realZone) then
                local _, index, type = MetaMap_GetZoneTableEntry(realZone, realID);
--old           if ( index and (type == "SZR") and not isMicroDungeon ) then
                if ( index and (type == "SZR") ) then
                        local mapName = MetaMap_ZoneTable[index]["Location"];
                        if (mapName) then
                                if (MetaMapOptions.MetaMapZone) then MetaMapOptions.MetaMapZone = mapName; end
                                local _, _, _, mapid = MetaMap_GetZoneTableEntry(mapName);
                                if ( mapid ~= 0 ) then
                                        MetaMap_Debug_Print("SetMapByID",true);
--old                                   SetMapByID(mapid);
                                        WorldMapFrame:SetMapID(mapid);
                                        --SetDungeonMapLevel(0);
                                else
                                        MetaMap_Debug_Print("SetMapZoom",true);
--                                      SetMapZoom(MetaMap_NameToZoneID(mapName));
--old                                   MetaMap_SetMapZoomByName(mapName);
                                        WorldMapFrame:SetMapID(MetaMap_NameToZoneID(zoneName));
                                end
                        end
                end

                for _, zoneTable in pairs(MetaMap_ZoneTable) do
                        if (zoneTable[MetaMap_Locale] == realZone) then
--old                           if ( not zoneTable.mapid or (zoneTable.mapid == WorldMapFrame:GetMapID() and not isMicroDungeon) ) then
                                if ( not zoneTable.mapid or (zoneTable.mapid == MetaMap_UiMapID_AreaID[WorldMapFrame:GetMapID()].AreaID) ) then
                                        if (zoneTable.ztype == "SZR") then
                                                realZone = zoneTable.Location;
                                        else
                                                realZone = MetaMap_MergeZoneName(zoneTable);
                                        end
                                end
                        end
                end
                MetaMap_BaseMap.Name = realZone;
        else
                MetaMap_BaseMap.Name = nil;
                MetaMapOptions.MetaMapLevel = 0;
                MetaMapOptions.oldScrollH = 0;
                MetaMapOptions.oldScrollV = 0;
                MetaMapOptions.oldScale = WorldFrame:GetScale();
        end

        MetaMap_BaseMap.ID = WorldMapFrame:GetMapID();
        MetaMap_BaseMap.Level = MetaMap_GetCurrentMapDungeonLevel();

        if ( not MetaMapOptions.MapChange and WorldMapFrame:IsVisible() and mapReset and self and not MetaMap_CurrentMap.Micro ) then
                MetaMap_SetMapAfterRefresh(self);
        else
                if ( isMicroDungeon ) then
                        MetaMapOptions.MetaMapZone = GetRealZoneText();
                        MetaMapOptions.MetaMapLevel = MetaMap_GetCurrentMapDungeonLevel();
                else
                        MetaMapOptions.MetaMapZone = MetaMap_GetRealZoneText();
                        MetaMapOptions.MetaMapLevel = 0;
                end
                MetaMapOptions.oldScrollH = 0;
                MetaMapOptions.oldScrollV = 0;
                MetaMapOptions.oldScale = WorldFrame:GetScale();
                MetaMapOptions.ShowDNI = true;
                MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();

                local _, _, zType = MetaMap_GetZoneTableEntry(MetaMap_GetRealZoneText());
                if (zType == "RDI" or zType == "DNI" or zType == "BG" or zType == "SCN") then
                        MetaMap_ShowInstance(self, true, true);
                else
                        MetaMap_ShowInstance(self, false, true);
                end
        end
        MetaMap_OldMap = MetaMap_CurrentMap;
        MetaMap_NoOldMap = false;
end

function MetaMap_SaveCurrentMapData(resetScale)
        if (not WorldMapFrame:IsVisible()) then return {}; end

        local mapName = MetaMap_GetCurrentMapInfo();
        local currentMap = {};
        if (mapName) then
                currentMap.Name = mapName;
                currentMap.ID   = WorldMapFrame:GetMapID();
                -- check for dungeon map of cosmos
                if ( (currentMap.ID == -1) and (mapName ~= "The Cosmos") ) then
                        currentMap.Name = "The Cosmos";
                end
--old           currentMap.CID   = GetCurrentMapContinent();
                currentMap.CID   = C_Map.GetWorldPosFromMapPos(currentMap.ID, C_Map.GetPlayerMapPosition(C_Map.GetBestMapForUnit("player"), "player"));
--old           currentMap.ZID   = GetCurrentMapZone();
                currentMap.ZID   = 1;
                currentMap.Level = MetaMap_GetCurrentMapDungeonLevel();
--old           local _, _, _, isMicroDungeon = GetMapInfo();
--old           currentMap.Micro = isMicroDungeon;
                if ( resetScale ) then
                        currentMap.oldScale   = MetaMap_WorldMap_baseScale;
                        currentMap.oldScrollH = 0;
                        currentMap.oldScrollV = 0;
                else
                        currentMap.oldScale   = MetaMap_oldScale;
                        currentMap.oldScrollH = MetaMap_oldScrollH;
                        currentMap.oldScrollV = MetaMap_oldScrollV;
                end
                MetaMap_Debug_Print("CurrentMap = "..mapName.." (mapid "..currentMap.ID..") level "..currentMap.Level, true);
                return currentMap;
        end
        return {};
end

function MetaMap_CopyMapData(inData)
        if ( not inData or not next(inData) ) then return {}; end

        local outData = {};
        if ( inData.Name )       then outData.Name       = inData.Name;       end
        if ( inData.ID )         then outData.ID         = inData.ID;         end
        if ( inData.CID )        then outData.CID        = inData.CID;        end
        if ( inData.ZID )        then outData.ZID        = inData.ZID;        end
        if ( inData.Level )      then outData.Level      = inData.Level;      end
        if ( inData.Micro )      then outData.Micro      = inData.Micro;      end
        if ( inData.oldScale )   then outData.oldScale   = inData.oldScale;   end
        if ( inData.oldScrollH ) then outData.oldScrollH = inData.oldScrollH; end
        if ( inData.oldScrollV ) then outData.oldScrollV = inData.oldScrollV; end

        return outData;
end

-- re-show map displayed before a map refresh
function MetaMap_SetMapAfterRefresh(self)
        MetaMap_Debug_Print("MetaMap_SetMapAfterRefresh", true);
        if (MetaMapOptions.MapChange) then return {}; end
        if (not WorldMapFrame:IsVisible()) then return {}; end
        if (not MetaMap_CurrentMap.Name or not MetaMap_CurrentMap.ID) then return {}; end
        local mapID = WorldMapFrame:GetMapID();
        local mapLevel = MetaMap_GetCurrentMapDungeonLevel();
        if (mapID == MetaMap_CurrentMap.ID and mapLevel == MetaMap_CurrentMap.Level) then return {}; end

        local _, _, zType = MetaMap_GetZoneTableEntry(MetaMap_CurrentMap.Name);
        local mapName = MetaMap_GetCurrentMapInfo();
        if (zType == "DN" and mapName and mapName == MetaMap_CurrentMap.Name) then return {}; end

        local savedMap = MetaMap_SaveCurrentMapData(true);

        if ( mapName ) then MetaMap_Debug_Print("Set map to: "..MetaMap_CurrentMap.Name.." (mapid "..MetaMap_CurrentMap.ID..") level "..MetaMap_CurrentMap.Level, true); end
        local cKey, zKey = MetaMap_NameToZoneID(MetaMap_CurrentMap.Name);
        if (cKey == -1 and (type(zKey) ~= "number" or zKey ~= 0)) then
                local valid = true;
                if (type(zKey) ~= "number") then
                        -- check that instance name is valid
                        valid = MetaMap_CheckValidZone(MetaMap_CurrentMap.Name);
                end
                if (valid) then
                        MetaMapOptions.MetaMapZone = MetaMap_CurrentMap.Name;
                        MetaMapOptions.MetaMapLevel = MetaMap_CurrentMap.Level;
                        MetaMapOptions.oldScrollH = MetaMap_CurrentMap.oldScrollH;
                        MetaMapOptions.oldScrollV = MetaMap_CurrentMap.oldScrollV;
                        MetaMapOptions.oldScale = MetaMap_CurrentMap.oldScale;
                        MetaMap_ShowInstance(self, true);
                        return savedMap;
                else
                        MetaMap_CurrentMap = MetaMap_SaveCurrentMapData();
                end
        else
                if (MetaMap_CurrentMap.ZID == 0) then
                        -- continent maps need to set with SetMapZoom, else (with SetMapByID) area buttons don't work
                        SetMapZoom(MetaMap_CurrentMap.CID, 0);
                else
                        SetMapByID(MetaMap_CurrentMap.ID);
                end
                if (MetaMap_CurrentMap.Level ~= 0) then SetDungeonMapLevel(MetaMap_CurrentMap.Level); end
                WorldMapDetailFrame:SetScale(MetaMap_CurrentMap.oldScale);
                WorldMapScrollFrame:SetHorizontalScroll(MetaMap_CurrentMap.oldScrollH);
                WorldMapScrollFrame:SetVerticalScroll(MetaMap_CurrentMap.oldScrollV);
                return savedMap;
        end
        return {};
end

--[[ note
continent, zone = MetaMap_NameToZoneID(zoneText)
Returns continent and zone IDs.

mapName, mapLevel, dataZone = MetaMap_GetCurrentMapInfo();
mapName returns currently displayed map.
dataZone returns 'MetaMap_Notes[mapNameIndex]'

There is also a 'Container' frame available for displaying data etc, within the WorldMap,
in the same format as the MetaMapWKB, and MetaMapQST displays.
Referenced and parented as 'MetaMapContainerFrame'.
]]

Compare with Previous | Blame