WoWInterface SVN GuildLottery

[/] [GLottery.lua] - Rev 2

Compare with Previous | Blame | View Log

GL = {}
GL.Me = ""
GL.Command = "Lottery"
GL.Command2 = "Lotterie"
GL.Command3 = "Raffle"
GL.WhisperHistory = {}
GL.WinningTicket=0
GL.WinningRaffleTicket1=0
GL.WinningRaffleTicket2=0
GL.WinningRaffleTicket3=0
GL.RaffleItem1='-1'
GL.RaffleItem2='-1'
GL.RaffleItem3='-1'
GL.WinningEvent=-1

GL.WinningPercentage=100
GL.SendingWhisper=false

GL.CommandQueue = {}
GL.SpamQueue = {}

GL.OnOpenEvent = nil
GL.OnPendingEvent = nil
GL.OnOpenEventData = nil
GL.OnPendingEventData = nil

GL_Settings = {}
GL_Settings.MinimapRadiusOffset = 80
GL_Settings.MinimapArcOffset = 343
GL_Settings.MinimapTexture = "Spell_Nature_RavenForm"
GL_Settings.MinimapTextureId = 1
GL_Settings.ShowMinimap = 1
GL_Settings.UseLotteryAnnouncement = 1
GL_Settings.UseWinnerAnnouncement = 1
GL_Settings.Tooltips = 1
GL_Settings.GuaranteedWinner = 0
GL_Settings.AllowInvalidItems = 0
GL_Settings.Channel = 1

GL_Settings.Debuglevel = 0

GuildLottery = LibStub("AceAddon-3.0"):NewAddon("Guild Lottery", "AceConsole-3.0", "AceEvent-3.0", "AceTimer-3.0")

local L = LibStub("AceLocale-3.0"):GetLocale("Glottery")

GL_GCHAT = "<<Guild Lottery>> "

GL_Icons = {
"Spell_Nature_RavenForm","Ability_Hunter_AspectOfTheMonkey","Ability_Mount_JungleTiger","Ability_Mount_WhiteTiger","Ability_Mount_PinkTiger","Spell_Nature_ProtectionformNature","Ability_Hunter_RunningShot","Ability_EyesOfTheOwl","Ability_Whirlwind",
"Shadow_RagingScream","Spell_Fire_FireArmor","Shadow_SacrificialShield","Shadow_DemonBreath","Shadow_EvilEye","Shadow_Twilight","Shadow_DetectLesserInvisibility","Shadow_PsychicScream","Shadow_AntiShadow","Shadow_ShadowPact","Shadow_DetectInvisibility","Shadow_GatherShadows",
"Shadow_DetectInvisibility","Shadow_Shadowform","Shadow_AntiShadow","Shadow_DeadofNight","Spell_Holy_WordFortitude","Spell_Holy_PrayerOfFortitude","Spell_Holy_PowerWordShield","Spell_Holy_Renew","Shadow_ShadowWordDominate","Spell_Holy_InnerFire","Spell_Frost_WindWalkOn","Shadow_Requiem","Spell_Magic_LesserInvisibility",
"Shadow_Raisedead","Shadow_UnsummonBuilding","Spell_Magic_LesserInvisibilty","Spell_Holy_PowerInfusion","Spell_Holy_GreaterHeal","Spell_Lightning_LightningBolt01","Spell_Holy_Excorcism","Spell_Holy_Restoration","Spell_Holy_HolyProtection","Spell_Holy_Heal","Spell_Holy_BlessingOfAgility","Spell_Holy_ArcaneIntellect",
"Spell_Holy_MagicalSentry","Spell_Frost_FrostArmor02","Shadow_DetectLesserInvisibility","Spell_Fire_FireArmor","Spell_Frost_Frost","Spell_Ice_Lament","Spell_Frost_FrostWard","Spell_MageArmor","Shadow_ManaBurn","Spell_Nature_EnchantArmor","Spell_Fire_SealOfFire","Spell_Arcane_TeleportOrgrimmar",
"Shadow_RagingScream","Shadow_SoulGem","Spell_Nature_AbolishMagic","Spell_Holy_FlashHeal","Spell_Nature_Regeneration","Spell_Nature_Rejuvenation","Spell_Nature_NaturesBlessing","Spell_Nature_Thorns","Spell_Nature_Ravenform","Spell_Nature_SpiritWolf","Spell_Nature_StoneSkinTotem","Spell_Nature_Swiftness",
"Spell_Nature_P","Spell_Nature_ResistNature","Spell_Nature_LightningShield","Racial_Troll_Berserk","Spell_Nature_LightningShield","Spell_Magic_MageArmor","Spell_MiscFood","Ability_Mount_BlackDireWolf","Ability_Mount_WhiteDireWolf","Ability_Mount_Kodo_01","Ability_Mount_Kodo_03","Ability_Mount_Raptor",
"Ability_Mount_Undeadhorse","Ability_Mount_Dreadsteed","Ability_Rogue_Sprint","Ability_Druid_CatForm","Ability_Ambush","Ability_Mount_JungleTiger","Ability_Druid_Dash","Ability_Warrior_DefensiveStance","Ability_TrueShot","Spell_INV_Jewelry_Talisman_07","Spell_INV_Potion_44","Spell_INV_Potion_58",
"Spell_INV_Potion_65","Spell_INV_Potion_92","Spell_INV_Potion_93","Spell_INV_Drink_07","Spell_INV_Drink_18","Spell_INV_Misc_Fork&Knive","Spell_Nature_TimeStop","Spell_Holy_DivineIntervention","Ability_Warrior_InnerRage","Spell_Holy_HealingAura","Spell_Holy_RighteousnessAura","Spell_Holy_HolySmite","Ability_ThunderBolt",
"Spell_Holy_SealOfWrath","Spell_Holy_FistOfJustice","Spell_Holy_SealOfWisdom","Spell_Holy_SealOfSalvation","Spell_Holy_PrayerOfHealing02","Spell_Holy_SealOfValor","Spell_Holy_SealOfProtection","Spell_Holy_GreaterBlessingofKings","Spell_Holy_GreaterBlessingofWisdom","Spell_Holy_GreaterBlessingofSalvation",
"Spell_Holy_GreaterBlessingofLight","Ability_Warrior_BattleShout","Shadow_Teleport","Ability_Hunter_BeastTraining","Ability_Hunter_MendPet","Ability_Druid_Dash","Ability_Druid_SupriseAttack","Shadow_ImpPhaseShift","Shadow_LifeDrain","Shadow_AntiShadow",
"Spell_Magic_LesserInvisibility","Shadow_GatherShadows","Spell_Holy_DevotionAura","Spell_Holy_AuraOfLight","Spell_Holy_MindSooth","Shadow_SealOfKings","Spell_Holy_MindVision","Spell_Frost_WizardMark","Spell_Fire_SealOfFire","Shadow_BloodBoil","Shadow_AuraOfDarkness","Spell_Frost_Stun",
"Ability_Hunter_SniperShot","Ability_Rogue_Trip","Ability_Hunter_Quickshot","Ability_Hunter_CriticalShot","Ability_Hunter_AimedShot","Ability_GolemStormBolt","Ability_GolemStormBolt","Spell_Frost_ChainsOfIce","Spell_Frost_FreezingBreath","Spell_Fire_FlameShock","Spell_Fire_SelfDestruct","Spell_Holy_Dizzy","Spell_Nature_Polymorph",
"Spell_Frost_FrostBolt02","Spell_Frost_FrostNova","Spell_Frost_FrostArmor","Spell_Fire_SoulBurn","Shadow_AbominationExplosion","Spell_Fire_Immolation","Shadow_Requiem","Shadow_LifeDrain02","Shadow_Haunting","Shadow_SiphonMana","Shadow_CurseOfSargeras","Shadow_CurseOfMannoroth","Shadow_CurseOfAchimonde",
"Shadow_ChillTouch","Shadow_AuraOfDarkness","Shadow_CurseOfTounges","Shadow_UnholyStrength","Shadow_GrimWard","Shadow_ShadowBolt","Shadow_Possession","Shadow_EnslaveDemon","Shadow_MindSteal *","Shadow_LifeDrain","Shadow_MindRot","Shadow_DeathScream","Shadow_DeathCoil","Ability_Gouge","Spell_Nature_ThunderClap","Shadow_DeathScream",
"Ability_ShockWave","Spell_Frost_Stun","Spell_Frost_Stun","Spell_Frost_Stun","Ability_Warrior_WarCry","Ability_GolemThunderClap","Ability_Warrior_Sunder","Spell_Holy_AshesToAshes","Shadow_PsychicScream","Spell_Nature_Slow","Ability_Druid_Disembowel","Spell_Nature_StarFall","Spell_Nature_FaerieFire","Spell_Nature_Sleep","Spell_Nature_InsectSwarm",
"Ability_Gouge","Ability_Rogue_Garrote","Shadow_MindSteal *","Ability_Rogue_Rupture","Ability_CheapShot","Ability_Sap","Ability_Warrior_Riposte","Shadow_LifeDrain","Ability_Rogue_KidneyShot","Spell_Frost_FrostShock","Shadow_DeathScream","Shadow_ShadowWordPain","Shadow_BlackPlague","Shadow_AbonimationExplosion","Shadow_CurseOfSargeras",
"Fire_FlameBolt","Fire_Fireball02","Frost_Stun","Frost_ChainsOfIce","Nature_StrangleVines","Nature_Starfall","Spell_Holy_SearingLight","Ability_BackStab","Ability_ShockWave","Ability_Vanish","Ability_Warrior_SavageBlow","Misc_Bandage_08"
}


-- MenuItem related
GL_MENUBUTTONSIZEY = 16
g_MenuItemSelected = 0
--

-- Raffle Constants
GL_LOTTERY = 0
GL_RAFFLE = 1
--

-- Channel Constants
GL_CHANNEL_GUILD = 1
GL_CHANNEL_RAID = 2

--
local GL_ANSWER_YES = L["UI_YES"]
local GL_ANSWER_NO = L["UI_NO"]

local Orig_ChatFrame_OnEvent=nil
local Orig_ChatEdit_InsertLink=nil

GL_VERSION_TEXT = GetAddOnMetadata("Glottery", "Version")

local RED     = "|cffff0000"
local GREEN   = "|cff00ff00"
local BLUE    = "|cff0000ff"
local MAGENTA = "|cffff00ff"
local YELLOW  = "|cffffff00"
local CYAN    = "|cff00ffff"
local WHITE   = "|cffffffff"

function GuildLottery:Color( color, text )
        if color==nil then color=WHITE; end
        local coloredtext=color..text.."|r"
        return coloredtext
end

function GuildLottery:SlashHandler(msg)
        local argv = {}
        for arg in string.gmatch(string.lower(msg), '[%a%d%-%.]+') do
                table.insert(argv, arg)
        end
        if argv[1] == "toggle" then
                GuildLottery:Toggle(0)
        elseif argv[1] == "spam" then
                if argv[2] == "raffle" then
                        GuildLottery:SpamClick(GL_RAFFLE)
                elseif argv[2] == "lottery" then
                        GuildLottery:SpamClick(GL_LOTTERY)
                else
                        GuildLottery:Error(L["ERR_UNKNOWNCMD"])
                end
--      elseif argv[1] == "sell" then

        elseif argv[1] == "roll" then
                GuildLottery:StartRollClick()
        else
                if argv[1]==nil then
                        GuildLottery:Help()
                else
                        GuildLottery:Error(L["ERR_UNKNOWNCMD"])
                end
        end
end

function GuildLottery:Error( txt )
        GuildLottery:Print(GuildLottery:Color(RED,txt))
end

function GuildLottery:OnInitialize()
  -- Code that you want to run when the addon is first loaded goes here.

  GuildLottery:RegisterChatCommand("glottery", "SlashHandler")
  GuildLottery:RegisterChatCommand("glot", "SlashHandler")
  
  GLTooltipCheckBox:SetChecked(GL_Settings.Tooltips)
  GLInvalidItemsCheckBox:SetChecked(GL_Settings.AllowInvalidItems)

  GLCheckBoxLotteryAnnouncement:SetChecked(GL_Settings.UseLotteryAnnouncement)
  GLCheckBoxWinnerAnnouncement:SetChecked(GL_Settings.UseWinnerAnnouncement)

  GLTitleText:SetText(L["UI_TITLE_LOTTERY"])

  
        GuildLottery:MinimapButton_Update()
        GL_DataInitialize()

        if GL_Settings.Debuglevel == nil then
                GL_Settings.Debuglevel=0
        end


        GuildLottery:InitUIText()

        GuildLottery:UpdateScreen()
        GuildLottery:UpdateUserButtons()
        
        
        MoneyInputFrame_SetOnValueChangedFunc(GLStartGoldFrame,function() GuildLottery:OnMoneyChanged(GLStartGoldFrame) end)
        MoneyInputFrame_SetOnValueChangedFunc(GLLotteryTicketPriceFrame, function() GuildLottery:OnMoneyChanged(GLLotteryTicketPriceFrame) end)
        MoneyInputFrame_SetOnValueChangedFunc(GLRaffleTicketPriceFrame, function() GuildLottery:OnMoneyChanged(GLRaffleTicketPriceFrame) end)

        GLJackPotFrameGold:SetTextColor(0.5,0.5,0.5)
        GLJackPotFrameSilver:SetTextColor(0.5,0.5,0.5)
        GLJackPotFrameGold:EnableMouse(0)
        GLJackPotFrameSilver:EnableMouse(0)

        GuildLottery:Print("Initialized")
  
