ZoneTrack = {}
ZoneTrackSaved = {
	TrackQuests = 1,
	TrackAchievement = 1
}

local VarsLoaded

local ZoneAchievement = {
	Alliance = {
		arathihighlands = 4896,
		badlands = 4900,
		blastedlands = 4909,
		burningsteppes = 4901,
		capeofstranglethorn = 4905,
		easternplaguelands = 4892,
		hinterlands = 4897,
		lochmodan = 4899,
		wetlands = 4899,
		northernstranglethorn = 4906,
		redridgemountains = 4902,
		searinggorge = 4910,
		swampofsorrows = 4904,
		westernplaguelands = 4893,
		westfall = 4903,
		duskwood = 4903,
		ashenvale = 4925,
		bloodmystisle = 4926,
		darkshore = 4928,
		desolace = 4930,
		dustwallowmarsh = 4929,
		felwood = 4931,
		feralas = 4932,
		silithus = 4934,
		stonetalonmountains = 4936,
		southernbarrens = 4937,
		tanaris = 4935,
		thousandneedles = 4938,
		ungorocrater = 4939,
		winterspring = 4940,
		hellfirepeninsula = 1189,
		zangarmarsh = 1190,
		terokkarforest = 1191,
		nagrand = 1192,
		bladesedgemountains = 1193,
		netherstorm = 1194,
		shadowmoonvalley = 1195,
		grizzlyhills = 37,
		boreantundra = 33,
		howlingfjord = 34,
		dragonblight = 35,
		zuldrak = 36,
		sholazarbasin = 39,
		stormpeaks = 38,
		icecrown = 40,
		uldum = 4872,
		deepholm = 4871,
		tolbarad = 4874,
		tolbaradpeninsula = 4874,
		mounthyjal = 4870,
		vashjir = 4869,
		twilighthighlands = 4873,
		jadeforest = 6300,
		valleyofthefourwinds = 6301,
		krasarangwilds = 6535,
		kunlaisummit = 6537,
		townlongsteppes = 6539,
		dreadwastes = 6540
	},
	Horde = {
		arathihighlands = 4896,
		badlands = 4900,
		blastedlands = 4909,
		burningsteppes = 4901,
		capeofstranglethorn = 4905,
		easternplaguelands = 4892,
		ghostlands = 4908,
		hillsbradfoothills = 4895,
		hinterlands = 4897,
		northernstranglethorn = 4906,
		searinggorge = 4910,
		silverpineforest = 4894,
		swampofsorrows = 4904,
		westernplaguelands = 4893,
		ashenvale = 4976,
		azshara = 4927,
		desolace = 4930,
		dustwallowmarsh = 4978,
		felwood = 4931,
		feralas = 4979,
		northernbarrens = 4933,
		silithus = 4934,
		stonetalonmountains = 4980,
		southernbarrens = 4981,
		tanaris = 4935,
		thousandneedles = 4938,
		ungorocrater = 4939,
		winterspring = 4940,
		hellfirepeninsula = 1271,
		zangarmarsh = 1190,
		terokkarforest = 1272,
		nagrand = 1273,
		bladesedgemountains = 1193,
		netherstorm = 1194,
		shadowmoonvalley = 1195,
		grizzlyhills = 1357,
		boreantundra = 1358,
		howlingfjord = 1356,
		dragonblight = 1359,
		zuldrak = 36,
		sholazarbasin = 39,
		stormpeaks = 38,
		icecrown = 40,
		uldum = 4872,
		deepholm = 4871,
		tolbarad = 4874,
		tolbaradpeninsula = 4874,
		mounthyjal = 4870,
		vashjir = 4982,
		twilighthighlands = 5501,
		jadeforest = 6534,
		valleyofthefourwinds = 6301,
		krasarangwilds = 6536,
		kunlaisummit = 6538,
		townlongsteppes = 6539,
		dreadwastes = 6540
	}
}

local AchievementZone = {
	Alliance = {},
	Horde = {}
}

