--[[
************************************************************************

questlog.lua

File date: 2010-07-13T14:36:51Z
File revision: 237
Project revision: 237
Project version: Locale update


Author: Angelike

************************************************************************
]]--

local beql = LibStub("AceAddon-3.0"):GetAddon("beql")
local beqlQ = beqlQ
local L = LibStub("AceLocale-3.0"):GetLocale("beql")
--local beql.cHeader = {}

function beql:QuestLog_UpdateFrame()
	-- movability
	if beql.db.profile.QuestLog.locked then
		QuestLogFrame:RegisterForDrag(0);
		beqlQuestLogFrameAnchor:SetMovable(nil);
	else
		QuestLogFrame:RegisterForDrag("LeftButton");
		beqlQuestLogFrameAnchor:SetMovable(true);
	end

--[[	if beql:IsEnabled() and beql.db.profile.QuestLog.style == 'simple' then
			-- Show Buttons
		beqlQuestLogFrameMinimizeButton:Hide();
		beqlQuestLogFrameConfigButton:Show();
		beqlQuestLogExpandButtonFrame:Hide()
	elseif beql:IsEnabled() and beql.db.profile.QuestLog.style == 'extended' then
		beqlQuestLogFrameMinimizeButton:Show();
		beqlQuestLogFrameConfigButton:Show();
		beqlQuestLogExpandButtonFrame:Show()
	else
		beqlQuestLogFrameMinimizeButton:Hide();
		beqlQuestLogFrameConfigButton:Hide();
		beqlQuestLogExpandButtonFrame:Hide()
	end --]]

	QuestLogFrame:SetAlpha(beql.db.profile.QuestLog.Alpha);
	QuestLogFrame:SetScale(beql.db.profile.QuestLog.Scale);

	QuestLogFrame:ClearAllPoints();
	QuestLogFrame:SetPoint("TOPLEFT", beqlQuestLogFrameAnchor, "TOPLEFT", 0,0)

	return true
end

function beql:QuestLog_ExtendedQuestLog()

	-- Code from DoubleWide by Iriel
	-- {
	QuestLogFrame:SetAttribute("UIPanelLayout-width", 680)
	QuestLogFrame:SetHeight(522)
	QuestLogDetailScrollFrame:ClearAllPoints()
	QuestLogDetailScrollFrame:SetPoint("TOPLEFT", QuestLogListScrollFrame, "TOPRIGHT", 34, 0)
	QuestLogDetailScrollFrame:SetHeight(410)
	QuestLogScrollFrame:SetHeight(410)

	HybridScrollFrame_CreateButtons(QuestLogScrollFrame, "QuestLogTitleButtonTemplate");

	for k in pairs(QuestLogFrame.textures) do
		if strfind(k, 'beql') then
			QuestLogFrame.textures[k]:Show()
		elseif strfind(k, 'QuestLogFrame') then
			QuestLogFrame.textures[k]:Hide()
		elseif k == 'Icon' then
			QuestLogFrame.textures[k]:SetTexture("Interface\\Addons\\beql\\Images\\icon");
		end
	end
	-- }
	-- Code from DoubleWide by Iriel, mod by angelike @ wowace.com

end

function beql:QuestLog_SimpleQuestlog()

	-- restore old sizes an points
	QuestLogFrame:SetAttribute("UIPanelLayout-width", nil)
end