end

function GuildLottery:Help()
    GL_printf(GuildLottery:Color(GREEN,L["UI_TITLE_LOTTERY"].." "..L["HLP"]))
    GL_printf(GuildLottery:Color(GREEN,"----------------------------------"))
    GL_printf("/glot "..GuildLottery:Color(YELLOW,"toggle").." - "..L["HLP_TOGGLE"])
    GL_printf("/glot "..GuildLottery:Color(YELLOW,"spam [lottery | raffle]").." - "..L["HLP_SPAM"])
    GL_printf("/glot "..GuildLottery:Color(YELLOW,"roll [lottery | raffle]").." - "..L["HLP_ROLL"])
end

--[[
local GL_EventDelta=0
function GuildLottery:OnGlobalUpdate(delta)
        if #GL.CommandQueue > 0 then
                GL_RunCommand()
        end     
end
--]]
function GuildLottery:string( string )
        if string==nil then
                string="nil"
        end
        return string
end

--
--   Event Handlers
--

function GuildLottery:CHAT_EVENT_HANDLER(eventName, arg1, arg2)
        GL_debug("GLottery: event "..eventName)
        local text=strupper(arg1)

        if string.find(text,"^"..GL.Command.."$") or string.find(text,"^"..GL.Command2.."$")then
                        GuildLottery:SendInfo(arg2, 0)
        end
        if string.find(text,"^"..GL.Command3.."$") then
                        GuildLottery:SendInfo(arg2, 1)
        end

        if string.find(text,"^"..GL.Command.." %d+$") then
                        local ticketno=string.gsub(text,"^"..GL.Command.." (%d+)$","%1")
                        GuildLottery:SendTicketOwnerOf(arg2,ticketno)
        end
        if string.find(text,"^"..GL.Command2.." %d+$") then
                        local ticketno=string.gsub(text,"^"..GL.Command2.." (%d+)$","%1")
                        GuildLottery:SendTicketOwnerOf(arg2,ticketno)
        end
        if string.find(text,"^"..GL.Command.." HELP$") then
                GuildLottery:SendHelp(arg2)
        end
        if string.find(text,"^"..GL.Command2.." HELP$") then
                GuildLottery:SendHelp(arg2)
        end
end

function GuildLottery:CALENDAR_OPEN_EVENT()
        if (GL.OnOpenEvent~=nil) then
                local func = GL.OnOpenEvent
                GL.OnOpenEvent = nil
                func()
        end
end

function GuildLottery:CALENDAR_ACTION_PENDING()
        if (GL.OnPendingEvent~=nil) then
                if GL.PendingEventToSkip~= nil then
                        if (GL.PendingEventToSkip==0) then
                                local func = GL.OnPendingEvent
                                GL.OnPendingEvent=nil
                                func()
                        else
                                GL.PendingEventToSkip=GL.PendingEventToSkip-1
                        end
                else
                        local func = GL.OnPendingEvent
                        GL.OnPendingEvent=nil
                        func()
                end
        end
end

function GuildLottery:GUILD_ROSTER_UPDATE()
                -- check if ppl came online who need to be notified still
                GuildLottery:CheckNotifications()
end

Orig_ChatEdit_InsertLink = ChatEdit_InsertLink

function ChatEdit_InsertLink(text)
  if text and GLRaffleItemOneEditBox:HasFocus() then
    GLRaffleItemOneEditBox:SetText(text)
    GLRaffleItemOneEditBox:SetCursorPosition(0)
return true
  elseif text and GLRaffleItemTwoEditBox:HasFocus() then
    GLRaffleItemTwoEditBox:SetText(text)
    GLRaffleItemTwoEditBox:SetCursorPosition(0)
    return true
  elseif text and GLRaffleItemThreeEditBox:HasFocus() then
    GLRaffleItemThreeEditBox:SetText(text)
    GLRaffleItemThreeEditBox:SetCursorPosition(0)
    return true
  else
    Orig_ChatEdit_InsertLink(text)
  end
end

Orig_ChatFrame_OnEvent = ChatFrame_OnEvent
function GL_ChatFrame_OnEvent(self, event, ...)
        local arg1, arg2 = ...
        if event=="CHAT_MSG_WHISPER_INFORM" then
                if GuildLottery:IsGLWhisper(arg1,arg2) then
                        return
                end
        end     
        if event=="CHAT_MSG_WHISPER" then
                local whisp=string.upper(arg1)
                if string.find(whisp,"^"..GL.Command.." %w+$") or string.find(whisp,"^"..GL.Command.."$") then
                        return
                end
                if string.find(whisp,"^"..GL.Command2.." %w+$") or string.find(whisp,"^"..GL.Command2.."$") then
                        return
                end
        end     
        if event=="CHAT_MSG_SYSTEM" then
                local errmsg=string.gsub(ERR_CHAT_PLAYER_NOT_FOUND_S,"%%s","(%%w+)")
                if string.match(arg1,errmsg) then
                        local player = string.gsub(arg1,errmsg,"%1")
                        
                        if GuildLottery:DataGetUserIdx(player, GL_LOTTERY)>0 then -- player has lottery tickets, so this message was for us
                                GuildLottery:DataSetNotified( GuildLottery:DataGetUserIdx(player, 0), 0, 0 ) -- remember that we could not send message
                                return
                        end
                        if GuildLottery:DataGetUserIdx(player, GL_RAFFLE)>0 then -- player has raffle tickets, so this message was for us
                                GuildLottery:DataSetNotified( GuildLottery:DataGetUserIdx(player, 1), 0, 1 ) -- remember that we could not send message
                                return
                        end
                end
        end
        Orig_ChatFrame_OnEvent(self, event, ...)
end
ChatFrame_OnEvent = GL_ChatFrame_OnEvent

function GuildLottery:OptionsOnShow()
    GLRadiusSliderButtonPos:SetValue(GL_Settings.MinimapRadiusOffset)
    GLArcSliderButtonPos:SetValue(GL_Settings.MinimapArcOffset)
    GLIconSliderButtonPos:SetValue(GL_Settings.MinimapTextureId)
        GL_ChannelDropDownMenu_OnLoad()
end

function GuildLottery:IsGLWhisper( text, to )
        if #GL.WhisperHistory > 0 then
                for n=#GL.WhisperHistory, 1, -1 do
                        hist = GL.WhisperHistory[n]
                        if (GetTime() - hist.time > 10) then
                                table.remove(GL.WhisperHistory,n)
                        end
                end
        end
        if #GL.WhisperHistory > 0 then
                for n=1, #GL.WhisperHistory, 1 do
                        hist = GL.WhisperHistory[n]
                        if hist.to==to and hist.text==text then
                                return true
                        end
                end
        end  
end

function GuildLottery:InitUIText()

        if GL_Data.Raffle==GL_RAFFLE then
                PanelTemplates_SetTab(GLControlFrame, 2)

            GLSettingAreaBackground:Hide()
            GLRaffleSettingAreaBackground:Show()

            GLNewLotteryButton:SetText(L["UI_NEWRAFFLE"])
        else
                PanelTemplates_SetTab(GLControlFrame, 1)

                GLSettingAreaBackground:Show()
            GLRaffleSettingAreaBackground:Hide()

                GLNewLotteryButton:SetText(L["UI_NEWLOTTERY"])
        end
        
        GLNewUserFramePlayerName:SetText(L["UI_TYPEPLAYERNAME"])
        GLNewUserFrameNumTickets:SetText(L["UI_NUMTICKETS"])
        GLNewUserCancelButton:SetText(L["UI_CANCEL"])
        GLNewUserOKButton:SetText(L["UI_ACCEPT"])

        GLQuestionNoButton:SetText(L["UI_NO"])
        GLQuestionYesButton:SetText(L["UI_YES"])

        GLTooltipText:SetText(L["UI_OPTION_TOOLTIP"])
        GLMinimapLabel:SetText(L["UI_OPTION_MINIMAP"])
        GLInvalidItemsLabel:SetText(L["UI_OPTION_INVALIDITEMS"])
        GLCheckBoxLotteryLabel:SetText(L["UI_OPTION_LOTEVT"])
        GLCheckBoxWinnerAnnouncementLabel:SetText(L["UI_OPTION_WINEVT"])
        GLChannelDropDownLabel:SetText(L["UI_OPTION_CHANNEL"])

        GLLabelUsers:SetText(L["UI_PLAYERS"])
        GLLabelTickets:SetText(L["UI_TICKETS"])
        GLLabelTicketOptions:SetText(L["UI_INFO_OPTIONS"])
        GLLabelRaffleDate:SetText(L["UI_RAFFLEDATE"])
        GLLabelRaffleName:SetText(L["UI_RAFFLENAME"])
        GLLabelMaxRaffleTickets:SetText(L["UI_MAXTICKETS"])
        GLLabelRaffleItemOneTickets:SetText(L["UI_RAFFLEITEMONE"])
        GLLabelRaffleItemTwoTickets:SetText(L["UI_RAFFLEITEMTWO"])
        GLLabelRaffleItemThreeTickets:SetText(L["UI_RAFFLEITEMTHREE"])
        GLLabelRaffleTicketPrice:SetText(L["UI_TICKETPRICE"])

        GLLabelLotteryDate:SetText(L["UI_LOTTERYDATE"])
        GLLabelLotteryName:SetText(L["UI_LOTTERYNAME"])
        GLLabelStartGold:SetText(L["UI_STARTGOLD"])
        GLLabelMaxTickets:SetText(L["UI_MAXTICKETS"])
        GLLabelSecondPrize:SetText(L["UI_SECONDPRIZE"])
        GLLabelJackpot:SetText(L["UI_JACKPOT"])
        GLLabelTicketPrice:SetText(L["UI_TICKETPRICE"])
        GLLabelGuildCut:SetText(L["UI_GUILDCUT"])

        GLRaffleItemOneButton:SetText(L["UI_OKAY"])
        GLRaffleItemTwoButton:SetText(L["UI_OKAY"])
        GLRaffleItemThreeButton:SetText(L["UI_OKAY"])

        GLStartRollButton:SetText(L["UI_STARTROLLING"])


        if GL_Settings.Channel == GL_CHANNEL_GUILD then
                GLSpamButton:SetText(L["UI_SPAMGUILD"])
        else
                GLSpamButton:SetText(L["UI_SPAMRAID"])
        end

        GLControlVersion:SetText(GL_VERSION_TEXT)
end

function GuildLottery:OnMoneyChanged(obj)
                local somethingchanged=false
                value = MoneyInputFrame_GetCopper(GLStartGoldFrame)
                if value ~= GL_Data.StartGold then 
                        GL_Data.StartGold = value
                        somethingchanged=true
                end

                value = MoneyInputFrame_GetCopper(GLLotteryTicketPriceFrame)
                if value ~= GL_Data.LotteryTicketPrice then
                        GL_Data.LotteryTicketPrice = value
                        somethingchanged=true
                end

                value = MoneyInputFrame_GetCopper(GLRaffleTicketPriceFrame)
                if value ~= GL_Data.RaffleTicketPrice then
                        GL_Data.RaffleTicketPrice = value
                        somethingchanged=true
                end

        if somethingchanged then
                GuildLottery:UpdateScreen()
        end     
end

function GuildLottery:OnGlobalLoad(self)
        GL.Me = UnitName("player")
        GL.Command = strupper(GL.Command)
        GL.Command2 = strupper(GL.Command2)
        GL.Command3 = strupper(GL.Command3)
        GuildLottery:RegisterEvent("CHAT_MSG_GUILD", "CHAT_EVENT_HANDLER")
        GuildLottery:RegisterEvent("CHAT_MSG_WHISPER",  "CHAT_EVENT_HANDLER")
        GuildLottery:RegisterEvent("CALENDAR_OPEN_EVENT")
        GuildLottery:RegisterEvent("CALENDAR_ACTION_PENDING")
        GuildLottery:RegisterEvent("GUILD_ROSTER_UPDATE")
        
  GuildLottery:Print(GL_VERSION_TEXT.." loaded")

-- minimap button
        --GuildLottery:MinimapButton_Update()

        if ButtonHole then
                ButtonHole.application.RegisterMod({id="GLOTTERY", name="Guild Lottery",tooltip="Guild Lottery", buttonFrame="GLMinimapButton", updateFunction="GuildLottery:MinimapButton_Update"})
        end
-- end minimap 
  tinsert(UISpecialFrames, "GLControlFrame")
end


function GuildLottery:Toggle(page)
        GuildLottery:MinimapButton_Update()
        GuildLottery:UpdateScreen()
        GuildLottery:UpdateUserButtons()

  if (GLControlFrame:IsVisible()) then
    GLControlFrame:Hide()
  else
    GLRaffleItemOneButton:Hide()
    GLRaffleItemTwoButton:Hide()
    GLRaffleItemThreeButton:Hide()

    GLControlFrame:Show()
  end

end

