---------------------------------------------------------------------------------
--
-- Prat - A framework for World of Warcraft chat mods
--
-- Copyright (C) 2006-2007  Prat Development Team
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to:
--
-- Free Software Foundation, Inc., 
-- 51 Franklin Street, Fifth Floor, 
-- Boston, MA  02110-1301, USA.
--
--
-------------------------------------------------------------------------------



--[[
Name: Prat_Scroll
Revision: $Revision: 26318 $
Author(s): Curney (asml8ed@gmail.com)
           Krtek (krtek4@gmail.com)
Inspired by: idChat2_PlayerNames by Industrial
Website: http://www.wowace.com/files/index.php?path=Prat/
Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#Scroll
SVN: http://svn.wowace.com/wowace/trunk/Prat/
Description: Module for Prat that enables mousewheel scrolling and TheDownLow for chat windows (default=on).
Dependencies: Prat
]]

local L = AceLibrary("AceLocale-2.2"):new("PratScroll")

L:RegisterTranslations("enUS", function() return {
    ["Scroll"] = true,
    ["Chat window scrolling options."] = true,
    ["Enable MouseWheel"] = true,
    ["Toggle MouseWheel support on and off for each chat window."] = true,
    ["Chat%dMouseWheel"] = true,
    ["Toggle MouseWheel support on and off for chat window %d."] = true,
    ["Set MouseWheel Speed"] = true,
    ["Set number of lines mousewheel will scroll."] = true,
    ["Set Ctrl+MouseWheel Speed"] = true,
    ["Set number of lines mousewheel will scroll when ctrl is pressed."] = true,
    ["Enable TheLowDown"] = true,
    ["Toggle jumping to the bottom on and off for each chat window."] = true,
    ["Chat%dLowDown"] = true,
    ["Toggle jumping to the bottom on and off for chat window %d."] = true,
    ["Set TheLowDown Delay"] = true,
    ["Set time to wait before jumping to the bottom of chat windows."] = true,
    ["Toggle"] = true,
    ["Toggle the module on and off."] = true,
     ["MouseWheel_name"] = "Enable MouseWheel",
     ["MouseWheel_desc"] = "Toggle MouseWheel support on and off for each chat window.",
     ["MouseWheel_perframename"] = "Chat%dMouseWheel",
     ["MouseWheel_perframedesc"] = "Toggle MouseWheel support on and off",
     ["normscrollspeed_name"] = "Set MouseWheel Speed",
     ["normscrollspeed_desc"] = "Set number of lines mousewheel will scroll.",
     ["ctrlscrollspeed_name"] = "Set Ctrl+MouseWheel Speed",
     ["ctrlscrollspeed_desc"] = "Set number of lines mousewheel will scroll when ctrl is pressed.",
     ["LowDown_name"] = "Enable TheLowDown",
     ["LowDown_desc"] = "Toggle jumping to the bottom on and off for each chat window.",
     ["LowDown_perframename"] = "Chat%dLowDown",
     ["LowDown_perframedesc"] = "Toggle jumping to the bottom on and off",
     ["lowdowndelay_name"] = "Set TheLowDown Delay",
     ["lowdowndelay_desc"] = "Set time to wait before jumping to the bottom of chat windows.",
} end)

-- L:RegisterTranslations("zhCN", function() return {
-- 	["Scroll"] = "滚动",
-- 	["Chat window scrolling options."] = "聊天窗口滚动选项。",
-- 	["MouseScroll"] = "鼠标滚动",
-- 	["Toggle mousewheel scrolling in chat windows on and off."] = "切换鼠标滚动聊天窗口功能打开与关闭。",
-- 	["Chat%dScrolling"] = "窗口%d滚动",
-- 	["Toggles mouse scrolling on and off for chat window %d."] = "切换聊天窗口 %d 鼠标滚动功能打开与关闭。",
-- 	["Normal ScrollSpeed"] = "滚动速度",
-- 	["Sets number of lines mousewheel will scroll."] = "鼠标滚动时卷动的行数。",
-- 	["Ctrl ScrollSpeed"] = "<Ctrl>滚动速度",
-- 	["Sets number of lines mousewheel will scroll when ctrl is pressed."] = "设置按下<Ctrl>时鼠标滚轮的滚动行数。",
-- 	["Toggle"] = "切换",
-- 	["Toggle the module on and off."] = "切换此模块的打开与关闭",
-- } end)

