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

beql.lua

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


Author: Angelike, Bayi

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

local beql = LibStub("AceAddon-3.0"):NewAddon("beql", "AceConsole-3.0", "AceEvent-3.0", "AceHook-3.0")
beql_dev = LibStub("AceAddon-3.0"):GetAddon("beql")

--[[do
	beql.functiontable = {}
	beql.functiontable.org = {}
	for k, v in pairs(beql) do
		if type(v) == 'function' then
			table.insert(beql.functiontable.org,k)
		end
	end
	table.sort(beql.functiontable.org)
end
--]]
beqlQ = LibStub("LibQuixote-2.0")
local L = LibStub("AceLocale-3.0"):GetLocale("beql")

do
	beql.revision = GetAddOnMetadata("beql", "Version")
	beql.versionstring = GetAddOnMetadata("beql", "Version")
	beql.cHeader = {}
	beql.uID_2_index = {}
	beql.index_2_Header = {}
	beql.questtimers = {}
	beql.lastquest = {}
	beql.QuestItems = 0
	beql.PlayerName = UnitName("player")
	beql.PlayerRealm = GetRealmName()
	beql.PlayerFraction = UnitFactionGroup("player")
	beql.PlayerKey = beql.PlayerRealm .."_" .. beql.PlayerFraction .."_" .. beql.PlayerName

	-- create Linecache
	beqlFrameCache = {}
	beqlFrameCache.Lines = UIFrameCache:New("FRAME", "beqlLine", UIParent, "beqlWatchFrameLineTemplate");
	beqlFrameCache.QuestLines = {}
	beqlFrameCache.QuestLineIndex = 1
	
	QuestLogFrame.selectedUID = 0
end

-- Debug Function
-- #NODOC
function beql:debugprint(text)
	if beql.db.profile.debug then
		DEFAULT_CHAT_FRAME:AddMessage("bEQL: " .. tostring(text))
	end
end
--local print = beql.debugprint

-- toggel addonstatus 
function beql:ToggleActive()
	if beql:IsEnabled() then
		beql:Disable()
	else
		beql:Enable()
	end
end

-- Init beql addon
function beql:OnInitialize()

	beql:InitDB()

	--[===[@debug@
	beql.db.profile.debug = true -- enable debug for svn version
	--@end-debug@]===]
	beql:debugprint("Init beql Addon")
	
	--[[@debug@
	do -- just 4 debug
		beql.functiontable.new = {}
		beql.functiontable.known = {}
		local found
		for k, v in pairs(beql) do
			if type(v) == 'function' then
				found = nil
				for _, v2 in pairs(beql.functiontable.org) do
					if v2 == k then
						found = true
					end
				end
				if not found then
					if strfind(k, "QuestLog_") 
						or strfind(k, "QuestTracker_") 
						or strfind(k, "AchievementTracker_") 
						or strfind(k, "Tooltip_") 
						or strfind(k, "Event_") 
						or strfind(k, "Hooks_") 
					then
						table.insert(beql.functiontable.known,k)
					else
						table.insert(beql.functiontable.new,k)
					end
				end
			end
		end
		table.sort(beql.functiontable.new)
		table.sort(beql.functiontable.known)
	end
	--@end-debug@]]

	-- make some hooks

	-- fix button on minimized tracker
	QuestLogFrame:HookScript("OnUpdate", function() 
		if not WatchFrame.showObjectives then return end
		if beql.db.char.QuestLogMinimized and QuestLogFrameShowMapButton:IsShown() then 
			QuestLogFrameShowMapButton:Hide() 
		elseif not beql.db.char.QuestLogMinimized and not QuestLogFrameShowMapButton:IsShown() then
			QuestLogFrameShowMapButton:Show()
		end
	end)
	

	-- fix map questbuttons in WatchFrame Clear Display
	hooksecurefunc("WatchFrame_ClearDisplay", function()
		for i=1, 25 do
			local itembutton = _G["WatchFrameItem" .. i]
			if itembutton then
				itembutton:Hide()
			else
				break;
			end
		end
		
		-- clear poi buttons
		local button
		for i=1, 4 do
			for j=1,25 do
				button = _G["poiWatchFrameLines" .. i .. "_" ..j]
				if button then
					button:Hide()
				end
			end
		end
	end)

	-- now set some scipts to our frames
	beql:AddFrameScripts();
	
	-- use a functioncall instand of a copy of the function to prevent hook issue
	QuestLogScrollFrame.update = function(...) QuestLog_Update(...) end
	QuestLogDetailFrame:SetScript("OnShow", function(...) QuestLogDetailFrame_OnShow(...) end)
	QuestLogFrame:SetScript("OnShow", function(...) QuestLog_OnShow(...) end)
	
	beql.db.RegisterCallback(beql, "OnProfileChanged", "RefreshConfig")
	beql.db.RegisterCallback(beql, "OnProfileCopied", "RefreshConfig")
	beql.db.RegisterCallback(beql, "OnProfileReset", "RefreshConfig")

	
	beql:BlizzardSetupOptions();
	beql:RegisterChatCommand("beql", function() beql:OpenBlizzardOption("main") end)

	beql:SetEnabledState(beql.db.profile.AddonStatus)

	beql:debugprint("Init beql Addon - done")