function GuildLottery:User_OnLoad(self)
        self:RegisterForClicks("LeftButtonDown", "RightButtonDown")
end

function GuildLottery:User_OnClick(self, button)
        local id = self:GetID()
        local offset = FauxScrollFrame_GetOffset(GLUsersScrollFrame)
        local idx = id+offset
        HideDropDownMenu(1)
        
        GLTicketsEditBox:ClearFocus()
        
        g_MenuItemSelected = idx
        if button=="RightButton" then
                ToggleDropDownMenu(1,nil,GLUserCmdList,"cursor")
        end
        GuildLottery:UpdateScreen()
        GuildLottery:UpdateUserButtons()
end

function GL_UserCmdList_OnLoad()
  HideDropDownMenu(1)
  GLUserCmdList.initialize = GL_UserCmdList_Initialize
  GLUserCmdList.displayMode = "MENU"
  GLUserCmdList.name = "Titre"
end

function GL_UserCmdList_Initialize()
        local IsUser=false
        if GuildLottery:DataValid(g_MenuItemSelected, GL_Data.Raffle) then
                IsUser=true
        end

  info = { }
  info.text = L["UI_LOTTERYCOMMANDS"]
  info.isTitle = true
  info.notCheckable = 1
  UIDropDownMenu_AddButton(info,1)

        if (IsUser) then
          info = { }
          info.text =  L["UI_ADDTICKETS"]
          info.notCheckable = 1
          info.value = selectAdminItem
          info.func = GL_UserCmdList_AddTickets_OnClick
          UIDropDownMenu_AddButton(info,1)
        end

  info = { }
  info.text =  L["UI_ADDPLAYER"]
  info.notCheckable = 1
  info.value = selectAdminItem
  info.func = GL_UserCmdList_AddUser_OnClick
  UIDropDownMenu_AddButton(info,1)
  
  info = { }
  info.text = L["UI_CANCEL"]
  info.notCheckable = 1
  info.func = GL_UserCmdList_Cancel_OnClick
  UIDropDownMenu_AddButton(info,1)
end

function GL_UserCmdList_AddTickets_OnClick()
        GLNewUserTicketsEditBox:SetText("1")
        GLNewUserNameEditBox:SetText(GuildLottery:DataGetUser(g_MenuItemSelected, GL_Data.Raffle))
        GLNewUserFrame:Show()
        GLNewUserTicketsEditBox:SetFocus()
        GLNewUserTicketsEditBox:HighlightText()
end

function GL_UserCmdList_AddUser_OnClick()
        GLNewUserTicketsEditBox:SetText("1")
        GLNewUserNameEditBox:SetText("")
        GLNewUserFrame:Show()
        GLNewUserNameEditBox:SetFocus()
end

function GL_UserCmdList_Cancel_OnClick()
  HideDropDownMenu(1)
end

function GuildLottery:FormatPrice ( price )
        if price==nil then price =0 end
        local c= price % 100
        local s= (math.floor(price/100)) % 100
        local g= math.floor(price/10000)
        local text=g..L["UI_GOLD"]
        if s>0 then text=text.." "..s..L["UI_SILVER"]; end
        if c>0 then text=text.." "..c..L["UI_COPPER"]; end
        return text
end

function GuildLottery:FormatTicket( tickets )
        if tickets==nil then 
                return
        end
        local i,count
        local text=""
        count=0
        for i=1, table.getn(tickets), 1 do
                text=text..tickets[i]
                count=count+1
                if count==5 then
                        text=text.."\n"
                        count=0
                else
                        text=text.." "
                end
        end
        return text
end

function GuildLottery:FormatDate( datestamp )
        local text=date(GL_DATE_FORMAT,datestamp)
        return text
end

function GuildLottery:ExtractDate( datestamp )
        local year, month, day, hour, minute = tonumber(date("%Y",datestamp)),tonumber(date("%m",datestamp)),tonumber(date("%d",datestamp)),tonumber(date("%H",datestamp)),tonumber(date("%M",datestamp))
        return year, month, day, hour, minute
end

function GuildLottery:CalculateJackpot()
        return GL_Data.StartGold+GuildLottery:DataGetTotalTicketCount(0)*GL_Data.LotteryTicketPrice
end
        
function GuildLottery:UpdateScreen()
        local IsUser=false
        local idx=g_MenuItemSelected
        if (GuildLottery:DataValid(idx, GL_Data.Raffle)) then
                IsUser=true
        end

        if (GL_Data.LotteryDate and GL_Data.LotteryDate~=0) then
                GLLotteryDateEditBox:SetText(GuildLottery:FormatDate(GL_Data.LotteryDate))
        end
-- Raffle
        if (GL_Data.RaffleDate and GL_Data.RaffleDate~=0) then
                GLRaffleDateEditBox:SetText(GuildLottery:FormatDate(GL_Data.RaffleDate))
        end
        if (GL_Data.RaffleDate and GL_Data.RaffleDate~=0) then
                GLRaffleDateEditBox:SetText(GuildLottery:FormatDate(GL_Data.RaffleDate))
        end
-- Raffle End
        GLLotteryDateEditBox:SetTextColor(0.5,0.5,0.5)
        GLLotteryNameEditBox:SetText(GL_Data.LotteryName)
        GLRaffleNameEditBox:SetText(GL_Data.RaffleName)
        MoneyInputFrame_ResetMoney(GLJackPotFrame)
        MoneyInputFrame_SetCopper(GLJackPotFrame,GuildLottery:CalculateJackpot())
        MoneyInputFrame_ResetMoney(GLStartGoldFrame)
        MoneyInputFrame_SetCopper(GLStartGoldFrame,GL_Data.StartGold)
        GLMaxTicketsEditBox:SetText(GL_Data.MaxLotteryTickets)
        GLMaxRaffleTicketsEditBox:SetText(GL_Data.MaxRaffleTickets)
        GLSecondPrizeEditBox:SetText(GL_Data.SecondPrize)
        GLGuildCutEditBox:SetText(GL_Data.GuildCut)
        MoneyInputFrame_ResetMoney(GLLotteryTicketPriceFrame)
        MoneyInputFrame_SetCopper(GLLotteryTicketPriceFrame, GL_Data.LotteryTicketPrice)
        MoneyInputFrame_SetCopper(GLRaffleTicketPriceFrame, GL_Data.RaffleTicketPrice)

        GLTicketsEditBox:SetTextColor(1,1,1)
        GLTicketsEditBox:EnableMouse(0)

        
        if (GL_Data.RaffleItemOne~='0') then
            local itemName, itemLink = GetItemInfo(GL_Data.RaffleItemOne)
            if (itemLink) then
                    GLRaffleItemOneEditBox:SetText(itemLink)
                    GLRaffleItemOneEditBox:SetCursorPosition(0)

            end
            GLRaffleItemOneButton:Hide()
        end
        
        if (GL_Data.RaffleItemTwo~='0') then
            local itemName, itemLink = GetItemInfo(GL_Data.RaffleItemTwo)
            if (itemLink) then
                    GLRaffleItemTwoEditBox:SetText(itemLink)
                    GLRaffleItemTwoEditBox:SetCursorPosition(0)
            end
            GLRaffleItemTwoButton:Hide()
        end
        if (GL_Data.RaffleItemThree~='0') then
            local itemName, itemLink = GetItemInfo(GL_Data.RaffleItemThree)
            if (itemLink) then
                    GLRaffleItemThreeEditBox:SetText(itemLink)
                    GLRaffleItemThreeEditBox:SetCursorPosition(0)
            end
            GLRaffleItemThreeButton:Hide()
        end

        if (GuildLottery:DataGetTotalTicketCount(GL_Data.Raffle)>0) then
                GLStartRollButton:Enable()
        else
                GLStartRollButton:Disable()
        end
        
        if ( IsUser ) then
                local TicketText=GuildLottery:FormatTicket(GuildLottery:DataGetTickets(idx, GL_Data.Raffle))
                GLTicketsEditBox:SetText(TicketText)
        else            
                GLTicketsEditBox:SetText("")
        end
end

function GL_UpdateUserButtons()
        GuildLottery:UpdateUserButtons()
end

function GuildLottery:UpdateUserButtons()
        GL_debug("GuildLottery:UpdateUserButtons")
        local size=GuildLottery:DataCount(GL_Data.Raffle)
        FauxScrollFrame_Update(GLUsersScrollFrame, size, 10, GL_MENUBUTTONSIZEY)
        local offset=FauxScrollFrame_GetOffset(GLUsersScrollFrame)
        local i = 1
        local button, normaltext, highlight
        for i=1, 10, 1 do
                button = getglobal("GLUserButton"..i)
                buttonText = getglobal("GLUserButton"..i.."Tag")
                idx = i+offset
                if (GuildLottery:DataValid(idx, GL_Data.Raffle)) then
                        buttonText:SetText(GuildLottery:DataGetUser(idx, GL_Data.Raffle).." ("..GuildLottery:DataGetTicketCount(idx, GL_Data.Raffle)..")")
                        if (GuildLottery:DataGetNotified(idx, GL_Data.Raffle)==0) then
                                button.r = 0.9
                                button.g = 0.4
                                button.b = 0.1
                        else
                                button.r = 0.3
                                button.g = 0.5
                                button.b = 0.9
                        end
                        if ( g_MenuItemSelected and g_MenuItemSelected == idx ) then
                                button.r=button.r+0.3
                                button.g=button.g+0.3
                                button.b=button.b+0.3
                        end
                        buttonText:SetTextColor(button.r, button.g, button.b)
                        button:Show()
                else
                        button:Show()
                        buttonText:SetText("")
                end
        end
        GuildLottery:RaffleItemOne_OnEscapePressed(GLRaffleItemOneEditBox)
        GuildLottery:RaffleItemTwo_OnEscapePressed(GLRaffleItemTwoEditBox)
        GuildLottery:RaffleItemThree_OnEscapePressed(GLRaffleItemThreeEditBox)

end

--||||||||||||||||||||||||||||------ Minimap button ------||||||||||||||||||||||||||||--

function GuildLottery:MinimapButton_Update()
  if(GL_Settings.ShowMinimap==1) then  
        GLMinimapCheckBox:SetChecked(1)
    local radius = GL_Settings.MinimapRadiusOffset
    local arc = GL_Settings.MinimapArcOffset
    
                GLMinimapButton:Show()
                GLMinimapButtonText:SetText("")
                GLMinimapButtonText:SetTextColor(1.0,0.1,0.1)
                
    GLMinimapButton:SetPoint( "TOPLEFT", "Minimap", "TOPLEFT",55 - ( ( radius ) * cos( arc ) ),( ( radius ) * sin( arc ) ) - 55)
    GL_Settings.MinimapTexture = GL_Icons[GL_Settings.MinimapTextureId]
    if (GL_Settings.MinimapTexture==nil) then
        GL_Settings.MinimapTexture=GL_Icons[1]
    end
    GLMinimapButtonTexture:SetTexture("Interface\\Icons\\"..GL_Settings.MinimapTexture)
    GLMinimapButtonTexture:SetAlpha(1.0)
  else
        GLMinimapCheckBox:SetChecked(0)
        GLMinimapButton:Hide()
  end
end

function GuildLottery:QuestionYes_Click()
        if GL_Question_Callback~=nil then
                GL_Question_Callback(GL_ANSWER_YES)
        end
        GL_Question_Callback=nil
        GLQuestionFrame:Hide()
end

function GuildLottery:QuestionNo_Click()
        if GL_Question_Callback~=nil then
                GL_Question_Callback(GL_ANSWER_NO)
        end
        GL_Question_Callback=nil
        GLQuestionFrame:Hide()
end

function GuildLottery:AskQuestion(text,callback)
        GL_ANSWER_NO = L["UI_NO"]
        GL_ANSWER_YES = L["UI_YES"]
        GL_Question_Callback=callback
        GLQuestionEditBox:SetText(text)
        GLQuestionFrame:Show()
end

function GuildLottery:BuyTickets( amount )
        local i,ticket
        local newTickets={}
                if GL_Data.Raffle==GL_RAFFLE then
                        if GL_Data.NextRaffleTicket==0 then
                                GL_Data.NextRaffleTicket=GL_Data.RaffleTicketSerie
                        end
                        for i=1, amount, 1 do
                                ticket=GL_Data.NextRaffleTicket
                                table.insert(newTickets,ticket)
                                GL_Data.NextRaffleTicket=ticket+1
                        end
                else
                        if GL_Data.NextLotteryTicket==0 then
                                GL_Data.NextLotteryTicket=GL_Data.LotteryTicketSerie
                        end
                        for i=1, amount, 1 do
                                ticket=GL_Data.NextLotteryTicket
                                table.insert(newTickets,ticket)
                                if (GL_Data.GuaranteedWinner == 1) then
                                        GL_Data.NextLotteryTicket=ticket+1
                                else
                                        GL_Data.NextLotteryTicket=ticket+2
                                end
                        end
                end
        return newTickets
end

--||||||||||||||||||||||||||||------ NewUserFrame Button Clicks -----||||||||||||||||||||||||||||--
function GuildLottery:NewUserCancel_Click()
        GLNewUserFrame:Hide()
end


function GuildLottery:NewUserOK_Click()
        local User=GLNewUserNameEditBox:GetText()
        local numtickets = tonumber(GLNewUserTicketsEditBox:GetText())
        local i, name
        local found = 0
        