L:RegisterTranslations("koKR", function() return {
    ["Scroll"] = "스크롤",
    ["Chat window scrolling options."] = "대화창 스크롤에 관한 설정입니다.",
    ["Enable MouseWheel"] = "마우스휠 사용",
    ["Toggle MouseWheel support on and off for each chat window."] = "각각의 대화창에 대한 마우스휠 기능을 사용합니다.",
    ["Chat%dMouseWheel"] = "대화창%d마우스휠",
    ["Toggle MouseWheel support on and off for chat window %d."] = "대화창 %d에 대한 마우스휠 기능을 사용합니다.",
    ["Set MouseWheel Speed"] = "마우스휠 속도 설정",
    ["Set number of lines mousewheel will scroll."] = "스크롤 할 라인 수를 설정합니다.",
    ["Set Ctrl+MouseWheel Speed"] = "CTRL+마우스휠 속도 설정",
    ["Set number of lines mousewheel will scroll when ctrl is pressed."] = "CTRL키를 눌렀을 때 스크롤 할 라인 수를 설정합니다.",
    ["Enable TheLowDown"] = "자동하단 사용",
    ["Toggle jumping to the bottom on and off for each chat window."] = "각각의 대화창에 대한 자동하단 기능을 사용합니다.",
    ["Chat%dLowDown"] = "대화창%d자동하단",
    ["Toggle jumping to the bottom on and off for chat window %d."] = "대화창 %d 에 대한 자동하단 기능을 사용합니다.",
    ["Set TheLowDown Delay"] = "자동하단 지연시간 설정",
    ["Set time to wait before jumping to the bottom of chat windows."] = "대화창의 하단으로 이동할 시간을 설정합니다.",
    ["Toggle"] = "사용",
    ["Toggle the module on and off."] = "기능 사용 여부를 결정합니다.",
    ["MouseWheel_name"] = "마우스휠 사용",
    ["MouseWheel_desc"] = "각각의 대화창에 대한 마우스휠 기능을 사용합니다.",
    ["MouseWheel_perframename"] = "대화창%d마우스휠",
    ["MouseWheel_perframedesc"] = "마우스휠 기능을 사용합니다.",
    ["normscrollspeed_name"] = "마우스휠 속도 설정",
    ["normscrollspeed_desc"] = "스크롤 할 라인 수를 설정합니다.",
    ["ctrlscrollspeed_name"] = "CTRL+마우스휠 속도 설정",
    ["ctrlscrollspeed_desc"] = "CTRL키를 눌렀을 때 스크롤 할 라인 수를 설정합니다.",
    ["LowDown_name"] = "자동하단 사용",
    ["LowDown_desc"] = "각각의 대화창에 대한 자동하단 기능을 사용합니다.",
    ["LowDown_perframename"] = "대화창%d자동하단",
    ["LowDown_perframedesc"] = "자동하단 기능을 사용합니다.",
    ["lowdowndelay_name"] = "자동하단 지연시간 설정",
    ["lowdowndelay_desc"] = "대화창의 하단으로 이동할 시간을 설정합니다.",
} end)