end

-- enable beql addon
function beql:OnEnable()
	beql:debugprint("Enable bEQL - START")
	beql.db.profile.AddonStatus = true;
	
	-- Check for other addons
	beql:Compatibility()

	-- Init Questlog
	beql:QuestLog_ToggleStyle(beql.db.profile.QuestLog.style)

	-- Load Questtracker
	beql:QuestTracker_ToggleStatus(beql.db.profile.disabledtracker)

	-- Init Tooltip
	beql:Tooltip_InitTooltip()

	-- Load Achievement Tracker
	--beql:AchievementTracker_Toggle(beql.db.profile.AchievementTracker.Enable)

	-- Browser
	--beql:Browser_HistoryInit()

	beql.db.profile.revision = beql.revision

	--
	-- Callbacks
	--
	local callbacks = {
		'Quest_Gained','Objective_Update','Quest_Complete','Quest_Lost','Quest_Abandoned',
		-- Group handle  -- unfinished business
--		'Party_Quest_Gained','Party_Quest_Complete','Party_Quest_Failed',
--		'Party_Quest_Lost','Party_Objective_Update','Party_Update','Sync_Finished',
	}
	for k in ipairs(callbacks) do
		beqlQ.RegisterCallback(beql, callbacks[k], beql['Quixote_' .. callbacks[k]])
	end
	beql:debugprint("Enable bEQL - end")
end

-- disable beql addon
function beql:OnDisable()
	beql.db.profile.AddonStatus = false;
	beql:debugprint("Disable bEQL")
	-- disable Questlog
	beql:QuestLog_ToggleStyle();
	beqlQuestLogFrameAnchor.UpdateFrame = nil;

	-- disable Tracker
	beql:QuestTracker_ToggleStatus(true)

	-- disable Achievementtracker
	--beql:AchievementTracker_Toggle()

	beql:UnhookAll();

	local callbacks = {
		'Quest_Gained','Objective_Update','Quest_Complete','Quest_Lost','Quest_Abandoned',
		-- Group handle  -- unfinished business
--		'Party_Quest_Gained','Party_Quest_Complete','Party_Quest_Failed',
--		'Party_Quest_Lost','Party_Objective_Update','Party_Update','Sync_Finished',
	}
	for k in ipairs(callbacks) do
		beqlQ.UnregisterCallback(beql, callbacks[k])
	end
	
	-- Update Frames
	WatchFrame_Update()
	QuestLog_Update()
end