function beql:QuestLog_ToggleStyle(style)

	local events = {'QUEST_PROGRESS','QUEST_COMPLETE',
		--'CHAT_MSG_SYSTEM', 'QUEST_GREETING', 'GOSSIP_SHOW', -- ToDo: Autoquest
		};
	local hooks = {
		'QuestLogTitleButton_OnClick',
		'QuestLog_Update',
		--'GetQuestLogTitle', -- something bugs if we open world map when in combat and this function is hooked
		'QuestLog_OnShow','QuestLog_SetSelection'
	} --
	-- Unregister old events Events
	for _, v in ipairs(events) do
		beql:UnregisterEvent(v);
	end

	-- Unhook old Scripts
	for _, v in ipairs(hooks) do
		beql:Unhook(v)
	end

	-- frame Defaults
	QuestLogTitleText:SetText(QUEST_LOG)
	beql:QuestLog_SetFontSize(12)
	QuestLogFrame:SetAlpha(1)
	QuestLogFrame:SetScale(1)
	QuestLogFrame:RegisterForDrag(0)
	QuestLogFrame:ClearAllPoints()
	QuestLogFrame:SetPoint("TOPLEFT", UIParent, "TOPLEFT", 0,-104)
	QuestLogScrollFrame:SetHeight(335)
	QuestLogFrame:SetWidth(680)
	QuestLogFrame:SetHeight(447)
	
	-- Hide Addon Buttons
	beqlQuestLogFrameMinimizeButton:Hide();
	beqlQuestLogFrameConfigButton:Hide();
	beqlQuestLogExpandButtonFrame:Hide()

	-- restore old textures
	for k in pairs(QuestLogFrame.textures) do
		if strfind(k, 'beql') then
			QuestLogFrame.textures[k]:Hide()
		elseif strfind(k, 'QuestLogFrame') then
			QuestLogFrame.textures[k]:Show()
		elseif k == 'Icon' then
			QuestLogFrame.textures[k]:SetTexture("Interface\\QuestFrame\\UI-QuestLog-BookIcon");
		end
	end

	beqlQ:RemoveObjectiveHandler(beql.ManageQuests, 'pre')

	UIPanelWindows["QuestLogFrame"] = {
		area = "doublewide",
		pushable = 0,
		whileDead = 1
	};

	-- Blizzard Status is now resored, activate beql stuff if needed
	
	if style and (style == 'simple' or style == 'extended') then
		beqlQuestLogFrameConfigButton:Show();
		beqlQuestLogExpandButtonFrame:Show()
		QuestLogFrame:ClearAllPoints();
		QuestLogFrame:SetPoint("TOPLEFT", beqlQuestLogFrameAnchor, "TOPLEFT", 0,0)
		beqlQ:AddObjectiveHandler(beql.ManageQuests, 'pre')
		QuestLogTitleText:SetText(L["Bayi's Extended Quest Log"])

		-- Events
		for _, v in ipairs(events) do
			beql:RegisterEvent(v, "Event_" .. v);
		end

		-- Hook Scripts
		for _, v in ipairs(hooks) do
			beql:RawHook(v, 'Hooks_' .. v, true);
		end

		if style == 'extended' then
			beqlQuestLogFrameMinimizeButton:Show();
			beql:QuestLog_ExtendedQuestLog();
		else
			beql:QuestLog_SimpleQuestlog();
		end
		beql:QuestLog_SetFontSize(beql.db.profile.QuestLog.FontSize);
	end
	QuestLog_Update();
end

function beql:QuestLog_Minimize(button)
	beql.db.char.QuestLogMinimized = true
	button = button and button or beqlQuestLogFrameMinimizeButton
	button:SetNormalTexture("Interface\\AddOns\\beql\\Images\\restore_up")
	button:SetPushedTexture("Interface\\AddOns\\beql\\Images\\restore_down")

	QuestLogFrame:SetAttribute("UIPanelLayout-width", 384)
	QuestLogFrame:SetWidth(353)

	-- change textures
	QuestLogFrame.textures.beqlRight:Hide();
	QuestLogFrame.textures.beqlLeft:SetTexture("Interface\\AddOns\\beql\\Images\\LeftOff");

	if QuestLogFrame:IsVisible() then
		QuestLogControlPanel:Hide()
	end
	QuestLogDetailScrollFrame:Hide();
end

function beql:QuestLog_Maximize(button)
	beql.db.char.QuestLogMinimized = false

	if ( GetNumQuestLogEntries() == 0 ) then
		-- no quests in log, do not allow to maximize
		return
	end

	button = button and button or beqlQuestLogFrameMinimizeButton
	button:SetNormalTexture("Interface\\AddOns\\beql\\Images\\minimize_up")
	button:SetPushedTexture("Interface\\AddOns\\beql\\Images\\minimize_down")
	QuestLogFrame:SetAttribute("UIPanelLayout-width", 680)
	QuestLogFrame:SetWidth(682)

	-- change textures
	QuestLogFrame.textures.beqlRight:Show();
	QuestLogFrame.textures.beqlLeft:SetTexture("Interface\\AddOns\\beql\\Images\\LeftOn");

	if QuestLogFrame:IsVisible() then
		QuestLogControlPanel:Show()
		QuestLogDetailScrollFrame:Show()
		QuestLogDetailScrollFrame:SetHeight(410)
	end
end