-- L:RegisterTranslations("zhTW", function() return {
--     ["Scroll"] = "滾動",
--     ["Chat window scrolling options."] = "聊天視窗滾動選項。",
--     ["MouseScroll"] = "滑鼠滾動",
--     ["Toggle mousewheel scrolling in chat windows on and off."] = "切換滑鼠滾動聊天視窗功能打開與關閉。",
--     ["Chat%dScrolling"] = "視窗%d滾動",
--     ["Toggles mouse scrolling on and off for chat window %d."] = "切換聊天視窗 %d 滑鼠滾動功能打開與關閉。",
--     ["Normal ScrollSpeed"] = "滾動速度",
--     ["Sets number of lines mousewheel will scroll."] = "視窗滾動時卷動的行數。",
--     ["Ctrl ScrollSpeed"] = "<Ctrl>滾動速度",
--     ["Sets number of lines mousewheel will scroll when ctrl is pressed."] = "設定按下<Ctrl>時視窗滾輪的行數。",
--     ["Toggle"] = "切換",
--     ["Toggle the module on and off."] = "切換打開或關閉此模組。",
-- } end)

L:RegisterTranslations("esES", function() return {
    ["Scroll"] = "Desplazamiento Vertical",
    ["Chat window scrolling options."] = "Opciones de desplazamiento vertical de las ventanas de chat",
    ["Enable MouseWheel"] = "Activar Rueda del Rat\195\179n",
    ["Toggle MouseWheel support on and off for each chat window."] = "Determina si se activa el soporte para la rueda del rat\195\179n en cada ventana de chat",
    ["Chat%dMouseWheel"] = "Rueda de rat\195\179n en Chat %d",
    ["Toggle MouseWheel support on and off for chat window %d."] = "Determina si se activa la rueda del rat\195\179n en la ventana %d",
    ["Set MouseWheel Speed"] = "Velocidad de la rueda del rat\195\179n",
    ["Set number of lines mousewheel will scroll."] = "N\195\186mero de l\195\173neas que la rueda del rat\195\179n desplazar\195\161 verticalmente",
    ["Set Ctrl+MouseWheel Speed"] = "Velocidad de Ctrl+Rueda del Rat\195\179n",
    ["Set number of lines mousewheel will scroll when ctrl is pressed."] = "N\195\186mero de l\195\173neas que la rueda del rat\195\179n desplazar\195\161 verticalmente cuando se presione la tecla Control",
    ["Enable TheLowDown"] = "Saltar Abajo",
    ["Toggle jumping to the bottom on and off for each chat window."] = "Determina si se activa el salto a la parte inferior de cada ventana de chat",
    ["Chat%dLowDown"] = "Salto Abajo en Chat %d",
    ["Toggle jumping to the bottom on and off for chat window %d."] = "Determina si se activa el salto a la parte inferior para la ventana de chat %d",
    ["Set TheLowDown Delay"] = "Retraso de Salto Abajo",
    ["Set time to wait before jumping to the bottom of chat windows."] = "Establece el tiempo tras el que quieres saltar abajo",
    ["Toggle"] = "Activar",
    ["Toggle the module on and off."] = "Activa y desactiva este m\195\179dulo.",
     ["MouseWheel_name"] = "Activar Rueda del Rat\195\179n",
     ["MouseWheel_desc"] = "Determina si se activa el soporte para la rueda del rat\195\179n en cada ventana de chat",
     ["MouseWheel_perframename"] = "Rueda de rat\195\179n en Chat %d",
     ["MouseWheel_perframedesc"] = "Determina si se activa el soporte para la rueda del rat\195\179n",
     ["normscrollspeed_name"] = "Velocidad de la rueda del rat\195\179n",
     ["normscrollspeed_desc"] = "N\195\186mero de l\195\173neas que la rueda del rat\195\179n desplazar\195\161 verticalmente",
     ["ctrlscrollspeed_name"] = "Velocidad de Ctrl+Rueda del Rat\195\179n",
     ["ctrlscrollspeed_desc"] = "N\195\186mero de l\195\173neas que la rueda del rat\195\179n desplazar\195\161 verticalmente cuando se presione la tecla Control",
     ["LowDown_name"] = "Saltar Abajo",
     ["LowDown_desc"] = "Determina si se activa el salto a la parte inferior de cada ventana de chat.",
     ["LowDown_perframename"] = "Salto Abajo en Chat %d",
     ["LowDown_perframedesc"] = "Determina si se activa el salto abajo",
     ["lowdowndelay_name"] = "Retraso de Salto Abajo",
     ["lowdowndelay_desc"] = "Establece el tiempo tras el que quieres saltar abajo",
} end)
 