--[[    
        for i=1, GetNumGuildMembers(true) do
                name = GetGuildRosterInfo(i)
                if string.find(name,"^"..User.."$") then
                        found = 1
                end                     
        end

        if found < 1 then
                GL_printf(GuildLottery:Color(GREEN,"GuildLottery: ").. GuildLottery:Color(RED, L["ERR_NOTINGUILD"]))
                GLNewUserFrame:Hide()
                GuildLottery:UpdateScreen()
                GuildLottery:UpdateUserButtons()
                return
        end
--]]

        local alreadysold = 0
        if GuildLottery:DataGetUserIdx(User, GL_Data.Raffle)>0 then
                alreadysold = GuildLottery:DataGetTicketCount(GuildLottery:DataGetUserIdx(User, GL_Data.Raffle), GL_Data.Raffle)
        end
        
        if GL_Data.Raffle==GL_RAFFLE then
                if (numtickets+alreadysold>GL_Data.MaxRaffleTickets) then
                        GL_printf( GuildLottery:Color(GREEN,"GuildRaffle: ")..GuildLottery:Color(RED,L["ERR_EXCEEDTICKET"].." "..GL_Data.MaxRaffleTickets-alreadysold..L["ERR_EXCEEDTICKET2"])..GuildLottery:Color(CYAN,User))
                        return
                end
        else
                if (numtickets+alreadysold>GL_Data.MaxLotteryTickets) then
                        GL_printf( GuildLottery:Color(GREEN,"GuildLottery: ")..GuildLottery:Color(RED,L["ERR_EXCEEDTICKET"].." "..GL_Data.MaxLotteryTickets-alreadysold..L["ERR_EXCEEDTICKET2"])..GuildLottery:Color(CYAN,User))
                        return
                end
        end
        
        local Tickets=GuildLottery:BuyTickets(numtickets)
        local idx=GuildLottery:DataGetUserIdx(User, GL_Data.Raffle)

        if (idx and idx>0) then
                GuildLottery:DataAddTickets(idx, Tickets)
                GuildLottery:SendInfo(User, GL_Data.Raffle)
        else
                if GL_Data.Raffle == 0 then
                        LotteryInfo={}
                        LotteryInfo.User=User
                        LotteryInfo.Tickets=Tickets
                        LotteryInfo.Notified=1
                        GuildLottery:InsertData( LotteryInfo )
                else
                        RaffleInfo={}
                        RaffleInfo.User=User
                        RaffleInfo.Tickets=Tickets
                        RaffleInfo.Notified=1
                        GuildLottery:InsertData( RaffleInfo )
                end
                GuildLottery:SendInfo(User, GL_Data.Raffle)
        end
        GLNewUserFrame:Hide()
        GuildLottery:UpdateScreen()
        GuildLottery:UpdateUserButtons()
end

function GuildLottery:NewUserNameAutocomplete(self)
        local text = self:GetText()
        local textlen = strlen(text)
        local numFriends, name


        -- No match, check your guild list
        numFriends = GetNumGuildMembers(true)   -- true to include offline members
        if ( numFriends > 0 ) then
                for i=1, numFriends do
                        name = GetGuildRosterInfo(i)
                        if ( strfind(strupper(name), strupper(text), 1, 1) == 1 ) then
                                self:SetText(name)
                                self:HighlightText(textlen, -1)
                                return
                        end
                end
        end
end

function GuildLottery:NewUserOnEscapePressed()
        GuildLottery:NewUserCancel_Click()
end

function GuildLottery:NewUserOnEnterPressed()
        if GLNewUserNameEditBox:GetText() ~= "" then
                GuildLottery:NewUserOK_Click()
        end
end

function GuildLottery:InsertData( info)
        local Position
        
        if (info~=nil and info.User ~= nil) then
                Position=GuildLottery:DataCount(GL_Data.Raffle)+1
                GuildLottery:DataInsert(Position,info)
                g_MenuItemSelected = Position
                GuildLottery:UpdateScreen()
                GuildLottery:UpdateUserButtons()
        end
end

--||||||||||||||||||||||||||||------ ControlFrame Button Clicks -----||||||||||||||||||||||||||||--

function GuildLottery:NewLotteryClick()
        if GuildLottery:DataGetTotalTicketCount(GL_Data.Raffle) > 0 then
                GuildLottery:AskQuestion( L["MSG_NEWLOT"]..GuildLottery:Color(YELLOW,L["MSG_NEWLOTCONFIRM"]),GL_NewLotteryAnswerCallback)
        else
--              GL.WinningTicket=0
--              GL.WinningRaffleTicket1=0
--              GL.WinningRaffleTicket2=0
--              GL.WinningRaffleTicket3=0
--              GL.RaffleItem1='-1'
--              GL.RaffleItem2='-1'
--              GL.RaffleItem3='-1'
--              GL.WinningEvent=-1
                GuildLottery:RemoveAnnouncement()
                GL_Calendar_PickupDate(GL_NewLotteryCallback)
                if GL_Data.Raffle == GL_LOTTERY then
                        GLCalendarGuaranteedWinner:SetText(L["TEXT_CALENDAR_GUARANTEED"])
                        GLGuarantee:SetChecked(GL_Data.GuaranteedWinner)
                else
                        GLCalendarGuaranteedWinner:SetText(L["TEXT_CALENDAR_MULTIPLE"])
                        GLGuarantee:SetChecked(GL_Data.MultiWinners)
                end
        end 
end


function GL_NewLotteryAnswerCallback( answer )
        if answer==GL_ANSWER_YES then
                GL.WinningTicket=0
                GL.WinningRaffleTicket1=0
                GL.WinningRaffleTicket2=0
                GL.WinningRaffleTicket3=0
                GL.RaffleItem1='-1'
                GL.RaffleItem2='-1'
                GL.RaffleItem3='-1'
                GL.WinningEvent=-1
                GuildLottery:RemoveAnnouncement()

                GL_Calendar_PickupDate(GL_NewLotteryCallback)
                if GL_Data.Raffle == GL_LOTTERY then
                        GLCalendarGuaranteedWinner:SetText(L["TEXT_CALENDAR_GUARANTEED"])
                        GLGuarantee:SetChecked(GL_Data.GuaranteedWinner)
                else
                        GLCalendarGuaranteedWinner:SetText(L["TEXT_CALENDAR_MULTIPLE"])
                        GLGuarantee:SetChecked(GL_Data.MultiWinners)
                end
        end
end

function GL_NewLotteryCallback(datetime)
        if GL_Data.Raffle == 0 then
                GL_Data.LotteryDate=datetime
        else
                GL_Data.RaffleDate=datetime
        end     
                GuildLottery:DataClear(GL_Data.Raffle)
                GuildLottery:UpdateUserButtons()
                GuildLottery:UpdateScreen()
                GuildLottery:CreateAnnouncement()
end

local GLRollState=0
function GuildLottery:StartRollClick()

        if GLRollState > 0 then
                GuildLottery:Error(L["ERR_ROLLING"])
                return
        end

        if GL_Settings.Channel == GL_CHANNEL_RAID then
                local members = GetNumRaidMembers()
                
                if members == 0 then
                        GuildLottery:Error(L["ERR_NOTINRAID"])
                        return
                end
        end

        
        if GuildLottery:DataGetTotalTicketCount(GL_Data.Raffle) > 0 then
                if (GL_Data.Raffle == GL_LOTTERY) then
                        GuildLottery:ScheduleTimer("Rolling_Lottery", 10)
                else
                        if (GuildLottery:DataGetTotalTicketCount(1) < GuildLottery:GetNumPrizes()) and (GL_Data.MultiWinners==1) then

                                GuildLottery:Error(L["ERR_NOTENOUGHTICKETS"])
                                return

                        elseif (GuildLottery:FixPrizes() == 1) then
                                GL.RaffleItem1 = GL_Data.RaffleItemOne
                                GL.RaffleItem2 = GL_Data.RaffleItemTwo
                                GL.RaffleItem3 = GL_Data.RaffleItemThree
                                GuildLottery:ScheduleTimer("Rolling_Raffle", 10)
                        else
                                GuildLottery:Error(L["ERR_PRIZES"])
                                return
                        end
                end
        else
                GuildLottery:Error(L["ERR_NOTICKETS"])
        end
        GuildLottery:RemoveAnnouncement()
        GLRollState=1
        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_START"]))
end

function GuildLottery:GetNumPrizes()
   numPrizes = 0
   if (GL_Data.RaffleItemOne~='0') then numPrizes=1; end
   if (GL_Data.RaffleItemTwo~='0') then numPrizes = numPrizes+1; end
   if (GL_Data.RaffleItemThree~='0') then numPrizes = numPrizes+1; end
       return numPrizes
end

function GuildLottery:FixPrizes()

   if (GL_Data.RaffleItemOne=='0') and (GL_Data.RaffleItemTwo=='0') and (GL_Data.RaffleItemThree=='0') then
       return 0
   end

   if (GL_Data.RaffleItemOne=='0') then
        if (GL_Data.RaffleItemTwo~='0') then
                GL_Data.RaffleItemOne=GL_Data.RaffleItemTwo
                GL_Data.RaffleItemTwo='0'
                GLRaffleItemOneEditBox:SetText(GL_Data.RaffleItemOne)
                GLRaffleItemTwoEditBox:SetText('')
        elseif (GL_Data.RaffleItemThree~='0') then
                GL_Data.RaffleItemOne=GL_Data.RaffleItemThree
                GL_Data.RaffleItemThree='0'
                GLRaffleItemOneEditBox:SetText(GL_Data.RaffleItemOne)
                GLRaffleItemThreeEditBox:SetText('')
                return 1
        end    

        if (GL_Data.RaffleItemTwo=='0') then
                if (GL_Data.RaffleItemThree~='0') then
                        GL_Data.RaffleItemTwo=GL_Data.RaffleItemThree
                        GL_Data.RaffleItemThree='0'
                        GLRaffleItemTwoEditBox:SetText(GL_Data.RaffleItemTwo)
                        GLRaffleItemThreeEditBox:SetText('')
                end
        end
   end
   return 1
end

function GuildLottery:ToggleClick(num)

        if(GLCalendarFrame:IsVisible()) then
            return
        end
        
        PanelTemplates_SetTab(GLControlFrame, num+1)

        if num == 0 or num == 1 then
                GLNonOptionsFrame:Show()
                GLOptionsFrame:Hide()
        else
                GLNonOptionsFrame:Hide()
                GLOptionsFrame:Show()
                GLRadiusSliderButtonPos:SetValue(GL_Settings.MinimapRadiusOffset)
                GLArcSliderButtonPos:SetValue(GL_Settings.MinimapArcOffset)
                GLIconSliderButtonPos:SetValue(GL_Settings.MinimapTextureId)
                GL_ChannelDropDownMenu_OnLoad()
                return
        end
        
        if num ~= GL_Data.Raffle then
                if GL_Data.Raffle==GL_RAFFLE then
                        GL_Data.Raffle=GL_LOTTERY

                        GLSettingAreaBackground:Show()
                        GLRaffleSettingAreaBackground:Hide()

                        GLNewLotteryButton:SetText(L["UI_NEWLOTTERY"])
                else
                        GL_Data.Raffle=GL_RAFFLE

                        GLSettingAreaBackground:Hide()
                        GLRaffleSettingAreaBackground:Show()


                        GLNewLotteryButton:SetText(L["UI_NEWRAFFLE"])
                end
                GuildLottery:UpdateScreen()
                GuildLottery:UpdateUserButtons()
        end
end

local GLWinAmount=0
local GLWinnerName=""
local GLRaffleWinnerName1=""
local GLRaffleWinnerName2=""
local GLRaffleWinnerName3=""
local GLWinPlayer=0
local GLWinGuild=0
local GLWinningTicket=0
local GLWinningPercentage=0
local GLNewLotteryStart=0
local GLFirstNumber=0
local GLLastNumber=0
local GLNumberOfTickets=0