function beql:QuestLog_SetFontSize(size)
	if not size or size == 0 then size = 12 end
	local font, fontsize, fontflags, button, buttontag
	for i = 1, #QuestLogScrollFrame.buttons do
			buttontag = getglobal("QuestLogScrollFrameButton"..i.."Tag")
			font,fontsize,fontflags = buttontag:GetFont()
			buttontag:SetFont(font,size)

			button = getglobal("QuestLogScrollFrameButton"..i.."NormalText");
			font,fontsize,fontflags = button:GetFont()
			button:SetFont(font,size)
	end

	-- +0px
	local smallfonts = {
		'QuestInfoRequiredMoneyText','QuestInfoTimerText','QuestInfoObjective1',
		'QuestInfoObjective2','QuestInfoObjective3','QuestInfoObjective4',
		'QuestInfoObjective5','QuestInfoObjective6','QuestInfoObjective7',
		'QuestInfoObjective8','QuestInfoObjective9','QuestInfoObjective10',
	}
	
	-- +1px
	local normalfonts = {
		"QuestInfoSpellLearnText", "QuestInfoItemReceiveText", "QuestInfoItemChooseText", 
		"QuestInfoDescriptionText", "QuestInfoAnchor", "QuestInfoGroupSize", 
		"QuestInfoRewardText", "QuestInfoObjectivesText",
		
		-- test
		'QuestInfoHonorFrameReceiveText', 'QuestInfoArenaPointsFrameReceiveText', 'QuestInfoTalentFrameReceiveText', 
		'QuestInfoXPFrameReceiveText', 'QuestInfoPlayerTitleFrameTitle', 'QuestInfoPlayerTitleFrameTitleLabel', 'QuestInfoReputationText', 
	}
	
	local largefonts = {
		'QuestInfoXPFramePoints', 'QuestInfoTalentFramePoints', 
	}
	
	-- +6px
	local bigfonts = {
		"QuestInfoTitleHeader", "QuestInfoDescriptionHeader", "QuestInfoObjectivesHeader", "QuestInfoRewardsHeader" ,
	}

	for _, fontname in ipairs(smallfonts) do
		if not _G[fontname] then
			beql:debugprint(fontname.." not found")
			break
		end
		local font,fontsize,fontflags = _G[fontname]:GetFont();
		_G[fontname]:SetFont(font,size,fontflags);
	end

	for _, fontname in ipairs(normalfonts) do
		if not _G[fontname] then
			beql:debugprint(fontname.." not found")
			break
		end
		local font,fontsize,fontflags = _G[fontname]:GetFont();
		_G[fontname]:SetFont(font,size + 1,fontflags);
	end

	for _, fontname in ipairs(largefonts) do
		if not _G[fontname] then
			beql:debugprint(fontname.." not found")
			break
		end
		local font,fontsize,fontflags = _G[fontname]:GetFont();
		_G[fontname]:SetFont(font,size + 4,fontflags);
	end

	for _, fontname in ipairs(bigfonts) do
		if not _G[fontname] then
			beql:debugprint(fontname.." not found")
			break
		end
		local font,fontsize,fontflags = _G[fontname]:GetFont();
		_G[fontname]:SetFont(font,size + 6,fontflags);
	end


	--font,fontsize,fontflags = QuestLogDummyText:GetFont()
	--QuestLogDummyText:SetFont(font,size + 6)
end

local function _QuestLog_HighlightQuest(questLogTitle)
	local prevParent = QuestLogHighlightFrame:GetParent();
	if ( prevParent and prevParent ~= questLogTitle ) then
		-- set prev quest's colors back to normal
		local prevName = prevParent:GetName();
		prevParent:UnlockHighlight();
		prevParent.tag:SetTextColor(prevParent.r, prevParent.g, prevParent.b);
		prevParent.groupMates:SetTextColor(prevParent.r, prevParent.g, prevParent.b);
	end
	if ( questLogTitle ) then
		local name = questLogTitle:GetName();
		-- highlight the quest's colors
		questLogTitle.tag:SetTextColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b);
		questLogTitle.groupMates:SetTextColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b);
		questLogTitle:LockHighlight();
		-- reposition highlight frames
		QuestLogHighlightFrame:SetParent(questLogTitle);
		QuestLogHighlightFrame:SetPoint("TOPLEFT", questLogTitle, "TOPLEFT", 0, 0);
		QuestLogHighlightFrame:SetPoint("BOTTOMRIGHT", questLogTitle, "BOTTOMRIGHT", 0, 0);
		QuestLogSkillHighlight:SetVertexColor(questLogTitle.r, questLogTitle.g, questLogTitle.b);
		QuestLogHighlightFrame:Show();
	else
		QuestLogHighlightFrame:Hide();
	end
end

--
-- EVENTS --
--


function beql:Event_QUEST_PROGRESS()
	if beql.db.profile.QuestLog.autocomplete then
		CompleteQuest()
	end
end

function beql:Event_QUEST_COMPLETE()
	local questname = GetTitleText()

	beql.lastquest.qID = "unknown"
	beql.lastquest.name = questname
	beql.lastquest.chatname = string.format(ERR_QUEST_COMPLETE_S , questname)

	-- search for quest in questlog
	for uid, questdata in pairs(beqlQ.quests) do
		if questdata.title == questname then
			beql.lastquest.qID = uid
			break
		end
	end

--	print("Complete Quest " .. GetTitleText() .. " UniqeID: " .. beql.lastquest.name)
	if beql.db.profile.QuestLog.autocomplete and GetNumQuestChoices() == 0 then
		GetQuestReward(QuestFrameRewardPanel.itemChoice)
	end