for ZoneText, AchievementID in pairs(ZoneAchievement.Alliance) do
	AchievementZone.Alliance[AchievementID] = ZoneText
end
for ZoneText, AchievementID in pairs(ZoneAchievement.Horde) do
	AchievementZone.Horde[AchievementID] = ZoneText
end

local AltZoneNames = {
	stormwindstockade = "stockade",
	mounthyjal = "firelandsinvasion",
	moltenfront = "firelandsinvasion",
	crumblingdepths = "deepholm",
	darkmoonisland = "darkmoonfaire"
}

local LastZoneText
local LastRealZoneText
local LastSubZoneText
local LastMinimapZoneText
local LastAltZoneText

local Frame = CreateFrame("Frame", nil, UIParent)

function ZoneTrack.Events(Self, Event, ...)
	if Event == "ADDON_LOADED" then
		VarsLoaded = true
	end
	if not VarsLoaded then return end
	
	local ZoneText = GetZoneText()
	local RealZoneText = GetRealZoneText()
	local SubZoneText = GetSubZoneText()
	local MinimapZoneText = GetMinimapZoneText()
	
	if not ( ZoneText or RealZoneText or SubZoneText or MinimapZoneText ) then return end
	
	if ZoneText then
		ZoneText = string.lower(ZoneText)
		if string.sub(ZoneText, 1, 4) == "the " then ZoneText = string.sub(ZoneText, 5) end
		ZoneText = string.gsub(ZoneText, " ", "")
		ZoneText = string.gsub(ZoneText, "-", "")
		ZoneText = string.gsub(ZoneText, "'", "")
		ZoneText = string.gsub(ZoneText, ":", "")
	end
	
	if RealZoneText then
		RealZoneText = string.lower(RealZoneText)
		if string.sub(RealZoneText, 1, 4) == "the " then RealZoneText = string.sub(RealZoneText, 5) end
		RealZoneText = string.gsub(RealZoneText, " ", "")
		RealZoneText = string.gsub(RealZoneText, "-", "")
		RealZoneText = string.gsub(RealZoneText, "'", "")
		RealZoneText = string.gsub(RealZoneText, ":", "")
	end
	
	if SubZoneText then
		SubZoneText = string.lower(SubZoneText)
		if string.sub(SubZoneText, 1, 4) == "the " then SubZoneText = string.sub(SubZoneText, 5) end
		SubZoneText = string.gsub(SubZoneText, " ", "")
		SubZoneText = string.gsub(SubZoneText, "-", "")
		SubZoneText = string.gsub(SubZoneText, "'", "")
		SubZoneText = string.gsub(SubZoneText, ":", "")
	end
	
	if MinimapZoneText then
		MinimapZoneText = string.lower(MinimapZoneText)
		if string.sub(MinimapZoneText, 1, 4) == "the " then MinimapZoneText = string.sub(MinimapZoneText, 5) end
		MinimapZoneText = string.gsub(MinimapZoneText, " ", "")
		MinimapZoneText = string.gsub(MinimapZoneText, "-", "")
		MinimapZoneText = string.gsub(MinimapZoneText, "'", "")
		MinimapZoneText = string.gsub(MinimapZoneText, ":", "")
	end
	
	local AltZoneText = AltZoneNames[ZoneText]
	
	if ZoneTrackSaved.TrackAchievement == 1 then
		local Faction = UnitFactionGroup("player")
		
		if ZoneAchievement[Faction] then
			local AchievementID = ZoneAchievement[Faction][ZoneText]
			
			local AlreadyTracked
			for _, TrackedID in pairs({GetTrackedAchievements()}) do
				if TrackedID == AchievementID then
					AlreadyTracked = true
				elseif AchievementZone[Faction][TrackedID] then
					RemoveTrackedAchievement(TrackedID)
				end
			end
			
			if AchievementID and not AlreadyTracked then
				local _, _, _, Completed, _, _, _, _, _, _, _, _ = GetAchievementInfo(AchievementID)

				if not Completed then AddTrackedAchievement(AchievementID) end
			end
		end
	end
	
	if ZoneTrackSaved.TrackQuests == 1 then
		ExpandQuestHeader(0)		

		local Track

		for i = 1, GetNumQuestLogEntries() do
			local Title, _, _, _, IsHeader, _, _, _, _, _ = GetQuestLogTitle(i)
			
			if IsHeader == 1 then
				local HeaderTitle = string.lower(Title)
				if string.sub(HeaderTitle, 1, 4) == "the " then HeaderTitle = string.sub(HeaderTitle, 5) end
				HeaderTitle = string.gsub(HeaderTitle, " ", "")
				HeaderTitle = string.gsub(HeaderTitle, "-", "")
				HeaderTitle = string.gsub(HeaderTitle, "'", "")
				HeaderTitle = string.gsub(HeaderTitle, ":", "")

				if HeaderTitle == ZoneText or HeaderTitle == RealZoneText or HeaderTitle == SubZoneText or HeaderTitle == MinimapZoneText or HeaderTitle == AltZoneText then
					Track = "a"
				elseif HeaderTitle == LastZoneText or HeaderTitle == LastRealZoneText or HeaderTitle == LastSubZoneText or HeaderTitle == LastMinimapZoneText or HeaderTitle == LastAltZoneText then
					Track = "r"
				else
					Track = nil
				end
			else
				if Track == "a" then
					AddQuestWatch(i)
				elseif Track == "r" then
					RemoveQuestWatch(i)
				end
			end
		end
	end

	LastZoneText = ZoneText
	LastRealZoneText = RealZoneText
	LastSubZoneText = SubZoneText
	LastMinimapZoneText = MinimapZoneText
	LastAltZoneText = AltZoneText