-- RollState1 = (announce 10 seconds to roll)
function GuildLottery:Rolling_Lottery()
        local number

        if (GL_Data.GuaranteedWinner == 1) then
                number = 1
        else
                number = 2
        end

        if GLRollState==1 then
                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TENSECS"]))
                GLRollState=2
                GuildLottery:ScheduleTimer("Rolling_Lottery",10)

        elseif GLRollState==2 then
                GLNumberOfTickets=GuildLottery:DataGetTotalTicketCount(GL_LOTTERY)
                GLFirstNumber=GL_Data.LotteryTicketSerie
                GLLastNumber=GL_Data.NextLotteryTicket-number
                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT1"])) -- "Rolling for the Jackpot "..GuildLottery:FormatPrice(GuildLottery:CalculateJackpot()));
                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT2"],GLNumberOfTickets,GLFirstNumber,GLLastNumber))
                GLRollState=3
                GuildLottery:ScheduleTimer("Rolling_Lottery",5)

        elseif GLRollState==3 then
                GLWinningTicket=math.random(GL_Data.LotteryTicketSerie,GL_Data.NextLotteryTicket-number)
                local idx=GuildLottery:DataGetTicketIdx(GLWinningTicket, GL_LOTTERY)
                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT3"],GLWinningTicket))
                if (idx==0) then
                        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT4LOSE"]))
                        -- No winner
                        if GL_Data.SecondPrize>0 then
                                GLRollState=4
                        else
                                GLRollState=10
                        end
                else
                        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT4WIN"]))
                        GLWinningPercentage=100
                        GLRollState=10
                end
                GuildLottery:ScheduleTimer("Rolling_Lottery",5)
        elseif GLRollState==4 then
                -- Rolling for SecondPrize
                GLWinningTicket=math.random(GL_Data.LotteryTicketSerie,GL_Data.NextLotteryTicket-number)
                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT5"],GLWinningTicket))
                local idx=GuildLottery:DataGetTicketIdx(GLWinningTicket, GL_LOTTERY)
                if (idx==0) then
                        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT6LOSE"]))
                        GLWinningTicket=0
                        GLRollState=10
                else
                        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT6WIN"]))
                        GLWinningPercentage=GL_Data.SecondPrize
                        GLRollState=10
                end
                GuildLottery:ScheduleTimer("Rolling_Lottery",5)
        elseif GLRollState==10 then
                GLWinAmount=0
                GLWinnerName=""
                if GLWinningTicket>0 then
                        GLWinnerName = GuildLottery:GetUserByTicket(GLWinningTicket, GL_LOTTERY)
                        GLWinAmount = (GLWinningPercentage * GuildLottery:CalculateJackpot()) / 100
                        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT7"],GLWinnerName,GLWinningPercentage))
                        if GL_Data.GuildCut > 0 then
                                GLWinPlayer = math.floor(((100-GL_Data.GuildCut)*GLWinAmount)/100)
                                GLWinGuild = math.floor(((GL_Data.GuildCut)*GLWinAmount)/100)
                                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT8GUILD"],GuildLottery:FormatPrice( GLWinPlayer),GLWinnerName,GuildLottery:FormatPrice(GLWinGuild)))
-- TODO: Fix the "You have to pay out, messages, it's not localized! :(
                                GL_printf(GuildLottery:Color(GREEN,"GuildLottery:")..GuildLottery:Color(WHITE," You have to pay out: ")..GuildLottery:Color(YELLOW,GuildLottery:FormatPrice(GLWinPlayer))..GuildLottery:Color(WHITE," to: ")..GuildLottery:Color(CYAN,GLWinnerName))
                                GL_printf(GuildLottery:Color(GREEN,"GuildLottery:")..GuildLottery:Color(WHITE," You have to pay out: ")..GuildLottery:Color(YELLOW,GuildLottery:FormatPrice(GLWinGuild))..GuildLottery:Color(WHITE," to the guild"))
                        else
                                GLWinPlayer = GLWinAmount
                                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT8NORMAL"],GuildLottery:FormatPrice( GLWinPlayer)))
                                GL_printf(GuildLottery:Color(GREEN,"GuildLottery:")..GuildLottery:Color(WHITE," You have to pay out: ")..GuildLottery:Color(YELLOW,GuildLottery:FormatPrice(GLWinPlayer))..GuildLottery:Color(WHITE," to: ")..GuildLottery:Color(CYAN,GLWinnerName))
                        end
                end
                GLRollState=11
                GuildLottery:ScheduleTimer("Rolling_Lottery",5)
        elseif GLRollState==11 then
                GLNewLotteryStart=0
                GLNewLotteryStart = GuildLottery:CalculateJackpot()-GLWinAmount
                if GLNewLotteryStart>0 then
                        GuildLottery:Chat(GuildLottery:Parse(L["ROLL_NEXT"],GuildLottery:FormatPrice(GLNewLotteryStart)))
                end
                GL_Data.StartGold = GLNewLotteryStart
                if GL_Data.Raffle==GL_RAFFLE then
                        GuildLottery:ToggleClick()
                end
                if (GL_Settings.UseWinnerAnnouncement == 1) then
                        GL.WinningEvent=0
                        GuildLottery:AskQuestion(GuildLottery:Color(YELLOW,L["MSG_CREATEWINNEREVT"]),GL_CreateWinnerCallback)
                else
                        GuildLottery:DataClear(GL_LOTTERY)
                        GL_printf(GuildLottery:Color(GREEN,"GuildLottery: ")..GuildLottery:Color(WHITE,L["MSG_CHOOSENEXT"]))
                        GuildLottery:NewLotteryClick()
                end
                GLRollState=0

        end     
end

function GuildLottery:Rolling_Raffle()
        local number;

        number = 1;

        if GLRollState==1 then -- Rolling in 10 seconds
                GLWinningRaffleTicket1='-1'
                GLWinningRaffleTicket2='-1'
                GLWinningRaffleTicket3='-1'

                GLRaffleWinnerName1=""
                GLRaffleWinnerName2=""
                GLRaffleWinnerName3=""

                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TENSECS"]))
                GLRollState=2
                GuildLottery:ScheduleTimer("Rolling_Raffle", 10)

        elseif GLRollState==2 then
                GLNumberOfTickets=GuildLottery:DataGetTotalTicketCount(GL_RAFFLE)
                GLFirstNumber=GL_Data.RaffleTicketSerie
                GLLastNumber=GL_Data.NextRaffleTicket-1
                GuildLottery:Chat(GuildLottery:Parse(L["ROLL_TEXT2"],GLNumberOfTickets,GLFirstNumber,GLLastNumber))

                if GL.RaffleItem2 =='0' and GL.RaffleItem3 =='0' then
                        GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_ROLL_TEXT3"])) -- "Rolling for the Prizes " (Multiple winners)
                elseif GL.RaffleItem2 ~='0' and GL.RaffleItem3 =='0' then
                        GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_ROLL_TEXT2"])) -- "Rolling for the Prizes " (Multiple winners)
                else
                        GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_ROLL_TEXT1"])) -- "Rolling for the Prizes " (Multiple winners)
                end

                if (GL_Data.MultiWinners==1) then
                        GLRollState=3
                else
                        GLRollState=4
                end

        GuildLottery:ScheduleTimer("Rolling_Raffle", 5)

        elseif GLRollState==3 then -- Multiple winners
                GLWinningRaffleTicket1=math.random(GL_Data.RaffleTicketSerie,GL_Data.NextRaffleTicket-number)
                if GL.RaffleItem2~='0' then
                        GLWinningRaffleTicket2=math.random(GL_Data.RaffleTicketSerie,GL_Data.NextRaffleTicket-number)
                else
                        GLWinningRaffleTicket2='-1'
                end
                if GL.RaffleItem3~='0' then
                        GLWinningRaffleTicket3=math.random(GL_Data.RaffleTicketSerie,GL_Data.NextRaffleTicket-number)
                else
                        GLWinningRaffleTicket3='-1'
                end

                while (GLWinningRaffleTicket2==GLWinningRaffleTicket1) do
                        GLWinningRaffleTicket2=math.random(GL_Data.RaffleTicketSerie,GL_Data.NextRaffleTicket-number)
                end
                if GLWinningRaffleTicket3~='-1' then
                        while (GLWinningRaffleTicket3==GLWinningRaffleTicket2) or (GLWinningRaffleTicket3==GLWinningRaffleTicket1) do
                                GLWinningRaffleTicket3=math.random(GL_Data.RaffleTicketSerie,GL_Data.NextRaffleTicket-number)
                        end
                end
                if (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2=='-1') then
                        GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT5"],GLWinningRaffleTicket1))
                elseif (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2~='-1') then
                        GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT4"],GLWinningRaffleTicket1,GLWinningRaffleTicket2))
                else
                        GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT3"],GLWinningRaffleTicket1,GLWinningRaffleTicket2,GLWinningRaffleTicket3))
                end

                GLRollState=10

                GuildLottery:ScheduleTimer("Rolling_Raffle", 5)
        elseif GLRollState==4 then
                -- Single Winner
                GLWinningRaffleTicket1=math.random(GL_Data.RaffleTicketSerie,GL_Data.NextRaffleTicket-number)
                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_S_ROLL_TEXT3"],GLWinningRaffleTicket1))
                local idx=GuildLottery:DataGetTicketIdx(GLWinningRaffleTicket1, GL_RAFFLE)
                GLRollState=10
                
                GuildLottery:ScheduleTimer("Rolling_Raffle", 5)

        elseif GLRollState==10 then


                GLRaffleWinnerName1 = GuildLottery:GetUserByTicket(GLWinningRaffleTicket1, GL_RAFFLE)

                if (GL_Data.MultiWinners==1) then
                        if (GLWinningRaffleTicket2~='-1') then
                                GLRaffleWinnerName2 = GuildLottery:GetUserByTicket(GLWinningRaffleTicket2, GL_RAFFLE)
                        end
                        if (GLWinningRaffleTicket3~='-1') then
                                GLRaffleWinnerName3 = GuildLottery:GetUserByTicket(GLWinningRaffleTicket3, GL_RAFFLE)
                        end             

                        if (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2=='-1') then
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName1,GL.RaffleItem1))
                        elseif (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2~='-1') then
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT8"],GLRaffleWinnerName1,GL.RaffleItem1,GLRaffleWinnerName2,GL.RaffleItem2))
                        else
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName1,GL.RaffleItem1))
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName2,GL.RaffleItem2))
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName3,GL.RaffleItem3))
                        end
                else
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT10"], GLRaffleWinnerName1))
                        if (GLRaffleItem3=='-1' and GLRaffleItem2=='-1') then
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT11"],GL.RaffleItem1))
                        elseif (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2~='-1') then
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT11"], GL.RaffleItem1))
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT11"], GL.RaffleItem2))
                        else
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT11"], GL.RaffleItem1))
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT11"], GL.RaffleItem2))
                                GuildLottery:Chat(GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT11"], GL.RaffleItem3))
                        end
                        
                end
                
                GLRollState=11
                GuildLottery:ScheduleTimer("Rolling_Raffle", 5)
        elseif GLRollState==11 then

                if GL_Data.Raffle==GL_LOTTERY then
                        GuildLottery:ToggleClick()
                end
                if (GL_Settings.UseWinnerAnnouncement == 1) then
                        GL.WinningEvent=1;
                        GuildLottery:AskQuestion(GuildLottery:Color(YELLOW,L["MSG_CREATEWINNEREVT"]),GL_CreateWinnerCallback)
                else
                        GuildLottery:DataClear(GL_RAFFLE)
                        GL_printf(GuildLottery:Color(GREEN,"GuildLottery: ")..GuildLottery:Color(WHITE,L["MSG_CHOOSENEXT"]))
                        GuildLottery:NewLotteryClick()
                end
                GLRollState=0
        end     
end

function GL_CreateWinnerCallback(answer)
        if answer==GL_ANSWER_YES then
                GuildLottery:CreateWinnerAnnouncement()
        end
end

function GuildLottery:MaxRaffleTicketsOnEscapePressed(self)
        GLMaxRaffleTicketsEditBox:SetText(GL_Data.MaxRaffleTickets)
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()

end

function GuildLottery:MaxRaffleTicketsOnEnterPressed(self)
        GL_Data.MaxRaffleTickets=GLMaxRaffleTicketsEditBox:GetNumber()
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:MaxTicketsOnEscapePressed(self)
        GLMaxTicketsEditBox:SetText(GL_Data.MaxLotteryTickets)
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:MaxTicketsOnEnterPressed(self)
        GL_Data.MaxLotteryTickets=GLMaxTicketsEditBox:GetNumber()
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:SecondPrizeOnEscapePressed(self)
        GLSecondPrizeEditBox:SetText(GL_Data.SecondPrize)
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:SecondPrizeOnEnterPressed(self)
        local num=GLSecondPrizeEditBox:GetNumber()
        if num~=nil then
                if num>100 then 
                        num=100;
                end
                if num<0 then
                        num=0;
                end
                GL_Data.SecondPrize=num
        end

        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end


function GL_TicketPriceOnEscapePressed()
        GuildLottery:UpdateScreen()
end

function GL_TicketPriceOnEnterPressed()
        GL_Data.TicketPrice = GLTicketPriceEditBox:GetNumber()
        GuildLottery:UpdateScreen()
end

function GL_StartGoldOnEscapePressed()
        GuildLottery:UpdateScreen()
end

function GL_StartGoldOnEnterPressed()
        local value=GLStartGoldEditBox:GetNumber()
        if value then
                GL_Data.StartGold=value
        else
                GL_Data.StartGold=0
        end
        GuildLottery:UpdateScreen()
end


-- Raffle
function GuildLottery:RaffleItemOne_OnTextChanged(self)
    if (GLRaffleItemOneEditBox:GetText()=='' and GL_Data.RaffleItemOne=='0') then
        return
    end
    
    if (GLRaffleItemOneEditBox:GetText() ~= GL_Data.RaffleItemOne) then
            GLRaffleItemOneButton:Show()
    end
end

function GuildLottery:RaffleItemOne_OnEnterPressed(self)
    GuildLottery:RaffleItemOneButton_OnClick(GLRaffleItemOneButton)
end

function GuildLottery:RaffleItemOne_OnEscapePressed(self)
        if (GL_Data.RaffleItemOne~='0') then
            GLRaffleItemOneEditBox:SetText(GL_Data.RaffleItemOne)
        else
            GLRaffleItemOneEditBox:SetText('')
        end

        GLRaffleItemOneEditBox:SetCursorPosition(0)
        GLRaffleItemOneEditBox:ClearFocus()
        GLRaffleItemOneButton:Hide()
end

function GuildLottery:RaffleItemOneButton_OnClick(self)
    local text = GLRaffleItemOneEditBox:GetText()
    local itemName, itemLink = GetItemInfo(text)

    if (GLRaffleItemOneEditBox:GetText() == '') then
        GL_Data.RaffleItemOne='0'
        GLRaffleItemOneEditBox:ClearFocus()
        GLRaffleItemOneButton:Hide()
        return;
    end        

        if (itemLink == nil and GL_Settings.AllowInvalidItems == 1) then
                itemLink = "["..text.."]"
        end
        
    if (itemLink) then
            GLRaffleItemOneEditBox:SetText(itemLink)
            GL_Data.RaffleItemOne=itemLink
            GLRaffleItemOneEditBox:ClearFocus()
    else
                GL_printf(GuildLottery:Color(GREEN,"GuildLottery: ").. GuildLottery:Color(RED, L["ERR_INVALIDITEM"]))
                if (GL_Data.RaffleItemOne~='0') then
                        GLRaffleItemOneEditBox:SetText(GL_Data.RaffleItemOne)
                else
                        GLRaffleItemOneEditBox:SetText('')
                end

                GLRaffleItemOneEditBox:ClearFocus()
        end

        GLRaffleItemOneEditBox:SetCursorPosition(0)
        GLRaffleItemOneButton:Hide()
end

--

function GuildLottery:RaffleItemTwo_OnTextChanged(self)
    if (GLRaffleItemTwoEditBox:GetText()=='' and GL_Data.RaffleItemTwo=='0') then
        return;
    end
    
    if (GLRaffleItemTwoEditBox:GetText() ~= GL_Data.RaffleItemTwo) then
            GLRaffleItemTwoButton:Show()
    end
end

function GuildLottery:RaffleItemTwo_OnEnterPressed(self)
    GuildLottery:RaffleItemTwoButton_OnClick(Button2)
end

function GuildLottery:RaffleItemTwo_OnEscapePressed(self)
        if (GL_Data.RaffleItemTwo~='0') then
            GLRaffleItemTwoEditBox:SetText(GL_Data.RaffleItemTwo)
        else
            GLRaffleItemTwoEditBox:SetText('')
        end

        GLRaffleItemTwoEditBox:SetCursorPosition(0)
        GLRaffleItemTwoEditBox:ClearFocus()
        GLRaffleItemTwoButton:Hide()
end

function GuildLottery:RaffleItemTwoButton_OnClick(self)
    local text = GLRaffleItemTwoEditBox:GetText()
    local itemName, itemLink = GetItemInfo(text)

    if (GLRaffleItemTwoEditBox:GetText() == '') then
                GL_Data.RaffleItemTwo='0'
        GLRaffleItemTwoEditBox:ClearFocus()
        GLRaffleItemTwoButton:Hide()
        return
    end        

        if (itemLink == nil and GL_Settings.AllowInvalidItems == 1) then
                itemLink = "["..text.."]"
        end
        
    if (itemLink) then
            GLRaffleItemTwoEditBox:SetText(itemLink)
            GL_Data.RaffleItemTwo=itemLink
            GLRaffleItemTwoEditBox:ClearFocus()
    else
                GL_printf(GuildLottery:Color(GREEN,"GuildLottery: ").. GuildLottery:Color(RED, L["ERR_INVALIDITEM"]))
                if (GL_Data.RaffleItemTwo~='0') then
                    GLRaffleItemTwoEditBox:SetText(GL_Data.RaffleItemTwo)
                else
                    GLRaffleItemTwoEditBox:SetText('')
        end

        GLRaffleItemTwoEditBox:ClearFocus()
    end

    GLRaffleItemTwoEditBox:SetCursorPosition(0)
    GLRaffleItemTwoButton:Hide()
end

--    

function GuildLottery:RaffleItemThree_OnTextChanged(self)
    if (GLRaffleItemThreeEditBox:GetText()=='' and GL_Data.RaffleItemThree=='0') then
        return
    end
    
    if (GLRaffleItemThreeEditBox:GetText() ~= GL_Data.RaffleItemThree) then
            GLRaffleItemThreeButton:Show()
    end
end

function GuildLottery:RaffleItemThree_OnEnterPressed(self)
    GuildLottery:RaffleItemThreeButton_OnClick(Button2)
end

function GuildLottery:RaffleItemThree_OnEscapePressed(self)
        if (GL_Data.RaffleItemThree~='0') then
            GLRaffleItemThreeEditBox:SetText(GL_Data.RaffleItemThree)
        else
            GLRaffleItemThreeEditBox:SetText('')
        end

        GLRaffleItemThreeEditBox:SetCursorPosition(0)
        GLRaffleItemThreeEditBox:ClearFocus()
        GLRaffleItemThreeButton:Hide()
end

function GuildLottery:RaffleItemThreeButton_OnClick(self)
    local text = GLRaffleItemThreeEditBox:GetText()
    local itemName, itemLink = GetItemInfo(text)

    if (GLRaffleItemThreeEditBox:GetText() == '') then
                GL_Data.RaffleItemThree='0'
        GLRaffleItemThreeEditBox:ClearFocus()
        GLRaffleItemThreeButton:Hide()
        return;
    end

        if (itemLink == nil and GL_Settings.AllowInvalidItems == 1) then
                itemLink = "["..text.."]"
        end

    if (itemLink) then
            GLRaffleItemThreeEditBox:SetText(itemLink)
            GL_Data.RaffleItemThree=itemLink
            GLRaffleItemThreeEditBox:ClearFocus()
    else
                GL_printf(GuildLottery:Color(GREEN,"GuildLottery: ").. GuildLottery:Color(RED, L["ERR_INVALIDITEM"]))
                if (GL_Data.RaffleItemThree~='0') then
                    GLRaffleItemThreeEditBox:SetText(GL_Data.RaffleItemThree)
                else
                    GLRaffleItemThreeEditBox:SetText('')
        end

        GLRaffleItemThreeEditBox:ClearFocus()
    end

    GLRaffleItemThreeEditBox:SetCursorPosition(0)
    GLRaffleItemThreeButton:Hide();
end

function GuildLottery:ShowToolTip(self, title, message)
  GameTooltip:SetOwner(self, "ANCHOR_CURSOR")
  GameTooltip:SetText(title)  -- This sets the top line of text, in gold.
  GameTooltip:AddLine(message, 1, 1, 1)
  GameTooltip:Show()
end

function GL_printf(text)
   if DEFAULT_CHAT_FRAME then
      DEFAULT_CHAT_FRAME:AddMessage(text)
   else
      message(text)
   end
end
-- TODO replace this with ace3 print message
function GL_debug(text)
        if      GL_Settings.Debuglevel>0 then
                GL_printf(text)
  end
end

local GLRegistered=-1
function GuildLottery:SendWhisperLine(to, text )
        table.insert(GL.WhisperHistory, { to=to, text=text, time=GetTime() })
        if to == GL.Me then
                GL_printf( GuildLottery:Color(GREEN,text))
        else
                SendChatMessage( text, "WHISPER", nil, to )
        end     
end

function GuildLottery:GetUserByTicket( ticketno, raffle )
        local idx=GuildLottery:DataGetTicketIdx(tonumber(ticketno), raffle)
        local Name=GuildLottery:DataGetUser(idx, raffle)
        return Name
end

function GuildLottery:SendTicketOwnerOf( user, ticketno, raffle )
        local Name=GuildLottery:GetUserByTicket( ticketno, raffle )
        GuildLottery:SendWhisperLine(user, "GuildLottery:")
        if Name==nil or Name=="" then
                GuildLottery:SendWhisperLine(user, GuildLottery:Parse(L["TICKETINFO_NOTSOLD"],ticketno)) -- "Ticket number "..ticketno.." is not sold.")
        else
                GuildLottery:SendWhisperLine(user, GuildLottery:Parse(L["TICKETINFO_SOLD"],ticketno,Name)) --"Ticket number "..ticketno.." is sold to: "..Name)
        end