end
--[[
function beql:Event_CHAT_MSG_SYSTEM(event, msg)

	--[ [ Questhistory
	if msg == beql.lastquest.chatname then
--		print("beql: You completed Quest " .. beql.lastquest.name .. " (ID: " .. beql.lastquest.qID .. ")")

		-- quest comes not from questlog, wem must seach the ID
		if beql.lastquest.qID == "unknown" then
			-- create questname key
			if not beql.db.global.questsearch[beql.lastquest.name] then
				beql.db.global.questsearch[beql.lastquest.name] = {}
			end

			-- create playerkey for quest
			if not beql.db.global.questsearch[beql.lastquest.name][beql.PlayerKey] then
				beql.db.global.questsearch[beql.lastquest.name][beql.PlayerKey] = {
				time = time(),
				count = 1,
				--zone = Quest:GetQuestCategoryKey(GetZoneText()),
			}
			else
				-- update done count
				beql.db.global.questsearch[beql.lastquest.name][beql.PlayerKey].count = beql.db.global.questsearch[beql.lastquest.name][beql.PlayerKey].count + 1
			end
			--beqlQuestFindFrame:Show()
		elseif type(beql.lastquest.qID) == 'number' then
			if not beql.db.global.QuestHistoryDB[beql.PlayerKey][beql.lastquest.qID] then
				beql.db.global.QuestHistoryDB[beql.PlayerKey][beql.lastquest.qID] = {
					count = 0,
				}
			end
			beql.db.global.QuestHistoryDB[beql.PlayerKey][beql.lastquest.qID].time = timestamp
			beql.db.global.QuestHistoryDB[beql.PlayerKey][beql.lastquest.qID].status = 3
			beql.db.global.QuestHistoryDB[beql.PlayerKey][beql.lastquest.qID].count = beql.db.global.QuestHistoryDB[beql.PlayerKey][beql.lastquest.qID].count + 1

		end
	end--] ]

end
--]]
local f = CreateFrame('Frame')
f:RegisterAllEvents()
f:SetScript('OnEvent', function(self, event)
	if strmatch(event, 'QUEST') or strmatch(event, 'GOSSIP')  or strmatch(event, 'FLOAT') then --UPDATE_FLOATING_CHAT_WINDOWS
		beql:debugprint(event)
	end
end)
--[[
function beql:Event_QUEST_GREETING()
-- ToDo accetpt new/dayliy/repeatable quest
	print("Event_QUEST_GREETING")
	local numActiveQuests = GetNumActiveQuests(); -- Quests in quest log
	local numAvailableQuests = GetNumAvailableQuests(); -- Quests not in quest log
	print('numActiveQuests ' .. tostring( numActiveQuests ))
	print('numAvailableQuests ' .. tostring( numAvailableQuests ))
	if numActiveQuests > 0 then
		for i = 1, numActiveQuests, 1 do
			local title, isComplete = GetActiveTitle(i);
			if isComplete and beql.db.profile.QuestLog.AutoQuest then
				SelectActiveQuest(i);
			end
			beql:debugprint(title .. " (id: " .. tostring(i) .. ")")
			
		end
		-- todo check active quest for complete
	end
	
	if numAvailableQuests > 0 then
		for i=1, numAvailableQuests, 1 do
			local isTrivial, isDaily, isRepeatable = GetAvailableQuestInfo(i - numActiveQuests);
			-- daily
			if (isDaily and beql.db.profile.QuestLog.AutoQuestDaily) or ( not isTrivial and beql.db.profile.QuestLog.AutoQuest and not beql.db.profile.QuestLog.AutoQuestTrivial ) or ( beql.db.profile.QuestLog.AutoQuest and beql.db.profile.QuestLog.AutoQuestTrivial) then
				SelectAvailableQuest(i)
			end
			local title = GetAvailableTitle(i)
			beql:debugprint(tostring(title) .. " (id: " .. tostring(i) .. ")")
			
			--SelectAvailableQuest
		end
		-- todo chek active quest for complete
		-- todo check new quests
	end

-- ToDo progress completed quests
end


local function Gossip_ActiveQuests(...)
	local index = 1
	for i=1, select('#', ...), 4 do
		local isComplete = select(i+3)
		if isComplete and beql.db.profile.QuestLog.AutoQuest then
			SelectGossipActiveQuest(index);
		elseif (isComplete and beql.db.profile.QuestLog.AutoQuestDaily ) then -- check Daily
			-- ToDo: very complexe check, if active quest is an daily quest :)
			local questname = select(i,...)
			for uid, questdata in pairs(beqlQ.quests) do
				if questdata.title == questname then
					local questindex = uID_2_index[uid];
					local isDaily = select(8 ,GetQuestLogTitle(questindex));
					if isDaily then
						SelectGossipActiveQuest(index);
					end
				end
			end
		end
		index = index + 1
	end
end

local function Gossip_AvailableQuests(...)
	local index = 1
	for i=1, select('#', ...), 5 do
		local isTrivial, isDaily, isRepeatable = select(i+2)
		if (isDaily and beql.db.profile.QuestLog.AutoQuestDaily) or ( not isTrivial and beql.db.profile.QuestLog.AutoQuest and not beql.db.profile.QuestLog.AutoQuestTrivial ) or ( beql.db.profile.QuestLog.AutoQuest and beql.db.profile.QuestLog.AutoQuestTrivial) then
			SelectGossipAvailableQuest(index)
		end
		index = index + 1
	end

end

function beql:Event_GOSSIP_SHOW()
	-- Blizzard, this is an stupid idea
	Gossip_ActiveQuests(GetGossipActiveQuests()) -- title1, level1, isLowLevel1, isComplete1, title2, level2, isLowLevel2, isComplete2, etc

	Gossip_AvailableQuests(GetGossipAvailableQuests()) -- title1, level1, isLowLevel1, isDaily1, isRepeatable1, title2, level2, isLowLevel2, isDaily2, isRepeatable2
end

hooksecurefunc('CloseQuest', function()
	print('CloseQuest')
end)
hooksecurefunc('CloseGossip', function()
	print('CloseGossip')
end)
--]]
--
-- Hooks
--