end

Frame:RegisterEvent("ADDON_LOADED")
Frame:RegisterEvent("ZONE_CHANGED_NEW_AREA")
Frame:RegisterEvent("ZONE_CHANGED")
Frame:SetScript("OnEvent", ZoneTrack.Events)

function ZoneTrack.SlashCmds(Msg, EditBox)
	local lMsg
	if Msg then lMsg = string.lower(Msg) end
	
	if string.sub(lMsg,1,1) == "q" then
		if ZoneTrackSaved.TrackQuests == 1 then
			ZoneTrackSaved.TrackQuests = 0
			print("|cff0099ffWyeSoft Zone Track:|r Auto-tracking of quests disabled")
		else
			ZoneTrackSaved.TrackQuests = 1
			print("|cff0099ffWyeSoft Zone Track:|r Auto-tracking of quests enabled")
		end
	elseif string.sub(lMsg,1,1) == "a" then
		if ZoneTrackSaved.TrackAchievement == 1 then
			ZoneTrackSaved.TrackAchievement = 0
			print("|cff0099ffWyeSoft Zone Track:|r Auto-tracking of achievement disabled")
		else
			ZoneTrackSaved.TrackAchievement = 1
			print("|cff0099ffWyeSoft Zone Track:|r Auto-tracking of achievement enabled")
		end
	elseif string.sub(lMsg,1,1) == "i" then
		print("|cff0099ffWyeSoft Zone Track:|r")
		print("Zone text: ", GetZoneText())
		print("Real zone text: ", GetRealZoneText())
		print("Sub zone text: ", GetSubZoneText())
		print("Minimap zone text: ", GetMinimapZoneText())
	else
		print("|cff0099ffWyeSoft Zone Track:|r Available commands:")
		print("|cffffff00/ZONETRACK Q|r  toggles automatic tracking of quests when entering a zone.")
		print("|cffffff00/ZONETRACK A|r  toggles automatic tracking of quest completion achievement when entering a zone.")
		print("|cffffff00/ZONETRACK I|r  displays information on the area you are currently in (intended for debugging purposes).")
		print("|cffffff00/ZONETRACK H|r  lists Zone Track's slash commands.")
	end
end

SLASH_ZONETRACK1 = "/zonetrack"
SLASH_ZONETRACK2 = "/wyesoftzonetrack"
SlashCmdList["ZONETRACK"] = ZoneTrack.SlashCmds