-- Internal for setting default values for the variables
-- #NODOC
function beql:InitDB()
	--local charfraction = beql.PlayerFraction .. "_" .. beql.PlayerName
	local defaults = {
	profile = {
		AddonStatus = true,
		Language = "SystemDefault",
		blizzardquesthelper = false,
		debug = false,


	-- QuestTracker
		QuestTracker = {
			Colors = {
				Bg = {
					r = TOOLTIP_DEFAULT_BACKGROUND_COLOR.r,
					g = TOOLTIP_DEFAULT_BACKGROUND_COLOR.g,
					b = TOOLTIP_DEFAULT_BACKGROUND_COLOR.r,
				},
				BgBorder = {
					r = TOOLTIP_DEFAULT_BACKGROUND_COLOR.r,
					g = TOOLTIP_DEFAULT_BACKGROUND_COLOR.g,
					b = TOOLTIP_DEFAULT_BACKGROUND_COLOR.r,
				},
				Zone = {
					r = 1,
					g = 1,
					b = 1,
				},
				HeaderNormal = {
					r = 0.75,
					g = 0.61,
					b = 0,
				},
				HeaderComplete = {
					r = 0.05,
					g = 0.93,
					b = 0.15,
				},
				HeaderFailed = {
					r = 1,
					g = 0.09,
					b = 0,
				},
				ObjectiveNormal = {
					r = 1,
					g = 0.09,
					b = 0,
				},
				ObjectiveComplete = {
					r = 0.05,
					g = 0.93,
					b = 0.15,
				},
				ObjetiveStepColor = {
					r = 0.96,
					g = 1,
					b = 0,
				},
			},

			-- Color event
			UseBgColors = true,
			CustomBgColor = false,
			CustomHeaderColor = true,
			HeaderQuestLevelColor = true,
			CustomZoneColor = false,
			CustomObjetiveColor = true,
			FadeColor = true,
			Alpha = 1,

			locked = true,
			disabled = false,
			ShowHeader = true,
			FontHeight = 10,
			ShowZones = true,
			RemoveFinished = true,
			MinimizeFinished = true,
			HideCompletedOnly = false,
			ShowObjectiveMarkers = true,
			UseTrackerListing = false,
			TrackerList = 0,
			TrackerSymbol = 0,
			SortItems = true,
			AddNew = true,
			AddUntracked = true,
			AutoResize = true,
			FixedWidth = 250,
			LeftClick = true,
			RightClick = true,
			activetracker = true,
			activetrackerparty = false,
		},

--[[		Color = {
			TooltipPartyQuixote = {
				r = 0.4,
				g = 0.4,
				b = 1,
			},
			TooltipPartyNonQuixote = {
				r = 1,
				g = 0.4,
				b = 0.4,
			},
			TooltipPartyObj = {
				r = 0.8,
				g = 0.8,
				b = 0.8,
			},
			TooltipPartyObjComp = {
				r = HIGHLIGHT_FONT_COLOR.r,
				g = HIGHLIGHT_FONT_COLOR.g,
				b = HIGHLIGHT_FONT_COLOR.b,
			},
			ColorMobTooltip = {
				r = 0.8,
				g = 0.8,
				b = 0.8,
			},
			ColorItemTooltip = {
				r = 0.8,
				g = 0.8,
				b = 0.8,
			},
		},--]]

-- QuestLog
		QuestLog = {
			chat = {
				AnnounceQuest = false,
				chattype = "default",
				accept = false,
				abandoned = false,
				progress = true,
				finished = true,
				delivert = false,
			},
			locked = true,
			alwaysminimize = false,
			alwaysmaximize = false,
			showlevel = true,
			InfoOnQuestCompletion = true,
			autocomplete = false,
			style = 'extended',
			Alpha = 1,
			Scale = 1,
			InfoSound = "Sound\\Interface\\PVPFlagCapturedmono.wav",
			FontSize = 12,
		},
-- Tooltip
		Tooltip = {
			Colors = {
				QuestTracker_TooltipTitle = {
					r = 0.75,
					g = 0.61,
					b = 0,
				},
				QuestTracker_TooltipDesc = {
					r = 1.0,
					g = 0.8,
					b = 0,
				},
				GameTooltip_MobTitle = {
					r = 1,
					g = 1,
					b = 1,
				},
				GameTooltip_ItemTitle = {
					r = 1,
					g = 1,
					b = 1,
				},
				GameTooltip_ObjectiveIncomplete = {
					r = 1,
					g = 0.09,
					b = 0,
				},
				GameTooltip_ObjectiveComplete = {
					r = 0.05,
					g = 0.93,
					b = 0.15,
				},
				GameTooltip_ObjectiveStep = {
					r = 0.96,
					g = 1,
					b = 0,
				},
				GameTooltip_NonObjective = {
					r = 1,
					g = 0.64,
					b = 0.03,
				},
			},
			-- Gametooltip
			mob = true,
			item = true,
			GameTooltip_TitelIsQuestcolor = true,
			GameTooltip_ColorObjectives = true,
			GameTooltip_FadeObjectiveColors = true,
			GameTooltip_ObjectiveUseStep = true,
			
			-- dont know
			TooltipTitleDiff = true,
			TooltipObjFade = true,
			TooltipItemFade = true,
			
			-- QuestTracker 
			QuestTracker_TooltipShow = true,
			QuestTracker_TooltipTitleQuestcolor = true,
			QuestTracker_TooltipDesc = true,
		},
-- Fubar
		fubar = {
			HidePlugin = false,
			ShowIcon = true,
			ShowText = true,
			ShowColoredText = true,
			ShowTooltip = true,
			FubarPosition = "MINIMAP",
			MinimapPosition = 238,
		},
	},

	char = {
		FramePositions = {
			QuestTracker_posx = 0,
			QuestTracker_posy = 0,
			QuestTracker_point = "CENTER",
			QuestLog_posx = 0,
			QuestLog_posy = -94,
			QuestLog_point = "TOPLEFT",
		},
		QuestLogMinimized = false,
		QuestWatchMinimized = false,
		QuestWatchIDs = {},
		questlogids = {},
	},
	global = {
		questtimes = {},
		searchid = 1,
		QuestDB = {},
		QuestHistoryDB = {
			[beql.PlayerKey] = {}, -- looks like realm_fraction_charname
		},
	},
	}
	beql.db = LibStub("AceDB-3.0"):New("beqlDBnew", defaults, true)