L:RegisterTranslations("deDE", function() return {
	["Scroll"] = "Scrollen",
	["Chat window scrolling options."] = "Chatfenster Scrollen Optionen",
	["Enable MouseWheel"] = "Aktiviere Mausrad",
	["Toggle MouseWheel support on and off for each chat window."] = "Schaltet Mausrad Unterst\195\188tzung an und aus f\195\188r jedes Chatfenster.",
	["Chat%dMouseWheel"] = "Chat %d Mausrad",
	["Toggle MouseWheel support on and off for chat window %d."] = "Schaltet Mauserad Unterst\195\188tzung an und aus f\195\188r das Chatfenster %d.",
	["Set MouseWheel Speed"] = "Mausrad Geschwindigkeit einstellen",
	["Set number of lines mousewheel will scroll."] = "Stellt die Anzahl an Zeilen ein die mit dem Mausrad gescrollt werden.",
	["Set Ctrl+MouseWheel Speed"] = "Strg+Mausrad Geschwindigkeit einstellen",
	["Set number of lines mousewheel will scroll when ctrl is pressed."] = "stellt ein wieviele Zeilen gescrollt werden wenn Strg gedr\195\188ckt gehalten wird.",
	["Enable TheLowDown"] = "Aktiviere Ganz runter",
	["Toggle jumping to the bottom on and off for each chat window."] = "Schaltet das springen zum Ende des Chattextes an und aus f\195\188r jedes Chatfenster.",
	["Chat%dLowDown"] = "Chat %d Ganz runter",
	["Toggle jumping to the bottom on and off for chat window %d."] = "Schaltet das springen zum Ende an und aus f\195\188r das Chatfenster %d.",
	["Set TheLowDown Delay"] = "Ganz runter verz\195\182gerrung einstellen",
	["Set time to wait before jumping to the bottom of chat windows."] = "Stellt ein nach welcher Zeit der Chattext in den chatfenstern zu seinem Ende springen soll.",
	["Toggle"] = "Einschalten",
	["Toggle the module on and off."] = "Schaltet dieses Modul an und aus",
	["MouseWheel_name"] = "Aktiviere Mausrad",
	["MouseWheel_desc"] = "Schaltet Mausrad Unterst\195\188tzung an und aus f\195\188r jedes Chatfenster.",
	["MouseWheel_perframename"] = "Chat %d Mausrad",
	["MouseWheel_perframedesc"] = "Schaltet Mauserad Unterst\195\188tzung an und aus.",
	["normscrollspeed_name"] = "Mausrad Geschwindigkeit einstellen",
	["normscrollspeed_desc"] = "Stellt die Anzahl an Zeilen ein die mit dem Mausrad gescrollt werden.",
	["ctrlscrollspeed_name"] = "Strg+Mausrad Geschwindigkeit einstellen",
	["ctrlscrollspeed_desc"] = "stellt ein wieviele Zeilen gescrollt werden wenn Strg gedr\195\188ckt gehalten wird.",
	["LowDown_name"] = "Aktiviere Ganz runter",
	["LowDown_desc"] = "Schaltet das springen zum Ende des Chattextes an und aus f\195\188r jedes Chatfenster.",
	["LowDown_perframename"] = "Chat %d Ganz runter",
	["LowDown_perframedesc"] = "Schaltet das springen zum Ende an und aus.",
	["lowdowndelay_name"] = "Ganz runter verz\195\182gerrung einstellen",
	["lowdowndelay_desc"] = "Stellt ein nach welcher Zeit der Chattextin den Chatfenstern zu seinem Ende springen soll.",
} end)