end

function GuildLottery:SendWhisperByKey ( key, lines, player)
        local line = 1
--      local text = GuildLottery:TextParse( getglobal(L[key..line]), player )
        local text = GuildLottery:TextParse( L[key..line], player )
        while ((text ~= nil and #text >0) and (line <= lines) ) do
                for i=1, #text do
                        if text[i] ~= "" then
                                GuildLottery:SendWhisperLine(player, text[i])
                        end
                end
                line=line+1
                if (line <= lines) then
                        text = GuildLottery:TextParse( L[key..line], player)
                end
        end
end

function GuildLottery:SendHelp( player )
        
        -- General - part
        local key = "INFO_HELP_LINE"
        GuildLottery:SendWhisperByKey( key, 7, player)

        -- OddEven or guaranteed winner - part
        local key="INFO_HELP_ODDEVEN_LINE";
        if (GL_Data.GuaranteedWinner == 1) then key = "INFO_HELP_GUARANTEED_LINE"; end
        GuildLottery:SendWhisperByKey( key, 1, player)

        -- Second prize - part  
        key = "INFO_HELP_NOSECONDPRIZE_LINE"
        if GL_Data.SecondPrize > 0 then 
                key = "INFO_HELP_SECONDPRIZE_LINE"
                GuildLottery:SendWhisperByKey( key, 3, player)
        else
                GuildLottery:SendWhisperByKey( key, 1, player)
        end
        
        -- Guild cut - part
        key = "INFO_HELP_NOGUILDCUT_LINE";
        if GL_Data.GuildCut > 0 then key = "INFO_HELP_GUILDCUT_LINE"; end
        GuildLottery:SendWhisperByKey( key, 1, player);
        
end

CF_MessageEventHandler_Orig = CF_MessageEventHandler;
function GL_CF_MessageEventHandler(self, event, ...)            
        if event == "CHAT_MSG_WHISPER_INFORM" then
                local msg = arg1;
                local user = arg2;
                if GuildLottery:IsGLWhisper( msg, user ) then
                        return;
                end
        end
  return CF_MessageEventHandler_Orig(self, event, ...)
end
CF_MessageEventHandler = GL_CF_MessageEventHandler

function GuildLottery:SendRaffleInfo( player, raffle )
        GuildLottery:SendInfo( player, 1 )
        GuildLottery:RemoveSpam("Raffle", player)
end

function GuildLottery:SendLotteryInfo( player, raffle )
        GuildLottery:SendInfo( player, 0 )
        GuildLottery:RemoveSpam("Lottery", player)
end

function GuildLottery:SendInfo( player, raffle )
        GL_printf(GuildLottery:Color(GREEN,"GuildLottery ")..GuildLottery:Color(WHITE,GuildLottery:Parse(L["MSG_SENDINFO"]))..GuildLottery:Color(CYAN,player))
        local idx =GuildLottery:DataGetUserIdx( player, raffle )
        -- assume he is online, so set the notification done
        GuildLottery:DataSetNotified(idx,1, raffle)
        GuildLottery:UpdateUserButtons()
        if raffle == 0 then
                GuildLottery:SendWhisperByKey( "LOTTERYINFO_TO_USER_ONE_LINE", 3, player)
                if (GuildLottery:DataGetTicketCount(idx, raffle) > 0) then
                        GuildLottery:SendWhisperByKey( "LOTTERYINFO_TO_USER_HAS_TICKETS_LINE", 3, player)
                end
                GuildLottery:SendWhisperByKey( "LOTTERYINFO_TO_USER_TWO_LINE", 3, player)
        else
                GuildLottery:SendWhisperByKey( "RAFFLEINFO_TO_USER_ONE_LINE", 3, player)
                if (GuildLottery:DataGetTicketCount(idx, raffle) > 0) then
                        GuildLottery:SendWhisperByKey( "RAFFLEINFO_TO_USER_HAS_TICKETS_LINE", 3, player)
                end
                GuildLottery:SendWhisperByKey( "RAFFLEINFO_TO_USER_TWO_LINE", 3, player)
        end
end


function GuildLottery:SpamClick(raffle)
  local line=1
  
        if GL_Settings.Channel == GL_CHANNEL_RAID then
                local members = GetNumRaidMembers()
                
                if members == 0 then
                        GuildLottery:Error(L["ERR_NOTINRAID"])
                        return
                end
        end

        if (raffle == nil) then 
                raffle = GL_Data.Raffle
        end
        

        if raffle==GL_LOTTERY then
                if (GL_Data.GuaranteedWinner == 1) then
                        GuildLottery:Chat(L["UI_GUARANTEEDWINNER"])
                end

                local spamtext = GuildLottery:TextParse( L["INFO_LOTTERYSPAM_LINE"..line] )
                count = 1
                while (spamtext ~= nil and #spamtext>0 and line <= 3 ) do
                        for i=1, #spamtext do
                                if spamtext[i] ~= "" then
                                        GuildLottery:Chat( spamtext[i] )
                                end
                        end
                        line=line+1
                        if (line <= 3) then
                        spamtext = GuildLottery:TextParse( L["INFO_LOTTERYSPAM_LINE"..line] )
                        end
                end
        else
                local spamtext = GuildLottery:TextParse( L["INFO_RAFFLESPAM_LINE"..line] )
                while (spamtext ~= nil and #spamtext>0 and line <= 7 ) do
                        for i=1, #spamtext do
                                if spamtext[i] ~= "" then
                                        GuildLottery:Chat( spamtext[i] )
                                end
                        end
                        line=line+1
                        if (line <= 7) then
                                spamtext = GuildLottery:TextParse( L["INFO_RAFFLESPAM_LINE"..line] )
                        end
                end
        end
end

function GuildLottery:Chat(text)
        local chatchan
        if GL_Settings.Channel == GL_CHANNEL_RAID then
                chatchan = "RAID"
        else
                chatchan = "GUILD"
        end
        
        if GL_Data.Raffle==GL_LOTTERY then
                SendChatMessage( "<<"..GL_Data.LotteryName..">> "..text, chatchan, nil, nil )
        else
                SendChatMessage( "<<"..GL_Data.RaffleName..">> "..text, chatchan, nil, nil )
        end
end


function GuildLottery:AnnouncementText(raffle)
        local text=""
        
        if (raffle==0) then
                text=text..GL_Data.LotteryName.."\n"
                if (GL_Data.GuaranteedWinner == 1) then
                        text=text..L["UI_GUARANTEEDWINNER"].."\n"
                end

                text=text..L["UI_LOTTERYDATE"]..": "..GuildLottery:FormatDate(GL_Data.LotteryDate).."\n"
                text=text..L["UI_STARTGOLD"]..": "..GuildLottery:FormatPrice(GL_Data.StartGold).."\n"
                text=text..L["UI_TICKETPRICE"]..": "..GuildLottery:FormatPrice(GL_Data.LotteryTicketPrice).."\n"
                text=text..L["UI_MAXTICKETS"]..": "..GL_Data.MaxLotteryTickets.."\n"
                if (GL_Data.GuaranteedWinner == 0) then
                        if GL_Data.SecondPrize ~= nil and GL_Data.SecondPrize > 0 then
                                text=text..L["UI_SECONDPRIZE"]..": "..GL_Data.SecondPrize.."%\n"
                        end
                end
                if GL_Data.GuildCut ~= nil and GL_Data.GuildCut > 0 then
                        text=text..L["UI_GUILDCUT"]..": "..GL_Data.GuildCut.."%\n"
                end             
                text=text.."\n"..L["UI_OWNER"]..": "..GL.Me.."\n"
                return text
        else
                local prizes = ""
                GuildLottery:FixPrizes()
                if (GL_Data.RaffleItemOne~="" and GL_Data.RaffleItemOne~='0') then prizes = prizes..GetItemInfo(GL_Data.RaffleItemOne); end
                if (GL_Data.RaffleItemTwo~="" and GL_Data.RaffleItemTwo~='0') then prizes = prizes..", "..GetItemInfo(GL_Data.RaffleItemTwo); end
                if (GL_Data.RaffleItemThree~="" and GL_Data.RaffleItemThree~='0') then prizes = prizes..", "..GetItemInfo(GL_Data.RaffleItemThree); end

                text=text..GL_Data.RaffleName.."\n"
                text=text..L["UI_RAFFLEDATE"]..": "..GuildLottery:FormatDate(GL_Data.RaffleDate).."\n"
                text=text..L["UI_TICKETPRICE"]..": "..GuildLottery:FormatPrice(GL_Data.RaffleTicketPrice).."\n"
                text=text..L["UI_MAXTICKETS"]..": "..GL_Data.MaxRaffleTickets.."\n"
                text=text..L["UI_PRIZES"]..prizes.."\n"
                text=text.."\n"..L["UI_OWNER"]..": "..GL.Me.."\n"
                return text
        end
end


        

function GuildLottery:WinnerAnnouncementText(raffle)
        local text=""
        local itemName1 =""
        local itemName2 =""
        local itemName3 =""
        
        if raffle == 1 then
                text=text..GL_Data.RaffleName.."\n"
                text=text..GuildLottery:Parse(L["ROLL_TEXT2"],GLNumberOfTickets,GLFirstNumber,GLLastNumber).."\n"
                if (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2=='-1') then
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT5"],GLWinningRaffleTicket1).."\n"
                        itemName1 = GetItemInfo(GL.RaffleItem1)
                        if itemName1 == nil then 
                                itemName1 = string.sub(GL.RaffleItem1, 2, -2)
                        end
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName1,itemName1)
                elseif (GLWinningRaffleTicket3=='-1' and GLWinningRaffleTicket2~='-1') then
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT4"],GLWinningRaffleTicket1,GLWinningRaffleTicket2).."\n"
                        itemName1 = GetItemInfo(GL.RaffleItem1)
                        itemName2 = GetItemInfo(GL.RaffleItem2)
                        if itemName1 == nil then 
                                itemName1 = string.sub(GL.RaffleItem1, 2, -2)
                        end
                        if itemName2 == nil then 
                                itemName2 = string.sub(GL.RaffleItem2, 2, -2)
                        end
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName1,itemName1).."\n"
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName2,itemName2)
                else
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT3"],GLWinningRaffleTicket1,GLWinningRaffleTicket2,GLWinningRaffleTicket3).."\n"
                        itemName1 = GetItemInfo(GL.RaffleItem1)
                        itemName2 = GetItemInfo(GL.RaffleItem2)
                        itemName3 = GetItemInfo(GL.RaffleItem3)
                        if itemName1 == nil then 
                                itemName1 = string.sub(GL.RaffleItem1, 2, -2)
                        end
                        if itemName2 == nil then 
                                itemName2 = string.sub(GL.RaffleItem2, 2, -2)
                        end
                        if itemName3 == nil then 
                                itemName3 = string.sub(GL.RaffleItem3, 2, -2)
                        end
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName1,itemName1).."\n"
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName2,itemName2).."\n"
                        text=text..GuildLottery:Parse(L["RAFFLE_M_ROLL_TEXT9"],GLRaffleWinnerName3,itemName3)
                end
                return text
        else
                text=text..GL_Data.LotteryName.."\n"
                text=text..GuildLottery:Parse(L["ROLL_TEXT2"],GLNumberOfTickets,GLFirstNumber,GLLastNumber).."\n"
                text=text..GuildLottery:Parse(L["ROLL_TEXT3"],GLWinningTicket).."\n"
                if GLWinnerName=="" then
                        text=text..GuildLottery:Parse(L["ROLL_TEXT4LOSE"]).."\n"
                else
                        text=text..GuildLottery:Parse(L["ROLL_TEXT7"],GLWinnerName,GLWinningPercentage).."\n"
                end
                if GLWinGuild>0 then
                        text=text..GuildLottery:Parse(L["ROLL_TEXT8GUILD"],GuildLottery:FormatPrice(GLWinPlayer),GLWinnerName,GuildLottery:FormatPrice(GLWinGuild)).."\n"
                else
                        text=text..GuildLottery:Parse(L["ROLL_TEXT8NORMAL"],GuildLottery:FormatPrice(GLWinPlayer)).."\n"
                end
                if GLNewLotteryStart>0 then
                        text=text..GuildLottery:Parse(L["ROLL_NEXT"],GuildLottery:FormatPrice(GLNewLotteryStart)).."\n"
                end
                return text
        end
        