function beql:Hooks_QuestLog_SetSelection(questindex)
	-- this is a fix, we show QuestLogFrame, before Quest is selected so QuestDetailFrame would not be shown
	QuestFrame.SelectedUid = select(9, GetQuestLogTitle(questindex));
	ShowUIPanel(QuestLogFrame);
	
	-- check if header is collapsed, expand it for correct display
	for i=questindex, 1, -1 do
		if select(5, GetQuestLogTitle(i)) then
			local headername = GetQuestLogTitle(i);
			if beql.cHeader[headername] == 1 then
				beql.cHeader[headername] = 0;
			end
			break;
		end
	end
	beql.hooks.QuestLog_SetSelection(questindex)
	if beql.db.profile.QuestLog.style == 'extended' then
		beql:QuestLog_Maximize();
	end
end

function beql:QuestLog_SetNearestValidSelection()

end

function beql:QuestLog_SetFirstValidSelection()
	local title, _, isHeader, add
	for i=1, GetNumQuestLogEntries(), 1 do
		title, _, _, _ , isHeader = GetQuestLogTitle(i)
		if add and (not isHeader) then
			return i
		elseif isHeader and beql.cHeader[title] == 0 then
			add = true
		end
	end
	return 0
end

function beql:Hooks_QuestLogTitleButton_OnClick(this, mousebutton)
	if mousebutton ~= "LeftButton" then
		return
	end
	
	-- Add control click
	local questIndex = this:GetID() -- + HybridScrollFrame_GetOffset(QuestLogScrollFrame); -- not needed, because we work with real Id'S
	local questName = GetQuestLogTitle(questIndex)

	if beql.db.char.QuestLogMinimized and not this.isHeader then
		beql:QuestLog_Maximize()
	end

	if this.isHeader and ( not IsModifiedClick() ) then
		if beql.cHeader[questName] == 1 then
			beql.cHeader[questName] = 0
		else
			beql.cHeader[questName] = 1
		end
		QuestLogFrame.selectedIndex = questIndex
		QuestFrame.SelectedUid = 0; -- mark as header
		QuestLog_Update();
		return
	end


	if not IsModifiedClick("QUESTWATCHTOGGLE") and IsControlKeyDown()  then
		if ChatFrame1EditBox:IsVisible() then
			-- add status to quest to chat (oldstyle)
			beql:AddQuestStatusToChatFrame(questIndex)
		end
	end

	-- Header clicked, toggle watches for the quests
	if IsModifiedClick("QUESTWATCHTOGGLE") and this.isHeader then
		local questLogTitleText, isHeader, isCollapsed, firstTrackable, lastTrackable, numTracked, numUntracked, _
		lastTrackable = -1
		numTracked = 0
		numUntracked = 0
		local track = false
		-- check tracked status
		for i=1, GetNumQuestLogEntries(), 1 do
			questLogTitleText, _, _, _, isHeader, isCollapsed = GetQuestLogTitle(i)
			if  questLogTitleText == questName  then
				track = true
				firstTrackable = i+1
			elseif ( track ) then
				if  not isHeader  then
					if IsQuestWatched(i)  then
						numTracked = numTracked+1
						RemoveQuestWatch(i)
					else
						numUntracked = numUntracked+1
						RemoveQuestWatch(i)
					end
				end
				if  isHeader and questLogTitleText ~= questName  then
					lastTrackable = i-1
					break
				end
			end
		end
		if  lastTrackable == -1  then
			lastTrackable = GetNumQuestLogEntries()
		end
		if  numUntracked == 0  then
			-- Untrack all
			for i=firstTrackable, lastTrackable, 1 do
				RemoveQuestWatch(i)
			end
		else
			-- Track all
			for i=firstTrackable, lastTrackable, 1 do
				AddQuestWatch(i)
				-- Set an error message if trying to show too many quests
				if ( GetNumQuestWatches() >= MAX_WATCHABLE_QUESTS ) then
					UIErrorsFrame:AddMessage(format(QUEST_WATCH_TOO_MANY, MAX_WATCHABLE_QUESTS), 1.0, 0.1, 0.1, 1.0)
					break
				end
			end
		end
		WatchFrame_Update()
		QuestLog_Update()
	end

	--
	-- Original QuestLogTitleButton_OnClick(button) (altered)
	--