L:RegisterTranslations("frFR", function() return {
    ["Scroll"] = "D\195\169filement",
    ["Chat window scrolling options."] = "Options de d\195\169filement.",
    ["Enable MouseWheel"] = "D\195\169filement avec la molette",
    ["Toggle MouseWheel support on and off for each chat window."] = "Active le d\195\169filement du texte avec la molette.",
    ["Chat%dMouseWheel"] = "Fen\195\170tre %d",
    ["Toggle MouseWheel support on and off for chat window %d."] = "Activer/d\195\169sactiver le support de la molette pour la fenêtre %d.",
    ["Set MouseWheel Speed"] = "Vitesse de d\195\169filement - Molette",
    ["Set number of lines mousewheel will scroll."] = "Règle le nombre de lignes que fait d\195\169filer la molette.",
    ["Set Ctrl+MouseWheel Speed"] = "Vitesse de d\195\169filement - Ctrl+Molette",
    ["Set number of lines mousewheel will scroll when ctrl is pressed."] = "R\195\168gle le nombre de lignes que fait d\195\169filer Ctrl+molette.",
    ["Enable TheLowDown"] = "Retour automatique en bas",
    ["Toggle jumping to the bottom on and off for each chat window."] = "Active/d\195\169sactive le retour automatique en bas de la fen\195\170tre au bout d'un d\195\169lai.",
    ["Chat%dLowDown"] = "Fen\195\170tre %d",
    ["Toggle jumping to the bottom on and off for chat window %d."] = "Active/d\195\169sactive le retour automatique en bas de la fen\195\170tre au bout d'un d\195\169lai pour la fen\195\170tre %d.",
    ["Set TheLowDown Delay"] = "D\195\169lai de retour automatique",
    ["Set time to wait before jumping to the bottom of chat windows."] = "R\195\168gle le d\195\169lai avant de revenir en bas de la fen\195\170tre.",
    ["Toggle"] = "Activer/d\195\169sactiver",
    ["Toggle the module on and off."] = "Active/d\195\169sactive le module.",
     ["MouseWheel_name"] = "D\195\169filement avec la molette",
     ["MouseWheel_desc"] = "Active le d\195\169filement du texte avec la molette.",
     ["MouseWheel_perframename"] = "Fen\195\170tre %d",
     ["MouseWheel_perframedesc"] = "Activer/d\195\169sactiver le support de la molette.",
     ["LowDown_name"] = "Retour automatique en bas",
     ["LowDown_desc"] = "Active/d\195\169sactive le retour automatique en bas de la fen\195\170tre au bout d'un d\195\169lai pour chaque fen\195\170tre.",
     ["LowDown_perframename"] = "Fen\195\170tre %d",
     ["LowDown_perframedesc"] = "Active/d\195\169sactive le retour automatique en bas de la fen\195\170tre au bout d'un d\195\169lai.",
} end)

Prat_Scroll = Prat:NewModule(Prat:RequestModuleName("PratScroll"))

-- Prat categories relevant to this module. list at: http://groups.google.com/group/wow-prat/web/prat-categories
local cat = Prat.Categories
Prat_Scroll.Categories	= { cat.FRAME, cat.BEHAVIOR }	-- eg { cat.TEXT, cat.INFO }

Prat_Scroll.defaultDB = {
        on = true,
        MouseWheel = {true, true, true, true, true, true, true},
        normscrollspeed = 1,
        ctrlscrollspeed = 3,
        LowDown = {true, true, true, true, true, true, true},
        lowdowndelay = 20,       
}

Prat_Scroll.moduleOptions = {}
Prat_Scroll.toggleOptions = { MouseWheel_handler={}, LowDown_handler = {} }