end

--[[----------------------------------------
-- Arguments:
-- number - quest id
-- string - quest name
--
-- Notes:
-- Prints the Quest Name/Status and Objectives to the currently opened chatbox
--
-- Returns:
-- * nothing
------------------------------------------]]
function beql:AddQuestStatusToChatFrame(questIndex)
	local chatFrame = DEFAULT_CHAT_FRAME
	local chatType = chatFrame.editBox:GetAttribute("chatType")
	local oText, oType, oNumP, oNumN, oComp
	local text
	if chatType == "WHISPER" then
		chatType = "SAY"
	end
	local qID, qIndex , qTitle, qLvl, qTag, qObj, qStat, qRec, qdaily, qZone = beqlQ:GetQuestById(questIndex)
	if qObj and qObj > 0 then
		SendChatMessage("["..qLvl..string.upper(beqlQ:GetShortTagForQuest(qID)).."] "..qTitle, chatType)
		local _, qObjectives = beqlQ:IterateObjectivesForQuest(qID)
		for oText, oItems in pairs(qObjectives) do
			text = ""
			oComp = false;
			oNumP, oNumN, oType = unpack(oItems)
			if oNumN == nil then oNumN = 1 end
			if oNumP == nil then oNumP = 1 end
			if oText == nil then oText = "" end
			if oNumP == oNumN then
				oComp = true
			end

			text = oText

			if oComp then
				text = text.." "..L["(Done)"]
			else
				text = text..": "..oNumP.."/"..oNumN
			end
			if text and strlen(text) > 0 then
				SendChatMessage(" - "..text, chatType)
			end
		end

--[[		for i=1, qObj do
			text = ""
			oText, oType, oNumP, oNumN, oComp = beqlQ:GetQuestStatusById(questIndex, i)
			text = oText
			if finished then
				text = text.." "..L["(Done)"]
			else
				text = text..": "..oNumP.."/"..oNumN
			end
			if text and strlen(text) > 0 then
				SendChatMessage(" - "..text, chatType)
			end
		end--]]
	else
		chatFrame:AddMessage(L["No Objectives!"])
	end
	chatFrame.editBox:Hide()
end

--[[----------------------------------------
-- Notes:
-- Sorts the Tracked quests
--
-- Returns:
-- * nothing
------------------------------------------]]