--	local questName = this:GetText()
--	local questIndex = this:GetID() + FauxScrollFrame_GetOffset(QuestLogListScrollFrame)
	if ( IsModifiedClick("QUESTWATCHTOGGLE") and not this.isHeader ) then
		-- Otherwise try to track it or put it into chat
		if ( ChatFrame1EditBox:IsVisible() ) then
			--ChatFrame1EditBox:Insert(strsub(strtrim(this:GetText()),11))
			local questLink = GetQuestLink(questIndex);
			if ( questLink ) then
				ChatEdit_InsertLink(questLink);
			else
				ChatFrame1EditBox:Insert(gsub(this:GetText(), " *(.*)", "%1"))
			end
		else
			-- Shift-click toggles quest-watch on this quest.
			if ( IsQuestWatched(questIndex) ) then
				RemoveQuestWatch(questIndex)
				WatchFrame_Update()
			else
				-- Set an error message if trying to show too many quests
				if ( GetNumQuestWatches() >= MAX_WATCHABLE_QUESTS ) then
					UIErrorsFrame:AddMessage(format(QUEST_WATCH_TOO_MANY, MAX_WATCHABLE_QUESTS), 1.0, 0.1, 0.1, 1.0)
					return
				end
				AddQuestWatch(questIndex)
				QuestLog_Update()
				WatchFrame_Update()
			end
		end
	end

	-- Quest History Love :)
	if (IsAltKeyDown() and QuestHistoryFrame) then -- questhistory
		if (mousebutton == "LeftButton") then
			QuestHistoryFrameSearchEditBox_OnEnterPressed_External(questName)
		end
	end

	-- only select quests, no headers
	if not this.isHeader then
		QuestLog_SetSelection(questIndex)
--	if IsAddOnLoaded("Lightheaded") then
--		LightHeaded:QuestLogTitleButton_OnClick(frame, button)
--	end
	end
	QuestLog_Update()

end

function beql:Hooks_QuestLog_OnShow(frame)
	if beql.db.profile.QuestLog.style == 'simple' then
		-- nothing to do, run org function and exit
		beql.hooks.QuestLog_OnShow(frame)
		return
	end
	
	-- run modified script to prevent issues
	UpdateMicroButtons();
	PlaySound("igQuestLogOpen");
	QuestLogControlPanel_UpdatePosition();
	QuestLogShowMapPOI_UpdatePosition();
	QuestLog_SetSelection(GetQuestLogSelection());
	QuestLog_Update();

	QuestLogDetailScrollFrame:SetParent(QuestLogFrame);
	QuestLogDetailScrollFrame:ClearAllPoints();
	QuestLogDetailScrollFrame:SetPoint("TOPRIGHT", QuestLogFrame, "TOPRIGHT", -32, -77);
	QuestLogDetailScrollFrame:SetHeight(410);
	QuestLogDetailScrollFrameScrollBar:SetPoint("TOPLEFT", QuestLogDetailScrollFrame, "TOPRIGHT", 6, -13);
	QuestLogDetailScrollFrameScrollBackgroundBottomRight:Hide();
	QuestLogDetailScrollFrameScrollBackgroundTopLeft:Hide();

	do return; end
	beqlQuestLogFrameAnchor.UpdateFrame = nil;
	beql:RestoreFramePosition(QuestLogFrame)

	if beql.db.char.QuestLogMinimized or beql.db.profile.QuestLog.alwaysminimize or GetQuestLogSelection() == 0 then
		beql:QuestLog_Minimize()
	end
	if beql.db.profile.QuestLog.alwaysmaximize then
		beql:QuestLog_Maximize()
	end
end

function beql:GetTaggedQuestLogTitle(index)
	local questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, uid = GetQuestLogTitle(index)
	if isHeader and not beql.cHeader[questLogTitleText] then
		beql:debugprint("new header: " .. questLogTitleText);
		-- new header
		beql.cHeader[questLogTitleText] = isCollapsed or 0;
	end
	
	if isHeader then
		-- no need to modify heades, exit
		return questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, uid, beql.cHeader[questLogTitleText]
	end
	
	-- build a tagged title
	if beql.db.profile.QuestLog.showlevel and questLogTitleText and level and level > 0 and not isHeader then
		if  questTag == GROUP then
			if suggestedGroup > 0 then
				questLogTitleText = "["..  level .. "G" .. suggestedGroup .. "]" .. questLogTitleText
			else
				questLogTitleText = "["..  level .. "G] " .. questLogTitleText
			end
		elseif  questTag == ELITE  then
			questLogTitleText = "[" .. level .. "+] " .. questLogTitleText
		elseif  questTag == ITEM_HEROIC then
			questLogTitleText = "[" .. level .. "H] " .. questLogTitleText
		elseif  questTag == RAID  then
			questLogTitleText = "[" .. level .. "R] " .. questLogTitleText
		elseif  questTag == PVP  then
			questLogTitleText = "[" .. level .. "P] " .. questLogTitleText
		elseif isDaily then
			questLogTitleText = "[" .. level .. "Y] " .. questLogTitleText
		elseif  questTag == LFG_TYPE_DUNGEON  then
			questLogTitleText = "[" .. level .. "D] " .. questLogTitleText
		else
			questLogTitleText = "[" .. level .. "] " .. questLogTitleText
		end
	end

	return questLogTitleText, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, uid