end


function GuildLottery:CreateWinnerAnnouncement()
        if GL_Settings.UseWinnerAnnouncement==1 then
                if (CalendarCanAddEvent()) then

                        local _, month, day, year = CalendarGetDate()
                        local hour, minute = GetGameTime()
                        local winnerText = GuildLottery:WinnerAnnouncementText(GL.WinningEvent)
                        minute=minute+1
                        CalendarCloseEvent()
                        CalendarNewGuildAnnouncement()
                        CalendarEventSetDate(month,day,year)
                        if GL.WinningEvent==1 then
                                CalendarEventSetTitle(L["MSG_RESULT"]..GL_Data.RaffleName)
                        else
                                CalendarEventSetTitle(L["MSG_RESULT"]..GL_Data.LotteryName)
                        end
                        CalendarEventSetDescription(winnerText)
                        CalendarEventSetTime(hour,minute)
                        CalendarEventSetType(5)
                        CalendarAddEvent()
                else
                        GuildLottery:Error(L["ERR_NOANNOUNCE"])
                end
        end
        GuildLottery:DataClear(GL.WinningEvent)
        GuildLottery:ScheduleTimer(GL_printf, 5, GuildLottery:Color(GREEN,"GuildLottery: ")..GuildLottery:Color(WHITE,L["MSG_CHOOSENEXT"]))
        GuildLottery:ScheduleTimer("NewLotteryClick", 5)
end


function GuildLottery:CreateAnnouncement()
        if GL_Settings.UseLotteryAnnouncement==1 then
                if (CalendarCanAddEvent()) then
                        local year, month, day, hour, minute
                        CalendarCloseEvent()

                        if GL_Data.Raffle == 1 then
                                year, month, day, hour, minute = GuildLottery:ExtractDate( GL_Data.RaffleDate)
                                GL_Data.AnnouncementTitle = GL_Data.RaffleName
                        else                    
                                year, month, day, hour, minute = GuildLottery:ExtractDate( GL_Data.LotteryDate)
                                GL_Data.AnnouncementTitle = GL_Data.LotteryName
                        end

                        
                        CalendarNewGuildAnnouncement()
                        CalendarEventSetDate(month,day,year)
                        CalendarEventSetTitle(GL_Data.AnnouncementTitle)
                        CalendarEventSetDescription(GuildLottery:AnnouncementText(GL_Data.Raffle))
                        CalendarEventSetTime(hour,minute)
                        CalendarEventSetType(5)
                        CalendarAddEvent()

                else
                        GuildLottery:Error(L["ERR_NOANNOUNCE"])
                end
        end
end

function GuildLottery:CalendarFindEvent( title, year, month, day )
        local monthOffset=0
        local my,mm
        for i=0, 17 do
                mm,my = CalendarGetMonth(i)
                if ((mm==month) and (my==year)) then
                        monthOffset=i
                end
        end
        local numevents=CalendarGetNumDayEvents(monthOffset,day)
        for eventIndex=1, numevents do
                local t =       CalendarGetDayEvent(monthOffset, day, eventIndex)
                if t==title then
                        return monthOffset, day, eventIndex
                end
        end
        return nil,nil,nil
end

function GuildLottery:RemoveAnnouncement()
        if (GL_Settings.UseLotteryAnnouncement==1) then
                local year, month, day

                if GL_Data.Raffle == 1 then
                        GL_Data.AnnouncementTitle = GL_Data.RaffleName
                else                    
                        GL_Data.AnnouncementTitle = GL_Data.LotteryName
                end
                
                if GL_Data.AnnouncementTitle ~= nil and GL_Data.AnnouncementTitle ~= "" then
                        if GL_Data.Raffle == 1 then
                                year, month, day = GuildLottery:ExtractDate( GL_Data.RaffleDate)
                        else
                                year, month, day = GuildLottery:ExtractDate( GL_Data.LotteryDate)
                        end

                        local mo,d,ei = GuildLottery:CalendarFindEvent( GL_Data.AnnouncementTitle, year, month, day )

                        if (mo ~= nil ) then
                                GL_Data.AnnouncementTitle=""
                                CalendarContextEventRemove(mo, d, ei)
                        else
--                              GuildLottery:Error(L["ERR_REMOVEANNOUNCE"])
                        end
                end
        end
end

function GuildLottery:Issecure()
        if issecure()~=nil then
                GL_printf("Environment is secure")
        else
                GL_printf("Environment is NOT secure")
        end
end


function GuildLottery:LotteryName_OnEnterPressed(self)
        GL_Data.LotteryName=GLLotteryNameEditBox:GetText()
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()

end

function GuildLottery:LotteryName_OnEscapePressed(self)
        GLLotteryNameEditBox:SetText(GL_Data.LotteryName)
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:RaffleName_OnEnterPressed(self)
        GL_Data.RaffleName=GLRaffleNameEditBox:GetText()
        self:ClearFocus()
        GuildLottery:UpdateScreen()

end

function GuildLottery:RaffleName_OnEscapePressed(self)
        GLRaffleNameEditBox:SetText(GL_Data.RaffleName)
        self:ClearFocus()
        GuildLottery:UpdateScreen()
end

function GuildLottery:GuildCut_OnEnterPressed(self)
        local num=GLGuildCutEditBox:GetNumber()
        if num~=nil then
                if num>100 then 
                        num=100
                end
                if num<0 then
                        num=0
                end     
                GL_Data.GuildCut=num
        end
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:GuildCut_OnEscapePressed(self)
        GLGuildCutEditBox:SetText(GL_Data.GuildCut)
        self:ClearFocus()
        self:SetTextColor(1,1,1)
        GuildLottery:UpdateScreen()
end

function GuildLottery:Parse(text, ... )
        local txt="";
        local tab = GuildLottery:TextParse(text,nil,...)
        if type(tab)=="table" then
                if #tab>0 then
                        txt=tab[1]
                end
        end
        return txt
end