--[[----------------------------------------
-- Notes:
-- Manage Tracked Quest list
--
-- Returns:
-- * nothing
------------------------------------------]]
function beql:ManageQuests()
	local numEntries = GetNumQuestLogEntries()
	local newquestid = 0
	local tinsert = tinsert
	local GetQuestLogTitle = beql.hooks.GetQuestLogTitle or GetQuestLogTitle

	-- cleanup old table
	table.wipe(beql.db.char.questlogids)

	if numEntries ~= 0 then
		for j=numEntries, 1, -1 do
			local questLogTitleText, _, _, _, isHeader, isCollapsed = GetQuestLogTitle(j)
			if isHeader and not beql.cHeader[questLogTitleText] then
				beql.cHeader[questLogTitleText] = isCollapsed or 0
				if isCollapsed then
					ExpandQuestHeader(j)
				end
			end
		end

		numEntries = GetNumQuestLogEntries()

		for j=1, numEntries, 1 do

			local UniqeID = select(9,GetQuestLogTitle(j))
			if UniqeID ~= 0 then
				tinsert(beql.db.char.questlogids, UniqeID, j)
				if not beql.uID_2_index[UniqeID] then
					if newquestid == 0 then
						newquestid = UniqeID;
					elseif newquestid ~= 0 and newquestid ~= -1 then
						newquestid = -1;
					end
				end
			end
		end
	end

	-- quest timers
	table.wipe(beql.questtimers);
	local questtimers = { GetQuestTimers() };
	
	for i=1, #questtimers do	
		local questindex = GetQuestIndexForTimer(i);
		local uid = select(9, GetQuestLogTitle(questindex));
		if (not beql.db.global.questtimes[uid]) or beql.db.global.questtimes[uid] < questtimers[i] then
			print('new timer - uid: ' .. tostring(uid) .. ' time: ' .. tostring(questtimers[i]));
			beql.db.global.questtimes[uid] = questtimers[i];
		end
		tinsert(beql.questtimers, uid, i) -- add timerindex 
	end
	
	table.wipe(beql.uID_2_index)
	for k, v in pairs(beql.db.char.questlogids) do
		tinsert(beql.uID_2_index, k, v)
	end

	-- found a new quest
	if newquestid > 0 then
		beql.db.char.newquestid = newquestid;
	end
end

--[[----------------------------------------
-- Arguments:
-- table - Color1
-- table - Color2
-- number - Have
-- number - Needed
--
-- Notes:
-- Fades Colors between Color1 and Color2 depending on how much percent has Have from Needed
--
-- Returns:
-- * table - Color Faded
------------------------------------------]]
function beql:FadeColors(tempColor, tempColor2, done, obj)
	local color = {r=0, g=0, b=0}
	local multiplier

	multiplier = (done / obj)
	color.r = tempColor.r + ((tempColor2.r - tempColor.r)*multiplier)
	color.g = tempColor.g + ((tempColor2.g - tempColor.g)*multiplier)
	color.b = tempColor.b + ((tempColor2.b - tempColor.b)*multiplier)

	return color

end

--[[----------------------------------------
-- Arguments:
-- number - Decimal nr
-- number - Length of number
--
-- Notes:
-- Converts a Decimal Number to Hexadecimal
--
-- Returns:
-- string - Hexadecimal number
------------------------------------------]]
function beql:decToHex(Dec, Length)
	local B, K, Hex, I, D = 16, "0123456789ABCDEF", "", 0;
	while Dec>0 do
		I=I+1;
		Dec, D = math.floor(Dec/B), math.fmod(Dec,B)+1;
		Hex=string.sub(K,D,D)..Hex;
	end
	if( (Length ~= nil) and (string.len(Hex) < Length) ) then
		local temp, i = Length-string.len(Hex), 1;
		for i=1, temp, 1 do
			Hex = "0"..Hex;
		end
	end
	return Hex;
end

--[[----------------------------------------
-- Arguments:
-- string - text
-- number - Red Component
-- number - Green Component
-- number - Blue Component
--
-- Notes:
-- Returns a WoW-style colored text
--
-- Returns:
-- string - Text colored with WoW control characters
------------------------------------------]]
function beql:ColorText(t, r, g, b)
	if ( t == nil ) then t = ""; end
	if ( r == nil ) then r = 0.0; end
	if ( g == nil ) then g = 0.0; end
	if ( b == nil ) then b = 0.0; end
	return "|CFF"..beql:decToHex(r*255, 2)..beql:decToHex(g*255, 2)..beql:decToHex(b*255, 2)..t.."|r";
end