end

function beql:Hooks_QuestLog_Update()

	-- prepare entries
	-- questtable contains the real id's for the quest
	-- real questindex = questtable[unreal quest index]
	local questtable = {}
	local title, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, uid;
	local LineNr = 1
	local CollapsedHeader = 0
	local addquests = true
	local NumHeader = 0
	local lastHeaderIndex, lastHeaderName
	
	for i=1, GetNumQuestLogEntries(), 1 do
		title, level, questTag, suggestedGroup, isHeader, isCollapsed = GetQuestLogTitle(i);
		if ( isHeader ) then
			lastHeaderIndex = i;
			lastHeaderName = title
			NumHeader = NumHeader + 1;
			-- dump header data
			if not beql.cHeader[title] then
				if isCollapsed then
					beql.cHeader[title] = 1
					CollapsedHeader = CollapsedHeader + 1
				else
					beql.cHeader[title] = 0
				end
			end

			if beql.cHeader[title] == 1 then
				-- Header is (virtual) collapsed, do not add quests
				addquests = nil
			else
				addquests = true
			end

			table.insert(questtable,i)
		elseif ( not addquest and QuestLogFrame.selectedIndex == i ) then
			-- we have a quest selected, which is in a collapsed Header, expand it and add quest
			beql.cHeader[lastHeaderName] = 0
--			addquests = true;
			table.insert(questtable,i)
		elseif( addquests ) then
			table.insert(questtable,i)
		end
	end

	if CollapsedHeader > 0 then
		-- we have real collapsed headers, expand all
		ExpandQuestHeader(0);
		-- no need to proceed, because we get the event QUEST_LOG_UPDATE
		return
	end

	-- set Collapse all texture
	if #questtable == NumHeader then
		--function QuestLogCollapseAllButton_OnClick(self)
		beqlQuestLogCollapseAllButton.collapsed = 1;
		beqlQuestLogCollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up");
		QuestLog_SetSelection(0);
	else
		beqlQuestLogCollapseAllButton.collapsed = nil;
		beqlQuestLogCollapseAllButton:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Up");
	end