function Prat_Scroll:GetModuleOptions()
    self.moduleOptions = {
        name = L["Scroll"],
        desc = L["Chat window scrolling options."],
        type = "group",
        args = {
 
            mousewheelspeed = {
                name = L["Set MouseWheel Speed"],
                desc = L["Set number of lines mousewheel will scroll."],
                type = "range",
                order = 180,
                get = function() return self.db.profile.normscrollspeed end,
                set = function(v) self.db.profile.normscrollspeed = v end,
                min = 1,
                max = 21,
                step = 1,
            },
            ctrlmousewheelspeed = {
                name = L["Set Ctrl+MouseWheel Speed"],
                desc = L["Set number of lines mousewheel will scroll when ctrl is pressed."],
                type = "range",
                order = 190,
                get = function() return self.db.profile.ctrlscrollspeed end,
                set = function(v) self.db.profile.ctrlscrollspeed = v end,
                min = 3,
                max = 21,
                step = 3,
            },

            lowdowndelay = {
                name = L["Set TheLowDown Delay"],
                desc = L["Set time to wait before jumping to the bottom of chat windows."],
                type = "range",
                order = 210,
                get = function() return self.db.profile.lowdowndelay end,
                set = function(v) self.db.profile.lowdowndelay = v end,
                min = 1,
                max = 60,
                step = 1,
            },

        }
    }
      	return self.moduleOptions
end


function Prat_Scroll:OnModuleEnable()
    for i = 1,NUM_CHAT_WINDOWS do
        self:MouseWheel(i,self.db.profile.MouseWheel[i])
       	self:LowDown(i,self.db.profile.LowDown[i])
    end
end

function Prat_Scroll:OnModuleDisable()
    for i = 1,NUM_CHAT_WINDOWS do
        self:MouseWheel(i,false)
       	self:LowDown(i,false)
    end
end

function Prat_Scroll:MouseWheel(id, enabled)
    self:Debug(id, enabled)
    local cf = getglobal("ChatFrame"..id)
    if enabled then
        cf:SetScript("OnMouseWheel", function()
            if (arg1 > 0) then
                if IsShiftKeyDown() then
                    cf:ScrollToTop()
                else
                    if IsControlKeyDown() then
                        for i = 1,self.db.profile.ctrlscrollspeed do
                            cf:ScrollUp()
                        end
                    else
                        for i = 1,self.db.profile.normscrollspeed do
                            cf:ScrollUp()
                        end
                    end
                end
            elseif (arg1 < 0) then
                if IsShiftKeyDown() then
                    cf:ScrollToBottom()
                else
                    if IsControlKeyDown() then
                        for i = 1,self.db.profile.ctrlscrollspeed do
                            cf:ScrollDown()
                        end
                    else
                        for i = 1,self.db.profile.normscrollspeed do
                            cf:ScrollDown()
                        end
                    end
                end
            end
        end)
        cf:EnableMouseWheel(true)
    else
        cf:SetScript("OnMouseWheel", nil)
        cf:EnableMouseWheel(false)
    end
end

function Prat_Scroll:LowDown(id, enabled)
    self:Debug(id, enabled)

	local name = "ChatFrame"..id
  local cf = getglobal(name)
	local funcs = {"ScrollUp", "ScrollDown", "ScrollToTop", "PageUp", "PageDown"}

  if enabled then
		for _,func in ipairs(funcs) do
			local f = function(cf)
				if self:IsEventScheduled(name.."DownTimeout") then self:CancelScheduledEvent(name.."DownTimeout") end
				self:ScheduleEvent(name.."DownTimeout", self.ResetFrame, self.db.profile.lowdowndelay, self, name)
			end
			self:SecureHook(cf, func, f)
		end
	else
		for _,func in ipairs(funcs) do
			if self:IsHooked(cf, func) then self:Unhook(cf, func) end
		end
	end
end

function Prat_Scroll:ResetFrame(name)
	local cf = getglobal(name)
	if not cf:AtBottom() then
		cf:ScrollToBottom()
	end
end