--[[---------------------------------------
-- Arguments:
-- string - text
--
-- Notes:
-- Prints all Points of a Region
--
-- Returns:
-- nothing

-- function to ge points of an region
-- #NODOC
-----------------------------------------]]
function beql:printpoints(tmp)
	local region
	if type(tmp) == 'string' then
		region = getglobal(tmp)
	else
		region = tmp
	end
	local i

	print("Framepoints for " .. tostring(region:GetName()))
	for i=1, region:GetNumPoints(),1 do
		local point, relativeTo, relativePoint, xOfs, yOfs = region:GetPoint(i)
		beql:debugprint(point .. " " .. relativeTo:GetName() .. " " .. relativePoint .. " " ..  xOfs .." ".. yOfs)
	end
end

function beql:round(input, places)
	if not places then
			places = 0
	end
	if type(input) == "number" and type(places) == "number" then
			local pow = 1
			for i = 1, ceil(places) do
					pow = pow * 10
			end
			return floor(input * pow + 0.5) / pow
	end
end

function beql:WatchFrameLine_Reset(line)
	-- org code
	line:ClearAllPoints();
	line.text:SetText("");
	line.text:SetTextColor(0.8, 0.8, 0.8);
	line.text:Show();
	line.dash:SetText(nil);
	line.dash:Show();
	line:SetHeight(WATCHFRAME_LINEHEIGHT);
	line.text:SetHeight(0);	
	line.criteriaID = nil;	

	-- mod start
	line.mapButton:Hide();
	line.isHeader = nil;
	line.type = nil;
	line.statusBar:Hide();
	line.text:SetWidth(0)
	line.mouseover:SetFrameLevel(1);
	line.dash:SetWidth(0);
	line.mouseover:ClearAllPoints();
	line.mouseover:SetPoint("TOPLEFT", line.text)
	line.mouseover:SetPoint("BOTTOMLEFT", line.text)
	line.iconframe:Hide();
	line.iconframe.aID = nil;
	line.qID = nil;
	line.aID = nil;
	line.subaID = nil;
	line.cType = nil
	line.hasItem = nil
end

function beql:WatchFrameLine_OnUpdate(elapsed)
--[[	self.updateTime = (self.updateTime or 0.2) - elapsed;
	
	if self.updateTime > 0 then
		return
	end
	
	self.updateTime = 0.2; --]]
	
	if self:IsMouseOver() then
		local line = self:GetParent()
		if line.type == 'q' and GetMouseFocus() == beqlQuestWatchFrame then
			beqlQuestWatchFrame.qID = line.qID
			beqlQuestWatchFrame.lastIdUpdate = GetTime() + .2
		elseif line.type == 'a' and GetMouseFocus() == beqlAchievementWatchFrame then
			beqlAchievementWatchFrame.aID = line.aID
			beqlAchievementWatchFrame.subaID = line.subaID
			if self.IsIcon then
				beqlAchievementWatchFrame.IsIcon = true
			else
				beqlAchievementWatchFrame.IsIcon = nil
			end
			beqlAchievementWatchFrame.lastIdUpdate = GetTime() + .2
		end
	end
end

function beql:RefreshConfig()
	beql:Disable()
	
	beqlQuestLogFrameAnchor.UpdateFrame = nil
	beqlQuestWatchAnchor.UpdateFrame = nil
	beqlAchievementWatchAnchor.UpdateFrame = nil
	
	if beql.db.profile.AddonStatus then
		beql:Enable()
	end
end

function beql:TrackerFrame_OnMouseDown(button)
	-- handel mouse down events, save time of the click
	if button == "LeftButton" then
		self.leftclicktime = GetTime()
	elseif button == "RightButton" then
		self.rightclicktime = GetTime()
	end
end