--
-- org script
--
	local numEntries = #questtable
	local numQuests = select(2, GetNumQuestLogEntries());
	if ( numEntries == 0 ) then
		HideUIPanel(QuestLogDetailScrollFrame);
		QuestLogDetailFrame.timeLeft = nil;
		EmptyQuestLogFrame:Show();
		EmptyQuestLogFrame:SetHeight(460)
		QuestLog_SetSelection(0);
	else
		EmptyQuestLogFrame:Hide();
	end

	QuestLog_UpdateMapButton();

	-- Update Quest Count
	QuestLog_UpdateQuestCount(numQuests);

	-- If no selection then set it to the first available quest
	local questLogSelection = GetQuestLogSelection();
	local haveSelection = questLogSelection ~= 0;
	if ( numQuests > 0 and not haveSelection ) then
		if ( QuestLogFrame.selectedIndex ) then
			--QuestLog_SetNearestValidSelection();
		else
			beql:QuestLog_SetFirstValidSelection();
		end
		questLogSelection = GetQuestLogSelection();
	end
	QuestLogFrame.selectedIndex = questLogSelection;

	-- hide the details if we don't have a selected quest
	if ( not haveSelection ) then
		HideUIPanel(QuestLogDetailScrollFrame);
	end

	-- update the group timer
	local haveGroup = GetNumPartyMembers() > 0 or GetNumRaidMembers() > 1;
	if ( haveGroup ) then
		QuestLogFrame.groupUpdateTimer = 0;
	else
		QuestLogFrame.groupUpdateTimer = nil;
	end

	-- hide the highlight frame initially, it may be shown when we loop through the quest listing if a quest is selected
	QuestLogHighlightFrame:Hide();

	-- Update the quest listing
	local buttons = QuestLogScrollFrame.buttons;
	local numButtons = #buttons;
	local scrollOffset = HybridScrollFrame_GetOffset(QuestLogScrollFrame);
	local buttonHeight = buttons[1]:GetHeight();
	local displayedHeight = 0;

	local numPartyMembers = GetNumPartyMembers();
	local questIndex, questLogTitle, questTitleTag, questNumGroupMates, questNormalText, questCheck;
	local color;
	local partyMembersOnQuest, tempWidth, textWidth;

	for i=1, numButtons do
		questLogTitle = buttons[i];
		questIndex = questtable[i + scrollOffset]; -- get real questindex
		questTitleTag = questLogTitle.tag;
		questNumGroupMates = questLogTitle.groupMates;
		questCheck = questLogTitle.check;
		questNormalText = questLogTitle.normalText;
		if ( (i + scrollOffset) <= numEntries ) then
			questLogTitle:SetID(questIndex);
			title, level, questTag, suggestedGroup, isHeader, isCollapsed, isComplete, isDaily, uid = beql:GetTaggedQuestLogTitle(questIndex, 'AddTags');

			if ( isHeader ) then
				-- set the title
				if ( title ) then
					questLogTitle:SetText(title);
				else
					questLogTitle:SetText("");
				end

				-- overwrite collapsed status
				if beql.cHeader[title] == 1 then
					isCollapsed = 1
				end

				-- set the normal texture based on the header's collapsed state
				if ( isCollapsed ) then
					questLogTitle:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-Up");
				else
					questLogTitle:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-Up");
				end
				questLogTitle:SetHighlightTexture("Interface\\Buttons\\UI-PlusButton-Hilight");

				questNumGroupMates:Hide();
				questTitleTag:Hide();
				--@alpha@
				questTitleTag:Show();
				questTitleTag:SetText(tostring(questIndex));
				--@alpha-end@
				questCheck:Hide();
			else
				-- set the title
				if ( ENABLE_COLORBLIND_MODE == "1" ) then
					-- ToDo fix doubble questlevel
					title = "["..level.."] " .. title;
				end
				questLogTitle:SetText("  "..title);

				-- this isn't a header, hide the header textures
				questLogTitle:SetNormalTexture("");
				questLogTitle:SetHighlightTexture("");

				-- If not a header see if any nearby group mates are on this quest
				partyMembersOnQuest = 0;
				for j=1, numPartyMembers do
					if ( IsUnitOnQuest(questIndex, "party"..j) ) then
						partyMembersOnQuest = partyMembersOnQuest + 1;
					end
				end
				if ( partyMembersOnQuest > 0 ) then
					questNumGroupMates:SetText("["..partyMembersOnQuest.."]");
					questNumGroupMates:Show();
				else
					questNumGroupMates:Hide();
				end

				-- figure out which tag to show, if any
				if ( isComplete and isComplete < 0 ) then
					questTag = FAILED;
				elseif ( isComplete and isComplete > 0 ) then
					questTag = COMPLETE;
				elseif ( isDaily ) then
					if ( questTag ) then
						questTag = format(DAILY_QUEST_TAG_TEMPLATE, questTag);
					else
						questTag = DAILY;
					end
				end
				if ( questTag ) then
					questTitleTag:SetText("("..questTag..")");
					questTitleTag:Show();
				else
					questTitleTag:Hide();
				end

				-- show the quest check if the quest is being watched
				if ( IsQuestWatched(questIndex) ) then
					questCheck:Show();
				else
					questCheck:Hide();
				end
			end

			-- Save if its a header or not
			questLogTitle.isHeader = isHeader;

			-- resize the title button so everything fits where it's supposed to
			QuestLogTitleButton_Resize(questLogTitle);

			-- Color the quest title and highlight according to the difficulty level
			if ( isHeader ) then
				color = QuestDifficultyColors["header"];
			else
				color = GetQuestDifficultyColor(level);
			end
			questTitleTag:SetTextColor(color.r, color.g, color.b);
			questLogTitle:SetNormalFontObject(color.font);
			questNumGroupMates:SetTextColor(color.r, color.g, color.b);
			questLogTitle.r = color.r;
			questLogTitle.g = color.g;
			questLogTitle.b = color.b;
			questLogTitle:Show();

			-- Place the highlight and lock the highlight state
			if ( questLogSelection == questIndex ) then
				_QuestLog_HighlightQuest(questLogTitle);
			else
				questLogTitle:UnlockHighlight();
			end
		else
			questLogTitle:Hide();
		end
		displayedHeight = displayedHeight + buttonHeight;
	end


	HybridScrollFrame_Update(QuestLogScrollFrame, numEntries * buttonHeight, displayedHeight);

	-- update the control panel
	QuestLogControlPanel_UpdateState();

--
-- end org function
--

	if beql.db.char.QuestLogMinimized or ( numEntries == 0 ) or GetQuestLogSelection() == 0 then
		beql:QuestLog_Minimize()
	else
		beql:QuestLog_Maximize()
	end

	local QuestLogCount_top = floor(QuestLogCount:GetTop()-QuestLogFrame:GetTop())
	QuestLogCount:SetPoint("TOPLEFT", QuestLogFrame,"TOPLEFT",250,QuestLogCount_top)

end

--- EOF --- 
 QuestLogFrame:SetBackdrop({bgFile = "Interface/Tooltips/UI-Tooltip-Background"});
 