function GuildLottery:TextParse( text, player, ...)
        local parsed={}
        if text==nil then return nil; end
        local p1,p2,p3,p4,p5,p6,p7,p8,p9,p10=...
        local prizes=""
                if GL_Data.RaffleItemOne~='0' then prizes=prizes..GL_Data.RaffleItemOne; end
                if GL_Data.RaffleItemTwo~='0' then prizes=prizes.." "..GL_Data.RaffleItemTwo; end
                if GL_Data.RaffleItemThree~='0' then prizes=prizes.." "..GL_Data.RaffleItemThree; end

                text = string.gsub(text,"%%lotteryowner%%", GL.Me)
                text = string.gsub(text,"%%me%%", GL.Me)
                text = string.gsub(text,"%%lotteryname%%", GL_Data.LotteryName )
                text = string.gsub(text,"%%lotterydate%%", GuildLottery:FormatDate(GL_Data.LotteryDate))
                text = string.gsub(text,"%%jackpot%%", GuildLottery:FormatPrice(GuildLottery:CalculateJackpot()) )
                text = string.gsub(text,"%%startgold%%", GuildLottery:FormatPrice(GL_Data.StartGold) )
                text = string.gsub(text,"%%maxlotterytickets%%", GL_Data.MaxLotteryTickets)
                text = string.gsub(text,"%%lotteryticketprice%%", GuildLottery:FormatPrice(GL_Data.LotteryTicketPrice))
                text = string.gsub(text,"%%secondprize%%", GL_Data.SecondPrize)
                text = string.gsub(text,"%%guildcut%%", GL_Data.GuildCut)

                text = string.gsub(text,"%%raffleowner%%", GL.Me)
                text = string.gsub(text,"%%rafflename%%", GL_Data.RaffleName )
                text = string.gsub(text,"%%raffledate%%", GuildLottery:FormatDate(GL_Data.RaffleDate))
                text = string.gsub(text,"%%maxraffletickets%%", GL_Data.MaxRaffleTickets)
                text = string.gsub(text,"%%raffleticketprice%%", GuildLottery:FormatPrice(GL_Data.RaffleTicketPrice))

                if string.match(text,"%%prize1%%") then
                        if (GL_Data.RaffleItemOne ~= "" and GL_Data.RaffleItemOne~='0') then
                                text = string.gsub(text,"%%prize1%%", GL_Data.RaffleItemOne)
                        else
                                text = ""
                        end
                end
                
                if string.match(text,"%%prize2%%") then
                        if (GL_Data.RaffleItemTwo ~= "" and GL_Data.RaffleItemTwo~='0') then
                                text = string.gsub(text,"%%prize2%%", GL_Data.RaffleItemTwo)
                        else
                                text = ""
                        end
                end

                if string.match(text,"%%prize3%%") then
                        if (GL_Data.RaffleItemThree ~= "" and GL_Data.RaffleItemThree~='0') then
                                text = string.gsub(text,"%%prize3%%", GL_Data.RaffleItemThree)
                        else
                                text = ""
                        end
                end

                text = string.gsub(text,"%%prizes%%", prizes)

        if (p1) then
                text = string.gsub(text,"%%1%%", p1)
        end
        if (p2) then
                text = string.gsub(text,"%%2%%", p2)
        end
        if (p3) then
                text = string.gsub(text,"%%3%%", p3)
        end
        if (p4) then
                text = string.gsub(text,"%%4%%", p4)
        end
        if (p5) then
                text = string.gsub(text,"%%5%%", p5)
        end
        if (p6) then
                text = string.gsub(text,"%%6%%", p6)
        end
        if (p7) then
                text = string.gsub(text,"%%7%%", p7)
        end
        if (p8) then
                text = string.gsub(text,"%%8%%", p8)
        end
        if (p9) then
                text = string.gsub(text,"%%9%%", p9)
        end

        if string.match(text,"%%availablelotterytickets%%") then
                if player ~= nil and player ~= "" then
                        local idx=GuildLottery:DataGetUserIdx( player, GL_LOTTERY )
                        if idx>=0 then
                                local availcount = GL_Data.MaxLotteryTickets - GuildLottery:DataGetTicketCount(idx, GL_LOTTERY)
                                text = string.gsub(text,"%%availablelotterytickets%%", availcount)
                        else
                                text = string.gsub(text,"%%availablelotterytickets%%", GL_Data.MaxLotteryTickets)
                        end
                else
                        text = nil
                end
        end
        if string.match(text,"%%availableraffletickets%%") then
                if player ~= nil and player ~= "" then
                        local idx=GuildLottery:DataGetUserIdx( player, GL_RAFFLE )
                        if idx>=0 then
                                local availcount = GL_Data.MaxRaffleTickets - GuildLottery:DataGetTicketCount(idx, GL_RAFFLE)
                                text = string.gsub(text,"%%availableraffletickets%%", availcount)
                        else
                                text = string.gsub(text,"%%availableraffletickets%%", GL_Data.MaxLotteryTickets)
                        end
                else
                        text = nil
                end
        end
        if string.match(text,"%%playername%%") then
                if player ~= nil and player ~= "" then
                        text = string.gsub(text,"%%playername%%",player)
                else
                        text=nil
                end
        end

        if text~=nil and string.match(text,"%%soldlotterytickets%%") then
                text=nil
                if player ~= nil and player ~= "" then
                        local idx=GuildLottery:DataGetUserIdx( player, GL_LOTTERY )
                        local tickets=GuildLottery:DataGetTickets(idx, GL_LOTTERY)
                        local i,count
                        local tickettext=""
                        count=0
                        if (GuildLottery:DataGetTicketCount(idx, GL_LOTTERY) > 0) then
                                for i=1, GuildLottery:DataGetTicketCount(idx, GL_LOTTERY), 1 do
                                        tickettext=tickettext..tickets[i].." "

                                        count=count+1
                                        if count==5 then
                                                table.insert(parsed,tickettext)
                                                count=0
                                                tickettext=""
                                        end
                                end
                                if tickettext~="" then
                                        table.insert(parsed,tickettext)
                                end
                        else
                                table.insert(parsed,"No Tickets Bought")
                        end

                end
        end
        if text~=nil and string.match(text,"%%soldraffletickets%%") then
                text=nil
                if player ~= nil and player ~= "" then
                        local idx=GuildLottery:DataGetUserIdx( player, GL_RAFFLE )
                        local tickets=GuildLottery:DataGetTickets(idx, GL_RAFFLE)
                        local i,count
                        local tickettext=""
                        count=0
                        if (GuildLottery:DataGetTicketCount(idx, GL_RAFFLE) > 0) then
                                for i=1, GuildLottery:DataGetTicketCount(idx, GL_RAFFLE), 1 do
                                        tickettext=tickettext..tickets[i].." "
                                        count=count+1
                                        if count==5 then
                                                table.insert(parsed,tickettext)
                                                count=0
                                                tickettext=""
                                        end
                                end
                                if tickettext~="" then
                                        table.insert(parsed,tickettext)
                                end
                        else
                                table.insert(parsed,"No Tickets Bought")
                        end

                end
        end
        if text ~= nil then
                table.insert(parsed,text)
        end
        return parsed
end

function GuildLottery:AddSpam(spamType, ...)
        arg1 = ...
        table.insert(GL.SpamQueue, {spam=spamType, person=arg1 })
end

local spamCmd={}
function GuildLottery:SpamExist(spamType, ... )
        local arg1 = ...
        for i=1, #GL.SpamQueue do
                spamCmd = GL.SpamQueue[i]

                if (spamCmd.spam == spamType) and (spamCmd.person==arg1) then
                        return true
                end
        end
end

function GuildLottery:RemoveSpam( spamType, ...)
        local arg1 = ...
        for i=1, #GL.SpamQueue do
                spamCmd = GL.SpamQueue[i]

                if (spamCmd.spam == spamType) and (spamCmd.person==arg1) then
                        table.remove(GL.SpamQueue,i)
                end

        end

end


function GuildLottery:TooltipCheckBox_OnClick()
        local checked = GLTooltipCheckBox:GetChecked()
        GL_Settings.Tooltips = checked or 0
end

function GuildLottery:InvalidItemsCheckBox_OnClick()
        local checked = GLInvalidItemsCheckBox:GetChecked()
        GL_Settings.AllowInvalidItems = checked or 0
end

function GuildLottery:MinimapCheckBox_OnClick()
        local checked = GLMinimapCheckBox:GetChecked()
        GL_Settings.ShowMinimap = checked or 0
        GuildLottery:MinimapButton_Update()
end

function GuildLottery:LotteryAnnouncement_OnClick()
        local checked = GLCheckBoxLotteryAnnouncement:GetChecked()
        GL_Settings.UseLotteryAnnouncement = checked or 0
end

function GuildLottery:WinnerAnnouncement_OnClick()
        local checked = GLCheckBoxWinnerAnnouncement:GetChecked()
        GL_Settings.UseWinnerAnnouncement = checked or 0
end

function GuildLottery:CheckNotifications()
        local index=1;
  local name,_,_,_,_,_,_,_, online= GetGuildRosterInfo(index)
  local idx
  while (name) do
        idx = GuildLottery:DataGetUserIdx(name, 0) -- lottery
        if (idx>0) then
                -- this user have tickets
                -- is he notified ??
                if (GuildLottery:DataGetNotified(idx, 0)==0 and online~=nil) then
                        -- he was not, schedule a notification in 50 seconds ( gives time to the player if he just was logging on )
                        if (GuildLottery:SpamExist("Raffle", name ) == false ) then
                                -- he was not, schedule a notification in 50 seconds ( gives time to the player if he just was logging on )
                                GuildLottery:AddSpam("Raffle", name )
                                GuildLottery:ScheduleTimer("SendRaffleInfo", 15, name)
                        end
                end
        end
        idx = GuildLottery:DataGetUserIdx(name, 1) -- raffle
        if (idx>0) then
                -- this user have tickets
                -- is he notified ??
                if (GuildLottery:DataGetNotified(idx, 1)==0 and online~=nil) then
                        if (GuildLottery:SpamExist("Lottery", name ) == false ) then
                                -- he was not, schedule a notification in 50 seconds ( gives time to the player if he just was logging on )
                                GuildLottery:AddSpam("Lottery", name )
                                GuildLottery:ScheduleTimer("SendLotteryInfo", 15, name)
                        end
                end
        end
                index=index+1
                name,_,_,_,_,_,_,_, online= GetGuildRosterInfo(index)
  end
end

local   GLChannelInfo            = {};
local loading = 1

function GL_ChannelDropDownMenu_OnLoad()
        
        GLChannelInfo.text       = "Guild";
        GLChannelInfo.value      = GL_CHANNEL_GUILD;
        GLChannelInfo.func       = GL_ChannelChanged
                         -- can also be done as function() FunctionCalledWhenOptionIsClicked() end;

        -- Add the above information to the options menu as a button.
        UIDropDownMenu_AddButton(GLChannelInfo);

        GLChannelInfo.text       = "Raid";
        GLChannelInfo.value      = GL_CHANNEL_RAID;
        GLChannelInfo.func       = GL_ChannelChanged
                         -- can also be done as function() FunctionCalledWhenOptionIsClicked() end;

        -- Add the above information to the options menu as a button.
        UIDropDownMenu_AddButton(GLChannelInfo);
        
        UIDropDownMenu_SetWidth(GLChannelDropDownMenuButton, 80);
        UIDropDownMenu_SetButtonWidth(GLChannelDropDownMenuButton, 100)

-- TODO: This is a bandaid, for now
        if GL_Settings.Channel ~= nil then
                local channeltext
                UIDropDownMenu_SetSelectedID(GLChannelDropDownMenuButton, GL_Settings.Channel)
                if GL_Settings.Channel == GL_CHANNEL_RAID then
                        UIDropDownMenu_SetText(GLChannelDropDownMenuButton,"Raid")
                else
                        UIDropDownMenu_SetText(GLChannelDropDownMenuButton,"Guild")
                end
        end
end

function GL_ChannelChanged(self)
        UIDropDownMenu_SetSelectedID(GLChannelDropDownMenuButton, self:GetID())
        GL_Settings.Channel = UIDropDownMenu_GetSelectedID(GLChannelDropDownMenuButton)

        if GL_Settings.Channel == GL_CHANNEL_GUILD then
                GLSpamButton:SetText(L["UI_SPAMGUILD"])
        else
                GLSpamButton:SetText(L["UI_SPAMRAID"])
        end

end

function GuildLottery:Test()
--      GuildLottery:ScheduleTimer("SendRaffleInfo", 5, "Mordsbooty")
        GuildLottery:AddSpam("Raffle", "Mordsbooty")

        if (GuildLottery:SpamExist("Raffle", "Mordsbooty")) then
                GuildLottery:Print("Found 1")
        else
                GuildLottery:Print("Not Found 1")
        end

        GuildLottery:RemoveSpam("Raffle", "Mordsbooty")
        
        if (GuildLottery:SpamExist("Raffle", "Mordsbooty")) then
                GuildLottery:Print("Found 2")
        else
                GuildLottery:Print("Not Found 2")
        end
        
end


function GuildLottery:Debugging()
        if GL_Settings.Debuglevel > 0 then
                GL_Settings.Debuglevel = 0
        else
                GL_Settings.Debuglevel = 1
        end
end


Compare with Previous | Blame