--[[---------------------------------------
-- Arguments:
-- none
--
-- Notes:
-- Adds scripts to our Fremes, which where created in frames.xml
--
-- Returns:
-- nothing

-- #NODOC
-----------------------------------------]]
function beql:AddFrameScripts()
	-- OnUpdate functions
	
	-- Anchor Frame for Questlog
	beqlQuestLogFrameAnchor:SetScript('OnUpdate', function(self, elapsed)
		if self.UIScale ~= UIParent:GetScale() then
			beql:RestoreFramePosition(self)
		end
		if not self.UpdateFrame then
			self.UpdateFrame = beql:QuestLog_UpdateFrame()
		end
	end)
	
	-- Anchor Frame for QuestTracker
	beqlQuestWatchAnchor:SetScript('OnUpdate', beql.QuestWatchAnchor_OnUpdate)

	-- QuesttrackerFrame itself
	beqlQuestWatchFrame:SetScript('OnUpdate', beql.QuestTracker_OnUpdate)
	
	-- ToDo Watchframline virtual template script dispatcher (OnUpdate)
	
	-- OnClick functions
	
	-- QuestLog Config Button
	beqlQuestLogFrameConfigButton:SetScript('OnClick', function(self, button, pushed)
		beql:OpenBlizzardOption("main");
	end)
	
	-- QuestLog Ninimize Button
	beqlQuestLogFrameMinimizeButton:SetScript('OnClick', function(self, button, pushed)
		if beql.db.char.QuestLogMinimized then
			beql:QuestLog_Maximize(self)
		else
			beql:QuestLog_Minimize(self)
		end
	end)
	
	-- Questlog Toggle all Header Button
	beqlQuestLogCollapseAllButton:SetScript('OnClick', function(self, button, pushed)
		local status
		if self.collapsed then
			status = 0
			self.collapsed = nil
		else
			status = 1
			self.collapsed = true
			QuestLog_SetSelection(0);
		end

		for k in pairs(beql.cHeader) do
			beql.cHeader[k] = status
		end

		if beql.db.char.QuestLogMinimized then
			beql:QuestLog_Minimize()
		else
			beql:QuestLog_Maximize()
		end
		QuestLog_Update()
	end)

	-- Quest Tracker Miniminze Button
	beqlQuestWatchFrameTitleMinimize:SetScript('OnClick', function(self, button, pushed)
		if beql.db.char.QuestWatchMinimized then
			beql:QuestTracker_TrackerMaximize()
		else
			beql:QuestTracker_TrackerMinimize()
		end
	end)
	
	-- QuestHistory Button
	-- ToDo beqlQuestHistoryButton:SetScript('OnClick', beql.Browser_Toggle)
	
	-- ToDo Watchframline virtual template script dispatcher (OnClick)
	
	-- OnDrag Functions
	-- Quest Tracker Frame
	beqlQuestWatchFrame:SetScript('OnDragStart', function()
		local anchor = beqlQuestWatchAnchor
		if anchor:IsMovable() then
			anchor.ismoving = true;
			anchor:StartMoving();
		end
	end)
	
	-- Quest Tracker Frame Title
	beqlQuestWatchFrameTitle:SetScript('OnDragStart', function()
		local anchor = beqlQuestWatchAnchor
		if anchor:IsMovable() then
			anchor.ismoving = true;
			anchor:StartMoving();
		end
	end)
	
	-- Quest Tracker Frame
	beqlQuestWatchFrame:SetScript('OnDragStop', function()
		local anchor = beqlQuestWatchAnchor
		anchor.ismoving = false
		anchor:StopMovingOrSizing()
		beql:SaveFramePosition(anchor)
	end)
	
	-- Quest Tracker Frame Title
	beqlQuestWatchFrameTitle:SetScript('OnDragStop', function()
		local anchor = beqlQuestWatchAnchor
		anchor.ismoving = false
		anchor:StopMovingOrSizing()
		beql:SaveFramePosition(anchor)
	end)
	
	-- QuestLogFrame
	QuestLogFrame:SetScript("OnDragStart",function(self)
		if beqlQuestLogFrameAnchor:IsMovable() then
			beqlQuestLogFrameAnchor.ismoving = true;
			beqlQuestLogFrameAnchor:StartMoving();
		end
	end)
	QuestLogFrame:SetScript("OnDragStop",function(self)
		if beqlQuestLogFrameAnchor:IsMovable() then
			beqlQuestLogFrameAnchor:StopMovingOrSizing();
			beqlQuestLogFrameAnchor.ismoving = false;
			beql:SaveFramePosition(beqlQuestLogFrameAnchor);
		end
	end)
	-- Mouse Events
	
	beqlQuestWatchFrame:SetScript('OnMouseDown', beql.TrackerFrame_OnMouseDown)
	beqlQuestWatchFrame:SetScript('OnMouseUp', beql.QuestTracker_OnMouseUp)
end

--
--- Party Functions
--

function beql:Quixote_Quest_Gained(...)
	local uid = select(2 , ...)
	beql:debugprint('New Quixote Quest: ' .. tostring(uid))
	if beql.db.char.newquestid == uid then
		beql:QuestTracker_QuestGained(...)
		if beql.db.profile.QuestLog.chat.accept then
			beql:Party_Status2Chat(L['Quest Accepted: '] .. select(1, ...))
		end
	end
end

local AbadonedQuestId = 0

function beql:Quixote_Quest_Lost(name, uid)
	if AbadonedQuestId == uid then
		AbadonedQuestId = 0
		return
	end
	if beql.db.profile.QuestLog.chat.delivert then
		beql:Party_Status2Chat(L['Quest finalized: '] .. tostring(name))
	end
end

function beql:Quixote_Quest_Abandoned(name, uid)
	AbadonedQuestId = uid
	if beql.db.profile.QuestLog.chat.abandoned then
		beql:Party_Status2Chat(L['Quest abandoned: '] .. tostring(name))
	end
end


function beql:Quixote_Objective_Update(title, uid, objective, had, numGot, numNeeded, qtype)
	local id = select(2,beqlQ:GetQuestByUid(uid))

	-- add unwatched quest
	if beql.db.profile.QuestTracker.AddUntracked == true and (not IsQuestWatched(id)) then
		AddQuestWatch(id)
	end

	-- print progress to party
	if beql.db.profile.QuestLog.chat.AnnounceQuest then
		local objText

		if qtype == "item" or qtype == "monster" or qtype == "reputation" then
			objText = objective..": "..numGot.."/"..numNeeded
		end
--		text = description..objText
		if beql.db.profile.QuestLog.chat.progress and objText then
			beql:Party_Status2Chat(objText)
		end

		if beql.db.profile.QuestLog.chat.finished and select(7, beqlQ:GetQuestByUid(uid)) == 1 then
			beql:Party_Status2Chat(title .." "..L["Completed!"])
		end
	end
end

function beql:Quixote_Quest_Complete(questname, uid)
	if beql.db.profile.QuestLog.InfoOnQuestCompletion then
		UIErrorsFrame:AddMessage(questname.." "..L["Completed!"], 1.0, 0.8, 0.0, 1.0, UIERRORS_HOLD_TIME)
		if beql.db.profile.QuestLog.InfoSound and beql.db.profile.QuestLog.InfoSound ~= "" then
			PlaySoundFile(beql.db.profile.QuestLog.InfoSound)
		end
	end
end

function beql:Party_Status2Chat(msg)
	if beql.db.profile.QuestLog.chat.AnnounceQuest then
		if beql.db.profile.QuestLog.chat.chattype == "default" then
			if UnitInBattleground("player") then
				SendChatMessage(msg, "BATTLEGROUND")
			elseif GetRealNumRaidMembers() > 0 then
				SendChatMessage(msg, "RAID")
			elseif GetRealNumPartyMembers() > 0 then
				SendChatMessage(msg, "PARTY")
			end
		elseif beql.db.profile.QuestLog.chat.chattype == "group" and GetRealNumPartyMembers() > 0 then
			SendChatMessage(msg, "PARTY")
		elseif beql.db.profile.QuestLog.chat.chattype == "say" then
			SendChatMessage(msg, "SAY")
		end
	end
	--questlog.chat.chattype
	if beql.db.profile.debug and not msg or msg == "" then
		assert(false , "beql:Party_Status2Chat: massage is a '" .. tostring(msg) .. "' value")
	end
end

--[[
function beql:Party_Quest_Gained (event)
	beql:debugprint(event)
	beql:Party_frame_Update()
end

function beql:Party_Quest_Complete (event)
	beql:debugprint(event)
	beql:Party_frame_Update()
end

function beql:Party_Quest_Failed (event)
	beql:debugprint(event)
	beql:Party_frame_Update()
end

function beql:Party_Quest_Lost (event)
	beql:debugprint(event)
	beql:Party_frame_Update()
end

function beql:Party_Objective_Update (event)
	beql:debugprint(event)
	beql:Party_frame_Update()
end

function beql:Party_Update (event)
	beql:debugprint(event)
	beql:Party_frame_Update()
end
--]]

-- EOF ---