cdbgroups = {}
cdbmembers = {}

function CooldownBars_OnLoad()
	this:RegisterEvent("SPELL_UPDATE_COOLDOWN")
	this:RegisterEvent("VARIABLES_LOADED")
	this:RegisterEvent("SPELLS_CHANGED")
	this:RegisterEvent("PLAYER_ENTERING_WORLD")
	this:RegisterEvent("CHAT_MSG_SPELL_AURA_GONE_SELF")
	this:RegisterEvent("UNIT_PET")
	this:RegisterForDrag("LeftButton")
	
	SlashCmdList["COOLDOWNBARS"] = function(msg)
		CooldownBars_slash(msg)
	end

    CDB_Pre_ContainerFrameItemButton_OnModifiedClick = ContainerFrameItemButton_OnModifiedClick;
    ContainerFrameItemButton_OnModifiedClick = CDB_ContainerFrameItemButton_OnModifiedClick;
	
	CDB_Pre_SpellButton_OnModifiedClick = SpellButton_OnModifiedClick;
	SpellButton_OnModifiedClick = CDB_SpellButton_OnModifiedClick;
	
	CDB_Pre_PaperDollItemSlotButton_OnModifiedClick = PaperDollItemSlotButton_OnModifiedClick;
	PaperDollItemSlotButton_OnModifiedClick = CDB_PaperDollItemSlotButton_OnModifiedClick;
	
	SLASH_COOLDOWNBARS1 = "/cdb"
end

function CDB_ContainerFrameItemButton_OnModifiedClick(button)
	if ( button == "LeftButton" ) then
		if ( IsShiftKeyDown() ) then
			if (CooldownBarsGroups:IsVisible()) then
				CDBTooltip:SetBagItem(this:GetParent():GetID(), this:GetID());
				local linetip = getglobal ("CDBTooltipTextLeft1");
				local text = linetip:GetText();
				CDB_AddMember(text);
				return;
			end
		end
	end
    CDB_Pre_ContainerFrameItemButton_OnModifiedClick(button);
end

function CDB_OnTooltip(v1,v2)
	GameTooltip:SetOwner(this,"ANCHOR_LEFT")
	GameTooltip:AddLine(v1)
	GameTooltip:AddLine(v2,.8,.8,.8,1)
	GameTooltip:Show()
end

function CDB_IconFrame_OnClick(arg1)
	if arg1=="LeftButton" and IsShiftKeyDown() then
		CDB_ShowGroups()
	elseif arg1=="LeftButton" then
		CooldownBars_ShowOptions()
	elseif arg1=="RightButton" then
		if cdbvars["checks"]["locked"] then
			cdbvars["checks"]["locked"] = false
		else
			cdbvars["checks"]["locked"] = true
		end
		cdb_setlocks("moveable")
	end
end

function CDB_PaperDollItemSlotButton_OnModifiedClick(button)
	if ( button == "LeftButton" ) then
		if ( IsShiftKeyDown() ) then
			if ( CooldownBarsGroups:IsVisible() ) then
				CDBTooltip:SetInventoryItem("player", this:GetID());
				local linetip = getglobal ("CDBTooltipTextLeft1");
				local text = linetip:GetText();
				CDB_AddMember(text);
				return;
			end
		end
	end
    CDB_Pre_PaperDollItemSlotButton_OnModifiedClick(button);
end

function CDB_SpellButton_OnModifiedClick(drag)
	if ( IsShiftKeyDown() ) then
		if (CooldownBarsGroups:IsVisible()) then
			local spellId = SpellBook_GetSpellID(this:GetID());
			if ( spellId > MAX_SPELLS ) then
				return;
			end
			local spellName, spellRank = GetSpellName( spellId, SpellBookFrame.bookType );
			CDB_AddMember(spellName);
			return;
		end
    end
    CDB_Pre_SpellButton_OnModifiedClick(drag);
end

function CooldownBars_OnEvent(event)
	if( event == "VARIABLES_LOADED" ) then
		if( not cdbvars ) then
			cdbvars = {}
			cdbvars.on = true
		end
		if( not cdbvars["version"] ) or ( cdbvars["version"] ~= CDB_VERSION ) then
			cdbvars.on = true
			cdbvars["version"] = CDB_VERSION
			cdbvars["texture"] = "standard"
			cdbvars["itemcolor"] = {
				[1] = 0.7,
				[2] = 0.7,
				[3] = 1,
				[4] = 1
			}
			cdbvars["skillcolor"] = {
				[1] = 0,
				[2] = 0.8,
				[3] = 0,
				[4] = 1
			}
			cdbvars["textcolor"] = {
				[1] = .9,
				[2] = .9,
				[3] = .9,
				[4] = 1
			}
			
			cdbvars["timecolor"] = {
				[1] = .9,
				[2] = .9,
				[3] = .9,
				[4] = 1
			}
			
			cdbvars["bordercolor"] = {
				[1] = 1,
				[2] = 1,
				[3] = 1,
				[4] = 1
			}
			
			cdbvars["bordercolorhidden"] = {
				[1] = 1,
				[2] = 1,
				[3] = 1,
				[4] = 0
			}

			cdbvars["backdropcolor"] = {
				[1] = 0,
				[2] = 0,
				[3] = 0,
				[4] = 0.7
			}
			
			cdbvars["backdropcolorhidden"] = {
				[1] = 0,
				[2] = 0,
				[3] = 0,
				[4] = 0
			}
		end
		
		if (not cdbvars["minimappos"]) then
			cdbvars["minimappos"] = 0
		end
		cdb_move_icon()
		if( not cdbvars["disabled"] ) then
			cdbvars["disabled"] = {}
		end
		if( not cdbvars["groups"] ) then
			cdbvars["groups"] = {}
		end
		if( not cdbvars["style"] ) then
			cdbvars["style"] = "seconds"
		end
		
		if( not cdbvars["checks"] ) then
			cdbvars["checks"] = {}
			for key, val in pairs(CDB_CHECKS) do
				if( key > 1) and (key < 5 ) or (key == 16) then
					cdbvars["checks"][val] = false
				else
					cdbvars["checks"][val] = true
				end
			end
		end
		
		if (not cdbvars["checks"]["hideminimap"]) then
			cdbvars["checks"]["hideminimap"] = false
		end

		if( not cdbvars["checks"]["flipbars"] ) then
			cdbvars["checks"]["flipbars"] = false
		end

		if( cdbvars["checks"]["cascade"] == nil ) then
			cdbvars["checks"]["cascade"] = true
		end
		
		if( cdbvars["checks"]["sort"] == nil ) then
			cdbvars["checks"]["sort"] = true
		end
		
		if( not cdbvars["values"] ) then
			cdbvars["values"] = {
				["columns"] = 1,
				["bardistance"] = 10,
				["barthickness"] = 14,
				["trans"] = 1,
				["scale"] = 1,
				["minbar"] = 150,
				["minalert"] = 10
			}
		end
		
		if( not cdbvars["report"] ) then
			cdbvars["report"] = {}
			cdbvars["report"]["enable"] = false
			cdbvars["report"]["channel"] = "SELECT"
			cdbvars["report"]["current"] = "SELECT"
		end
		
		if( not cdbvars["values"]["precision"] ) then
			cdbvars["values"]["precision"] = 0
		end
		
		if( not cdbvars["values"]["announcescale"] ) then
			cdbvars["values"]["announcescale"] = 1
		end
		
		if( not cdbvars["groups"] ) then
			cdbvars["groups"] = {}
		end
		
		if( not cdbvars["omnigroup"] ) then
			cdbvars["omnigroup"] = {}
		end			
		if( cdbvars["checks"]["down"] == nil ) then
			cdbvars["checks"]["down"] = true
		end
		
		if( not cdbvars["values"]["mintime"] ) then
			cdbvars["values"]["mintime"] = 2
		end
		
		for i=1, CDB_NUM_SLIDERS do
			getglobal("CooldownBarsOptionsHorizontalSlider"..i.."SliderTitle"):SetText(CDB_SLIDERS_LOCALISED[i])
			getglobal("CooldownBarsOptionsHorizontalSlider"..i.."SliderLow"):SetText(CDB_SLIDERS_ENDS[i][1])
			getglobal("CooldownBarsOptionsHorizontalSlider"..i.."SliderHigh"):SetText(CDB_SLIDERS_ENDS[i][2])
		end
		
		for i=1, CDB_NUM_LABELS do 
			getglobal("CooldownBarsOptionsLabel"..i.."Label"):SetText(CDB_LABELS[i])
		end
		
		for i=1, CDB_NUM_CHECKS do --CDB_CHECKS[i]
			getglobal("CooldownBarsOptionsCheckButton"..i.."Text"):SetText(CDB_CHECKS_LOCALISED[i])
		end
		cdbvars.bagItems = true
		cdbvars.init = false
	end
	
	if( cdbvars.on == false ) then
		return
	end
	
	if( event == "SPELLS_CHANGED" ) or (event == "PLAYER_ENTERING_WORLD") then
		local _, class = UnitClass("player")
		local _, race = UnitRace("player")
		if not (class == "ROGUE" or class == "DRUID" or race == "NightElf") then
			this:UnregisterEvent("CHAT_MSG_SPELL_AURA_GONE_SELF")
		end
		
		CooldownBars_init()
		CooldownBars_findCooldowns()
	end

	if( event == "CHAT_MSG_SPELL_AURA_GONE_SELF" ) then
		if( arg1 == CDB_STEALTH_FADES ) or (arg1 == CDB_PROWL_FADES) or (arg1 == CDB_SHADOWMELD_FADES ) then
			local fade = arg1
			if (arg1 == CDB_STEALTH_FADES) then
				fade = CDB_STEALTH
			elseif arg1 == CDB_PROWL_FADES then
				fade = CDB_PROWL
			elseif arg1 == CDB_SHADOWMELD_FADES then
				fade = CDB_SHADOWMELD
			end
			
			for k,v in pairs(cdbvars.stealth) do
			local name = GetSpellName( v, BOOKTYPE_SPELL )
			local startTime, duration, flag = GetSpellCooldown( v, BOOKTYPE_SPELL )
			
				if (duration > cdbvars["values"]["mintime"] and (name == fade)) then
					if( not cdbvars["disabled"][name] ) then
						for k, v in pairs(cdbvars["omnigroup"]) do 
							if( string.match( name, k ) ) then
								name = v
								break
							end
						end
						if( cdbvars["groups"][name] ) then
							name = cdbvars["groups"][name]
						end
						
						if( startTime ~= cdbvars["cooldowns"][name] ) then					
							cdbvars["cooldowns"][name] = startTime
							CooldownBars_addCooldown( name, startTime, duration, 1, GetSpellTexture(v, BOOKTYPE_SPELL) )		
						end
					end
				end
			end
		end
	elseif( event == "SPELL_UPDATE_COOLDOWN" ) then
		CooldownBars_findCooldowns()
	elseif( event == "UNIT_PET" ) and (arg1 == "player") then
		local i = 1
		cdbvars.petSpells = {}
		while( GetSpellName(i, BOOKTYPE_PET) ) do 
			if( GetSpellName(i, BOOKTYPE_PET) ~= GetSpellName(i+1, BOOKTYPE_PET) ) and ( not IsPassiveSpell(i, BOOKTYPE_PET) ) then
				table.insert(cdbvars.petSpells, i)
			end
			i = i+1
		end
	end
end

function CDB_IconDraggingFrame_OnUpdate()
	if cdb_dragging then
		local xpos,ypos = GetCursorPosition()
		local xmin,ymin = Minimap:GetLeft(), Minimap:GetBottom()

		xpos = xmin-xpos/Minimap:GetEffectiveScale()+70
		ypos = ypos/Minimap:GetEffectiveScale()-ymin-70

		cdbvars["minimappos"] = math.deg(math.atan2(ypos,xpos))
		cdb_move_icon()
	end
end

function cdb_move_icon()

	local xpos,ypos
	local angle = cdbvars["minimappos"]

	xpos = 80*cos(angle)
	ypos = 80*sin(angle)

	CDB_IconFrame:SetPoint("TOPLEFT","Minimap","TOPLEFT",52-xpos,ypos-52)

end

function CooldownBars_slash(msg)
	if( msg == "on" ) then
		if( not cdbvars.on ) then
			cdbvars.on = true
			
			CooldownBars_init()
			CooldownBars_findCooldowns()
			
			DEFAULT_CHAT_FRAME:AddMessage("CDB on", 1, 1, 0 )
		else
			DEFAULT_CHAT_FRAME:AddMessage("CDB already on", 1, 1, 0 )
		end
	elseif( msg == "off" ) then
		if( cdbvars.on ) then
			cdbvars.on = false
			for i=1, 12 do
				getglobal( "CooldownBar"..i ).kill = true					
			end
			DEFAULT_CHAT_FRAME:AddMessage("CDB off", 1, 1, 0 )
		else
			DEFAULT_CHAT_FRAME:AddMessage("CDB not on", 1, 1, 0 )
		end
	elseif( msg == "menu" ) then
		CooldownBars_ShowOptions()
	elseif( msg == "unlock" ) then
		cdbvars["checks"]["locked"] = false
		cdb_setlocks("moveable")
	elseif( msg == "lock" ) then
		cdbvars["checks"]["locked"] = true
		cdb_setlocks("moveable")
	elseif( string.match( msg, "report") ) then
		if msg == "report" then
			if cdbvars["report"]["enable"] == true then
				cdbvars["report"]["enable"] = false
				cdb_setlocks("report")
				DEFAULT_CHAT_FRAME:AddMessage("<CDB> Reporting |cffff0000disabled")
			else
				cdbvars["report"]["enable"] = true
				cdb_setlocks("report")
				DEFAULT_CHAT_FRAME:AddMessage("<CDB> Reporting |cff00ff00enabled")
			end
		else
			for channel in string.gmatch( msg, "report (%a+)" ) do
				if (channel == "party") or (channel == "say") or (channel == "guild") or (channel == "yell") or (channel == "select") then
					cdbvars["report"]["channel"] = string.upper(channel)
				else
					DEFAULT_CHAT_FRAME:AddMessage("Invalid channel valid channels are: select, party, guild, say, yell")
				end
			end
		end
	elseif( string.match( msg, "style" ) ) then
		for style in string.gmatch( msg, "style (%a+)" ) do
			if( style == "seconds" ) or (style == "minutes") then
				cdbvars["style"] = style
			else
				DEFAULT_CHAT_FRAME:AddMessage("Invalid style valid styles are: minutes, seconds")
			end
		end
	elseif( string.match( msg, "groups" ) ) then
		CDB_ShowGroups()
	else
		if( cdbvars.on ) then
			DEFAULT_CHAT_FRAME:AddMessage("CDB on", 1, 1, 0 )
		else
			DEFAULT_CHAT_FRAME:AddMessage("CDB off", 1, 1, 0 )
		end
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00on: |cffffffffEnable CDB")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00off: |cffffffffDisable CDB")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00lock: |cffffffffLock bars in place")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00unlock: |cffffffffUnlock bars")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00menu: |cffffffffShow Config Dialog")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00groups: |cffffffffShow Groups Dialog")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00report: |cffffffffEnable/Disable reporting of Cooldowns to party/raid")
		DEFAULT_CHAT_FRAME:AddMessage("|cff00ff00style <minutes/seconds>: |cffffffffChange formating of the time string")
	end
end

function CooldownBars_GetItemName(bag, slot)
	if (bag == -1) then
        CDBTooltip:SetInventoryItem("player", slot);
	else
		CDBTooltip:SetBagItem(bag,slot);
	end

	local linetip = getglobal ("CDBTooltipTextLeft1");
    local text = linetip:GetText();

  if text then
    return text
  else
    return ""
  end
end

function CooldownBars_findCooldowns()
	
	--[[ This checks the highest rank of every spell and checks whether or not they're cooling
		down. It'll then check if the start time is different from what the previously set start
		time was, and if it is add it to the cooldown bars. ]]
	for key, val in pairs(cdbvars.spells) do
		local startTime, duration, flag = GetSpellCooldown( val, BOOKTYPE_SPELL )
		local name = GetSpellName( val, BOOKTYPE_SPELL )
		
		if( name == CDB_PREP and (startTime > (GetTime()-0.005)) and (duration == 600)) then
			CooldownBars_cdReset(CDB_PREP_SKILLS)
		elseif( name == CDB_CS and (startTime > (GetTime()-0.005)) and (duration == 600)) then
			CooldownBars_cdReset(CDB_CS_SKILLS)						
		end		
		
		if (duration > cdbvars["values"]["mintime"]) then
			if( not cdbvars["disabled"][name] ) then
				for k, v in pairs(cdbvars["omnigroup"]) do 
					if( string.match( name, k ) ) then
						name = v
						break
					end
				end
				if( cdbvars["groups"][name] ) then
					name = cdbvars["groups"][name]
				end
				
				if( startTime ~= cdbvars["cooldowns"][name] ) then					
					cdbvars["cooldowns"][name] = startTime
					CooldownBars_addCooldown( name, startTime, duration, 1, GetSpellTexture(val, BOOKTYPE_SPELL) )		
				end
			end
		end
	end
	if( cdbvars["checks"]["bagitems"] ) then
		--[[ Checks the bags for items that have cooldowns. These work slightly differently in addition to storing their start time these
			will also store which bar they're using to display(thus if you're equip the item and restart its 30 second cooldown then
			it will simply change the particular bar) ]]
		for i=0, 4 do
			local bagType = GetBagName(i)
			if (bagType ) and not ( string.match(bagType, "Ammo") or string.match(bagType, "Quiver") or string.match(bagType, "Wrapped") ) then
				for d=1, GetContainerNumSlots(i) do
					local texture = GetContainerItemInfo(i, d)
					if( texture ) then
						local startTime, duration = GetContainerItemCooldown(i,d)
						if( duration > cdbvars["values"]["mintime"] ) then
							local name = CooldownBars_GetItemName(i,d)
							if( not cdbvars["disabled"][name] ) then
								if ( string.find(name,"Potion")) then
									name = "Potion Cooldown"
								else
									for k, v in pairs(cdbvars["omnigroup"]) do 
										if( string.match( name, k ) ) then
											name = v
											break
										end
									end
								end
								if( cdbvars["groups"][name] ) then
									name = cdbvars["groups"][name]
								end
								if( not cdbvars["items"][name] ) then
									cdbvars["items"][name] = {}
								end
								if ( cdbvars["items"][name]["startTime"] ~= startTime ) and ( not cdbvars["disabled"][name] ) then
									cdbvars["items"][name]["startTime"] = startTime
									CooldownBars_addCooldown( name, startTime, duration, 2, texture )
								end
							end
						end
					end
				end
			end
		end
		
		for i=0, 19 do
			if( GetInventoryItemTexture("player", i) ~= nil ) then
				local startTime, duration = GetInventoryItemCooldown("player", i)
				local name = CooldownBars_GetItemName(-1,i)
					
				if( (name == CDB_RENATAKI) and (duration == 180) and (startTime > (GetTime()-0.005))) then
					CooldownBars_cdReset(CDB_RENATAKI_SKILLS)			
				end		
					
				if( duration > cdbvars["values"]["mintime"] ) then					
					if( not cdbvars["disabled"][name] ) then
						for k, v in pairs(cdbvars["omnigroup"]) do 
							if( string.match( name, k ) ) then
								name = v
								break
							end
						end
						if( cdbvars["groups"][name] ) then
							name = cdbvars["groups"][name]
						end
						if( not cdbvars["items"][name] ) then
							cdbvars["items"][name] = {}
						end
						if ( cdbvars["items"][name]["startTime"] ~= startTime ) and ( not cdbvars["disabled"][name] ) then
							cdbvars["items"][name]["startTime"] = startTime
							CooldownBars_addCooldown( name, startTime, duration, 2, GetInventoryItemTexture("player", i) )
						end
					end
				end
			end
		end
		
		
	end
	--[[ PET Cooldowns ]]
	if( cdbvars["checks"]["petskills"] ) and UnitExists("pet") then
		for key, val in pairs(cdbvars.petSpells) do
		
			local startTime, duration, flag = GetSpellCooldown(val, BOOKTYPE_PET)
			--local name = GetSpellName( val, BOOKTYPE_PET )
			--DEFAULT_CHAT_FRAME:AddMessage(name.." "..startTime.." "..duration.." "..flag, 1, 0, 0 )
			
			if (duration > cdbvars["values"]["mintime"] and ( flag ~= 0 ) ) then
				local name = GetSpellName( val, BOOKTYPE_PET )
				
				if( not cdbvars["disabled"][name] ) then
					for k, v in pairs(cdbvars["omnigroup"]) do 
						if( string.match( name, k ) ) then
							name = v
							break
						end
					end
					if( cdbvars["groups"][name] ) then
						name = cdbvars["groups"][name]
					end
					if( startTime ~= cdbvars["cooldowns"][name] ) and ( not cdbvars["disabled"][name] ) then
						cdbvars["cooldowns"][name] = startTime
						CooldownBars_addCooldown( name, startTime, duration, 1, GetSpellTexture(val, BOOKTYPE_PET) )
					end
				end
			end
			
		end
	end
end

function CooldownBars_cdReset(t)
	for i=1, 12 do
		local barframe = getglobal( "CooldownBar"..i )
		local text = getglobal("CooldownBar"..i).name
		for k, v in pairs(t) do
			if text == v then
				barframe.kill = true
			end
		end		
	end
end

function CooldownBars_addCooldown( name, startTime, duration, item, texture, slot, bag )
	local i, d
	local time = GetTime()
	
	
	--[[slot and bag were put in for the tooltip, not sure why its not completely working yet]]
	
	if( cdbvars["checks"]["cascade"] and cdbvars["checks"]["sort"] ) then
		d = 1
		endTime = startTime + duration
		while( getglobal("CooldownBar"..d):IsVisible() and (d <= CDB_COOLDOWNBARS) ) do
			if( endTime <= getglobal("CooldownBar"..d).endTime ) then
				break
			else
				d = d + 1
			end
		end
		if( d == 13 ) then
			return
		end
		for b=1, CDB_COOLDOWNBARS do
			if( getglobal("CooldownBar"..b).channeling ) then
				local text = getglobal("CooldownBar"..b).name
				if( not getglobal("CooldownBar"..b):IsVisible() ) then
					break
				end
				if( text == name ) then
					i = b
					break
				end
			end
		end
		if( i ~= d ) then
			if( i ) then
				--DEFAULT_CHAT_FRAME:AddMessage(i.." "..d.." "..name)
				if( i < d ) then
					d = d - 1
				end
				CooldownBar_Cascade(i)
				CooldownBar_shift(d)
				i = d
			else
				--DEFAULT_CHAT_FRAME:AddMessage(d.." shift "..name)
				CooldownBar_shift(d)
				i = d
			end
		else
			--DEFAULT_CHAT_FRAME:AddMessage(i.." equals "..d.." "..name)
		end
	else
		for b=1, CDB_COOLDOWNBARS do
			if( getglobal("CooldownBar"..b).channeling ) then
				local text = getglobal("CooldownBar"..b).name
				if( text == name ) then
					i = b
				end
			end
		end
		if( not i ) then			
			for b=1, CDB_COOLDOWNBARS do -- else find the first unused bar
				local barframe = getglobal( "CooldownBar"..b )
				if( not barframe:IsVisible() ) then
					i = b
					break
				end
			end
		end
	end	
	
	if( not i ) then -- if no bar is found quit dont add the cooldown.
		return
	end
	
	local text = nil
	local texttime = nil
	local icon = getglobal("CooldownBar"..i.."Icon")
	local barframe = getglobal( "CooldownBar"..i )
	if ( cdbvars["checks"]["hidetext"] and cdbvars["texture"]=="hide") then
		text = getglobal( "CooldownBar"..i.."BarRightText" )
		timetext = getglobal( "CooldownBar"..i.."BarLeftText" )
	else
		text = getglobal( "CooldownBar"..i.."BarLeftText" )
		timetext = getglobal( "CooldownBar"..i.."BarRightText" )
	end
	local bar = getglobal( "CooldownBar"..i.."Bar" )
	local bg = getglobal( "CooldownBar"..i.."BGBar" )
	
	if( item == 2 ) then --use different colors for items and skills
		barframe.item = true
		bar:SetStatusBarColor( unpack(cdbvars["itemcolor"]) )
		local r,g,b,a = unpack(cdbvars["itemcolor"])
		bg:SetStatusBarColor( r,g,b,0.25*a )
		barframe.bag = bag
		barframe.slot = slot
	elseif( item == 1 ) then
		barframe.item = false
		bar:SetStatusBarColor( unpack(cdbvars["skillcolor"]) )
		local r,g,b,a = unpack(cdbvars["skillcolor"])
		bg:SetStatusBarColor( r,g,b,0.25*a )
		barframe.skill = slot
	end
	
	barframe.channeling = true
	barframe.startTime = startTime
	barframe.endTime = startTime + duration
	barframe.duration = duration
	barframe.texture = texture
	barframe.name = name
	icon:SetTexture(texture)
	icon:SetTexCoord(.078, .92, .079, .937)
	text:SetText( name )
	local timeleft = barframe.endTime - time
	if( not cdbvars["checks"]["showminutes"] ) then -- if style is set to seconds, show seconds regardless
		timetext:SetText( string.format( "%.1f", timeleft ) )
	else -- if style is set to minutes, show minutes unless its <1min
		if( timeleft > 60 ) then
			local minutes = 0
			while( timeleft > 60 ) do
				minutes = minutes + 1
				timeleft = timeleft - 60
			end
			timetext:SetText( string.format( "%d:%2d", minutes, timeleft ) )
			
		else
			timetext:SetText( string.format( "%.1f", timeleft ) )
		end
	end
	
	bar:SetMinMaxValues( barframe.startTime, barframe.endTime )
	bar:SetValue( barframe.endTime )
	CDB_SetWidths()
	barframe:Show()
	barframe:SetAlpha( cdbvars["values"]["trans"] )
end

function CDB_SetWidths()
	
	if( cdbvars["checks"]["autoresize"] ) then
		local largestwidth = cdbvars["values"]["minbar"]
		for i=1, CDB_COOLDOWNBARS do 
			local barframe = getglobal("CooldownBar"..i)
			if( barframe:IsVisible() ) then
				local width = getglobal("CooldownBar"..i.."BarLeftText"):GetWidth() + getglobal("CooldownBar"..i.."BarRightText"):GetWidth() + 30
				if( width > largestwidth ) then
					largestwidth = width
				end
			end
		end
		
		local totalwidth = largestwidth + 10
		if( cdbvars["checks"]["showicons"] ) then
			totalwidth = totalwidth + cdbvars["values"]["barthickness"]
		end
		for i=1, CDB_COOLDOWNBARS do 
			local barframe = getglobal("CooldownBar"..i)
			local bar = getglobal("CooldownBar"..i.."Bar")
			local bg = getglobal("CooldownBar"..i.."BGBar")
			
			barframe:SetWidth(totalwidth)
			bar:SetWidth(largestwidth)
			bg:SetWidth(largestwidth)
		end
	else
		local maxwidth = cdbvars["values"]["minbar"]
		for i=1, CDB_COOLDOWNBARS do
			local barframe = getglobal("CooldownBar"..i)
			if( barframe.channeling ) then
				local width = maxwidth - getglobal("CooldownBar"..i.."BarRightText"):GetWidth() - 30
				local textwidth = getglobal("CooldownBar"..i.."BarLeftText"):GetWidth()
				if( textwidth > width ) then
					local textbar = getglobal("CooldownBar"..i.."BarLeftText")
					local text = getglobal("CooldownBar"..i.."BarLeftText"):GetText()
					local percent = width/textwidth
					percent = percent - 0.1
					local len = string.len( text )
					len = tonumber( string.format( "%d", len*percent ) )
					text = string.sub( text, 1, len ).."..."
					textbar:SetText( text )
				end
			end
		end
	end
end

function CooldownBars_OnUpdate( i )
	local barframe = getglobal( "CooldownBar"..i )
	local text = getglobal("CooldownBar"..i).name
	if( barframe.kill and ((not (text == CDB_PREP or text == CDB_CS or text == CDB_RENATAKI)) and ((barframe.endTime - GetTime()) > 0) ) ) then --on remove or don't track this kill will be set, next update kills the bar
		barframe.kill = false
		barframe.channeling = false
		barframe.fadeOut = true
		barframe.item = false
		barframe.bag = nil
		barframe.slot = nil
		barframe.bar = nil
		barframe.skill = nil
		barframe.enemy = false
		barframe.texture = nil
		barframe.name = nil
		return
	end
	if( barframe.channeling ) then
		
		local time = GetTime()
		local timetext = nil
		if ( cdbvars["checks"]["hidetext"] and cdbvars["texture"]=="hide") then
			timetext = getglobal( "CooldownBar"..i.."BarLeftText" )
		else
			timetext = getglobal( "CooldownBar"..i.."BarRightText" )
		end
		if( time >= barframe.endTime ) then --when the times up
			local name = barframe.name
			if( cdbvars["checks"]["alerts"] ) and ( barframe.duration > cdbvars["values"]["minalert"] ) then
				CooldownAlertLabel1Text:SetText(name.." cooldown finished!")
				CooldownAlert:SetAlpha(1)
				CooldownAlert.holdtime = time + 2
				CooldownAlert.state = 1
				CooldownAlert:Show()
				if( cdbvars["checks"]["sound"] ) then
					PlaySound("Deathbind Sound")
				end
			end
			barframe.channeling = false
			barframe.fadeOut = true
			timetext:SetText("Ready!")
			if( barframe.item ) then
				barframe.item = false
				--cdbvars["items"][name]["bar"] = nil
			elseif( barframe.enemy ) then
				barframe.enemy = false
			end
			barframe.name = nil
			barframe.slot = nil
			barframe.bag = nil
			barframe.skill = nil
			CDB_SetWidths()
			return
		end
		
		local bar = getglobal( "CooldownBar"..i.."Bar" )
		
		local timeleft = barframe.endTime - time
		local barval = barframe.startTime + barframe.endTime - time
		if( not cdbvars["checks"]["showminutes"] ) then
			if( cdbvars["values"]["precision"] ~= 0 ) then
				timetext:SetText( string.format( "%."..cdbvars["values"]["precision"].."f", timeleft ) )
			else
				timetext:SetText( string.format( "%ds", timeleft ) )
			end
		else
			if( timeleft > 60 ) then
				local minutes = 0
				while( timeleft > 60 ) do
					minutes = minutes + 1
					timeleft = timeleft - 60
				end
				
				timetext:SetText( string.format( "%d:%02d", minutes, timeleft ) )
				
			else
				if( cdbvars["values"]["precision"] ~= 0 ) then
					timetext:SetText( string.format( "%."..cdbvars["values"]["precision"].."f", timeleft ) )
				else
					timetext:SetText( string.format( "%ds", timeleft ) )
				end
			end
		end
		bar:SetValue( barval )
	elseif( barframe.fadeOut ) then
		local alpha = barframe:GetAlpha()
		if( alpha > 0 ) then
			barframe:SetAlpha( alpha - 0.05 )
		else
			barframe.fadeOut = false
			if( cdbvars["checks"]["cascade"] ) then
				CooldownBar_Cascade(i)
			else
				barframe:Hide()
			end
		end
	end
end
	
function CooldownBars_init()
	cdbvars.init = true
	cdbvars.numSpells = 1
	cdbvars.spells = {}
	cdbvars.stealth = {}
	cdbvars.cooldowns = {}
	cdbvars.items = {}
	
	for i=1, CDB_COOLDOWNBARS do --make the popup look like a normal tooltip
		local popup = getglobal("CooldownBar"..i.."Popup")
		popup:SetBackdropBorderColor( TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b )
		popup:SetBackdropColor( TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b )
	end
	
	while( GetSpellName(cdbvars.numSpells, BOOKTYPE_SPELL) ) do --find the top rank of every spell
		local name = GetSpellName( cdbvars.numSpells, BOOKTYPE_SPELL )
		local nextName = GetSpellName( cdbvars.numSpells+1, BOOKTYPE_SPELL )
		if( name ~= nextName ) then
			if (name == CDB_STEALTH or name == CDB_PROWL or name == CDB_SHADOWMELD) then
				table.insert( cdbvars.stealth, cdbvars.numSpells)
			else 
				table.insert( cdbvars.spells, cdbvars.numSpells )
			end
		end
		cdbvars.numSpells = cdbvars.numSpells + 1
	end
	for key,val in pairs(cdbvars["cooldowns"]) do
		cdbvars["cooldowns"][key] = false
	end
	for key,val in pairs(cdbvars["items"]) do
		cdbvars["items"][key]["startTime"] = 0
	end

	cdb_setSettings()
		
end

function cdb_setSettings()
	local i = 1

	if cdbvars["checks"]["hideminimap"] then
		CDB_IconFrame:Hide()
	else
		CDB_IconFrame:Show()
	end
	
	while( i <= CDB_COOLDOWNBARS ) do
		local m = 1
		for l=1, (cdbvars["values"]["columns"]-1) do
			if( (i+l) > CDB_COOLDOWNBARS ) then
				break
			end
			local barframe = getglobal("CooldownBar"..(i+l))
			barframe:ClearAllPoints()
			barframe:SetPoint("TOPLEFT", "CooldownBar"..(l-1+i), "TOPRIGHT", cdbvars["values"]["bardistance"]-5, 0 )
			m = m+1
		end
		m = i + m
		if( m > CDB_COOLDOWNBARS ) then
			break
		end
		local barframe = getglobal("CooldownBar"..m)
		barframe:ClearAllPoints()
		if( cdbvars["checks"]["down"] ) then
			barframe:SetPoint("TOPLEFT", "CooldownBar"..i, "BOTTOMLEFT", 0, -cdbvars["values"]["bardistance"]+5 )
		else
			barframe:SetPoint("BOTTOMLEFT", "CooldownBar"..i, "TOPLEFT", 0, cdbvars["values"]["bardistance"]-5 )
		end
		i = m
	end

	for b=1, CDB_COOLDOWNBARS do
		local lefttext = getglobal( "CooldownBar"..b.."BarLeftText" )
		local righttext = getglobal( "CooldownBar"..b.."BarRightText" )
		local baricon = getglobal( "CooldownBar"..b.."Icon" )
		if cdbvars["checks"]["flipbars"] then
			baricon:ClearAllPoints()
			baricon:SetPoint("TOPRIGHT", "CooldownBar"..b, "TOPRIGHT", -5, -5 )
			righttext:ClearAllPoints()
			righttext:SetPoint("TOPLEFT", "CooldownBar"..b, "TOPLEFT", 5, -5 )
			lefttext:ClearAllPoints()
			if cdbvars["checks"]["showicons"] then
				lefttext:SetPoint("RIGHT", "CooldownBar"..b.."Icon", "LEFT", -1, 0 )
			else
				lefttext:SetPoint("TOPRIGHT", "CooldownBar"..b, "TOPRIGHT", -5, -5 )
			end
		else
			baricon:ClearAllPoints()
			baricon:SetPoint("TOPLEFT", "CooldownBar"..b, "TOPLEFT", 5, -5 )
			lefttext:ClearAllPoints()
			if cdbvars["checks"]["showicons"] then
				lefttext:SetPoint("LEFT", "CooldownBar"..b.."Icon", "RIGHT", 1, 0 )
			else
				lefttext:SetPoint("TOPLEFT", "CooldownBar"..b, "TOPLEFT", 5, -5 )
			end
			righttext:ClearAllPoints()
			righttext:SetPoint("TOPRIGHT", "CooldownBar"..b, "TOPRIGHT", -5, -5 )
		end
	end

	
	if ( cdbvars["checks"]["border"] ) then
		for i=1, CDB_COOLDOWNBARS do
			getglobal("CooldownBar"..i):SetBackdrop({bgFile="Interface\\Tooltips\\UI-Tooltip-Background",
													edgeFile="Interface\\Addons\\CooldownBars\\textures\\CC-Bar-Border",
													tile = true, tileSize = 16, edgeSize = 16,
													insets = { left = 5, right = 5, top = 5, bottom = 5 }})
		end
	else
		for i=1, CDB_COOLDOWNBARS do
			getglobal("CooldownBar"..i):SetBackdrop({bgFile="Interface\\Tooltips\\UI-Tooltip-Background",
													edgeFile="Interface\\Tooltips\\UI-Tooltip-Border",
													tile = true, tileSize = 16, edgeSize = 16,
													insets = { left = 5, right = 5, top = 5, bottom = 5 }})
		end
	end
	
	if ( cdbvars["texture"] == "cilo" ) then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."Bar"):SetStatusBarTexture("Interface\\Addons\\CooldownBars\\textures\\cilo")
			getglobal("CooldownBar"..i.."BGBar"):SetStatusBarTexture("Interface\\Addons\\CooldownBars\\textures\\cilo")
		end
	elseif ( cdbvars["texture"] == "smooth" ) then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."Bar"):SetStatusBarTexture("Interface\\Addons\\CooldownBars\\textures\\smooth")
			getglobal("CooldownBar"..i.."BGBar"):SetStatusBarTexture("Interface\\Addons\\CooldownBars\\textures\\smooth")
		end
	elseif ( cdbvars["texture"] == "standard") then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."Bar"):SetStatusBarTexture("Interface\\TargetingFrame\\UI-TargetingFrame-BarFill")
			getglobal("CooldownBar"..i.."BGBar"):SetStatusBarTexture("Interface\\TargetingFrame\\UI-TargetingFrame-BarFill")
		end
	elseif ( cdbvars["texture"] == "hide") then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."Bar"):SetStatusBarTexture("")
			getglobal("CooldownBar"..i.."BGBar"):SetStatusBarTexture("")
		end
	end
	
	if( cdbvars["checks"]["showicons"] ) then
		for i=1, CDB_COOLDOWNBARS do
			local bar = getglobal("CooldownBar"..i.."Bar")
			local bg = getglobal("CooldownBar"..i.."BGBar")
			local barframe = getglobal("CooldownBar"..i)
			
			barframe:SetWidth(cdbvars["values"]["minbar"] + cdbvars["values"]["barthickness"] + 10)
			bar:SetWidth(cdbvars["values"]["minbar"])
			bg:SetWidth(cdbvars["values"]["minbar"])
			
			bar:ClearAllPoints()
			bg:ClearAllPoints()
			if cdbvars["checks"]["flipbars"] then
				bar:SetPoint("RIGHT", "CooldownBar"..i.."Icon", "LEFT", 0, 0 )
				bg:SetPoint("RIGHT", "CooldownBar"..i.."Icon", "LEFT", 0, 0 )
			else
				bar:SetPoint("LEFT", "CooldownBar"..i.."Icon", "RIGHT", 0, 0 )
				bg:SetPoint("LEFT", "CooldownBar"..i.."Icon", "RIGHT", 0, 0 )
			end
		end
	else
		for i=1, CDB_COOLDOWNBARS do
			local bar = getglobal("CooldownBar"..i.."Bar")
			local bg = getglobal("CooldownBar"..i.."BGBar")
			local barframe = getglobal("CooldownBar"..i)
			
			barframe:SetWidth(cdbvars["values"]["minbar"] + 10)
			bar:SetWidth(cdbvars["values"]["minbar"])
			bg:SetWidth(cdbvars["values"]["minbar"])
			
			bar:ClearAllPoints()
			bg:ClearAllPoints()
			bar:ClearAllPoints()
			bg:ClearAllPoints()
			if cdbvars["checks"]["flipbars"] then
				bar:SetPoint("TOPRIGHT", "CooldownBar"..i, "TOPRIGHT", -5, -5 )
				bg:SetPoint("TOPRIGHT", "CooldownBar"..i, "TOPRIGHT", -5, -5 )
			else
				bar:SetPoint("TOPLEFT", "CooldownBar"..i, "TOPLEFT", 5, -5 )
				bg:SetPoint("TOPLEFT", "CooldownBar"..i, "TOPLEFT", 5, -5 )
			end
		end
	end
	
	for i=1, CDB_COOLDOWNBARS do
		getglobal("CooldownBar"..i):SetHeight( cdbvars["values"]["barthickness"] + 10 )
		getglobal("CooldownBar"..i):SetScale( cdbvars["values"]["scale"] )
		getglobal("CooldownBar"..i.."Bar"):SetHeight( cdbvars["values"]["barthickness"] )
		getglobal("CooldownBar"..i.."BGBar"):SetHeight( cdbvars["values"]["barthickness"] )
		if( cdbvars["checks"]["showicons"] ) then
			getglobal("CooldownBar"..i.."Icon"):SetHeight( cdbvars["values"]["barthickness"] )
			getglobal("CooldownBar"..i.."Icon"):SetWidth( cdbvars["values"]["barthickness"] )
			getglobal("CooldownBar"..i.."Icon"):SetTexCoord(.078, .92, .079, .937)
			getglobal("CooldownBar"..i.."Icon"):Show()
		else
			getglobal("CooldownBar"..i.."Icon"):Hide()
		end
	end
	
	for i=1, CDB_COOLDOWNBARS do 
		getglobal("CooldownBar"..i):SetAlpha( cdbvars["values"]["trans"] )
	end
	
	if( cdbvars["checks"]["hidetext"] and cdbvars["texture"]=="hide") then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."BarLeftText"):Show()
			getglobal("CooldownBar"..i.."BarRightText"):Hide()
		end
	elseif( cdbvars["checks"]["hidetext"]) then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."BarLeftText"):Hide()
		end
	else
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."BarLeftText"):Show()
			getglobal("CooldownBar"..i.."BarLeftText"):SetText(getglobal("CooldownBar"..i).name)
		end
	end
	
	if( cdbvars["checks"]["hidetime"] and cdbvars["checks"]["hidetext"] and cdbvars["texture"]=="hide") then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."BarLeftText"):Hide()
		end
	elseif( not cdbvars["checks"]["hidetime"] and cdbvars["checks"]["hidetext"] and cdbvars["texture"]=="hide") then
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."BarRightText"):Hide()
		end
	else
		for i=1, CDB_COOLDOWNBARS do 
			getglobal("CooldownBar"..i.."BarRightText"):Show()
		end
	end
	
	for i=1, CDB_COOLDOWNBARS do
		getglobal("CooldownBar"..i.."BarLeftText"):SetTextColor(unpack(cdbvars["textcolor"]))
		getglobal("CooldownBar"..i.."BarRightText"):SetTextColor(unpack(cdbvars["timecolor"]))
		if cdbvars["texture"] == "hide" then
			getglobal("CooldownBar"..i):SetBackdropBorderColor(unpack(cdbvars["bordercolorhidden"]))
			getglobal("CooldownBar"..i):SetBackdropColor(unpack(cdbvars["backdropcolorhidden"]))
		else
			getglobal("CooldownBar"..i):SetBackdropBorderColor(unpack(cdbvars["bordercolor"]))
			getglobal("CooldownBar"..i):SetBackdropColor(unpack(cdbvars["backdropcolor"]))
		end
	end
	
	CooldownAlertLabel1:SetScale(cdbvars["values"]["announcescale"])
		
	if cdbvars["report"]["enable"] == true then
		cdb_setlocks("report")
	else
		cdb_setlocks("moveable")
	end
end

function cdb_setlocks(type)
	if type == "moveable" then
		if( not cdbvars["checks"]["locked"] ) then
			CooldownAlert.locked = false
			CooldownAlert:Show()
			CooldownAlert:EnableMouse(1)
			CooldownAlert:SetAlpha(1)
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i):EnableMouse(1)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."Bar"):EnableMouse(1)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."BGBar"):EnableMouse(1)
			end
			CooldownFrame:Show()
		else
			CooldownAlert.locked = true
			CooldownAlert.state = 2
			CooldownAlert:EnableMouse(false)
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i):EnableMouse(false)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."Bar"):EnableMouse(false)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."BGBar"):EnableMouse(false)
			end
			CooldownFrame:Hide()
		end
	elseif type == "report" then
		if  cdbvars["report"]["enable"] == true then
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i):EnableMouse(1)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."Bar"):EnableMouse(1)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."BGBar"):EnableMouse(1)
			end
		else
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i):EnableMouse(false)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."Bar"):EnableMouse(false)
			end
			for i=1, CDB_COOLDOWNBARS do
				getglobal("CooldownBar"..i.."BGBar"):EnableMouse(false)
			end
		end
	end		
end

function CooldownBars_OnClick( button, name )
	if( string.gmatch( name, "Bar(%d+)Bar" ) ) and (button == "RightButton") then
		for w in string.gmatch( name, "(CooldownBar%d+)%a") do
			getglobal(w.."Popup"):Show()
		end
	elseif( button == "LeftButton" ) then
		if IsShiftKeyDown() and  cdbvars["report"]["enable"] == true then
			for w in string.gmatch( name, "(CooldownBar%d+)%a") do
				local skill = getglobal(name.."LeftText"):GetText()
				local timeleft = getglobal(name.."RightText"):GetText()
				
				if cdbvars["report"]["channel"] == "SELECT" then 
					if UnitInRaid("player") or ( UnitInParty("player") and GetNumPartyMembers() > 0 ) then
						if UnitInRaid("player") then
							cdbvars["report"]["current"] = "RAID"
						else
							cdbvars["report"]["current"] = "PARTY"
						end
					else
						cdbvars["report"]["current"] = "SAY"
					end
				else
					cdbvars["report"]["current"] = cdbvars["report"]["channel"]
				end				
				
				if cdbvars["report"]["current"] then
					SendChatMessage("<CDB> -="..skill.."=- available in: "..timeleft, cdbvars["report"]["current"] )
				end
			end		
		else
			for w,x in pairs(string.gmatch( name, "CooldownBar(%d+)PopupButton(%d)" )) do
				getglobal("CooldownBar"..w.."Popup"):Hide()
				if( x == "1" ) then
					getglobal("CooldownBar"..w).kill = true
				elseif( x == "2" ) then
					getglobal( "CooldownBar"..w).kill = true
					cdbvars["disabled"][getglobal("CooldownBar"..w).name] = true
				end
			end
		end
	end
end

function CooldownBars_ShowOptions()
	if CooldownBarsOptions:IsVisible() then
		CooldownBarsOptions:Hide()
	else
		for i=1, CDB_NUM_CHECKS do 
			if( cdbvars["checks"][CDB_CHECKS[i]] ) then
				getglobal("CooldownBarsOptionsCheckButton"..i):SetChecked(1)
			else
				getglobal("CooldownBarsOptionsCheckButton"..i):SetChecked(0)
			end
		end
		
		if cdbvars["texture"] == "standard" then	
			UIDropDownMenu_SetSelectedValue(CooldownBarsOptionsTextures, 1)
			UIDropDownMenu_SetText(CDB_TEXTURES_STANDARD, CooldownBarsOptionsTextures)
		elseif cdbvars["texture"] == "cilo" then	
			UIDropDownMenu_SetSelectedValue(CooldownBarsOptionsTextures, 2)
			UIDropDownMenu_SetText(CDB_TEXTURES_CILO, CooldownBarsOptionsTextures)
		elseif cdbvars["texture"] == "smooth" then	
			UIDropDownMenu_SetSelectedValue(CooldownBarsOptionsTextures, 3)
			UIDropDownMenu_SetText(CDB_TEXTURES_SMOOTH, CooldownBarsOptionsTextures)
		elseif cdbvars["texture"] == "hide" then	
			UIDropDownMenu_SetSelectedValue(CooldownBarsOptionsTextures, 4)
			UIDropDownMenu_SetText(CDB_TEXTURES_HIDE, CooldownBarsOptionsTextures)
		end
		
		for i=1, CDB_NUM_SLIDERS do 
			getglobal("CooldownBarsOptionsHorizontalSlider"..i.."Slider"):SetValue( cdbvars["values"][CDB_SLIDERS[i]] )
		end
		
		for i=1, CDB_NUM_COLORS do
			local swatch = getglobal("CooldownBarsOptionsColor"..i.."Swatch")
			swatch.r, swatch.g, swatch.b, swatch.a = unpack(cdbvars[CDB_COLORS[i]])
			swatch:SetVertexColor(unpack(cdbvars[CDB_COLORS[i]]))
		end
		
		CooldownBarsOptions:Show()
	end

end

function CooldownBars_SaveOptions()
	for i=1, CDB_NUM_CHECKS do 
		if( getglobal("CooldownBarsOptionsCheckButton"..i):GetChecked() == 1 ) then
			cdbvars["checks"][CDB_CHECKS[i]] = true
		else
			cdbvars["checks"][CDB_CHECKS[i]] = false
		end
	end
	
	if UIDropDownMenu_GetSelectedValue( CooldownBarsOptionsTextures) == 1 then
		cdbvars["texture"] = "standard"
	elseif UIDropDownMenu_GetSelectedValue( CooldownBarsOptionsTextures) == 2 then
		cdbvars["texture"] = "cilo"
	elseif UIDropDownMenu_GetSelectedValue( CooldownBarsOptionsTextures) == 3 then
		cdbvars["texture"] = "smooth"
	elseif UIDropDownMenu_GetSelectedValue( CooldownBarsOptionsTextures) == 4 then
		cdbvars["texture"] = "hide"
	end
	
	for i=1, CDB_NUM_SLIDERS do
		cdbvars["values"][CDB_SLIDERS[i]] = getglobal("CooldownBarsOptionsHorizontalSlider"..i.."Slider"):GetValue()
	end
	
	for i=1, CDB_NUM_COLORS do 
		local swatch = getglobal("CooldownBarsOptionsColor"..i.."Swatch")
		cdbvars[CDB_COLORS[i]] = { swatch.r, swatch.g, swatch.b, swatch.a }
	end
	CooldownBarsOptions:Hide()
	
	cdb_setSettings()
end

local CDBCancelFunc = {
	[1] = function(x) CDBCancelColor(1, x) end,
	[2] = function(x) CDBCancelColor(2, x) end,
	[3] = function(x) CDBCancelColor(3, x) end,
	[4] = function(x) CDBCancelColor(4, x) end,
	[5] = function(x) CDBCancelColor(5, x) end,
	[6] = function(x) CDBCancelColor(6, x) end
}

local CDBSetColorFunc = {
	[1] = function() CDBSetColor(1) end,
	[2] = function() CDBSetColor(2) end,
	[3] = function() CDBSetColor(3) end,
	[4] = function() CDBSetColor(4) end,
	[5] = function() CDBSetColor(5) end,
	[6] = function() CDBSetColor(6) end
}

local CDBSetOpacityFunc = {
	[1] = function() CDBSetOpacity(1) end,
	[2] = function() CDBSetOpacity(2) end,
	[3] = function() CDBSetOpacity(3) end,
	[4] = function() CDBSetOpacity(4) end,
	[5] = function() CDBSetOpacity(5) end,
	[6] = function() CDBSetOpacity(6) end
}

function CDB_ColorPicker(id)
	CloseMenus()
	local texture = getglobal("CooldownBarsOptionsColor"..id.."Swatch")
	ColorPickerFrame.func = CDBSetColorFunc[id]
	ColorPickerFrame:SetColorRGB(texture.r, texture.g, texture.b)
	ColorPickerFrame.previousValues = {r = texture.r, g = texture.g, b = texture.b, opacity =texture.a}
	ColorPickerFrame.cancelFunc = CDBCancelFunc[id]
	ColorPickerFrame.hasOpacity = true
	ColorPickerFrame.opacity = 1 - texture.a
	ColorPickerFrame.opacityFunc = CDBSetOpacityFunc[id]
	
	ColorPickerFrame:Show()
end

function CDBSetOpacity(id)
	local a = 1 - OpacitySliderFrame:GetValue()
	local texture = getglobal("CooldownBarsOptionsColor"..id.."Swatch")
	--DEFAULT_CHAT_FRAME:AddMessage(id)
	texture:SetAlpha(a)
	texture.a = a
end

function CDBSetColor(id)
	local r, g, b = ColorPickerFrame:GetColorRGB()
	local texture = getglobal("CooldownBarsOptionsColor"..id.."Swatch")
	--SHTSetOpacity(id)
	texture:SetVertexColor(r, g, b)
	texture.r = r
	texture.g = g
	texture.b = b
end

function CDBCancelColor(id, prev)
	local texture = getglobal("CooldownBarsOptionsColor"..id.."Swatch")
	local r = prev.r
	local g = prev.g
	local b = prev.b
	local a = prev.opacity
	texture:SetVertexColor(r, g, b)
	texture:SetAlpha( a )
	texture.r = r
	texture.g = g
	texture.b = b
	texture.a = a
end

function CooldownAlert_OnLoad()
	this:RegisterForDrag("LeftButton")
end

function CooldownAlert_OnUpdate()
	if( this.locked ) then
		if( this.state == 1 ) then
			local time = GetTime()
			if( time >= this.holdtime ) then
				this.state = 2
			end
		elseif( this.state == 2 ) then
			local alpha = this:GetAlpha() - 0.05
			if( alpha > 0 ) then
				this:SetAlpha(alpha)
			else
				this.state = 0
				this:Hide()
			end
		end
	end
end

function CooldownBar_shift(id, pos)	
	if( not id ) then
		return
	end
	if( not pos ) then
		for i=1, CDB_COOLDOWNBARS do 
			if( not getglobal("CooldownBar"..i):IsVisible() ) then
				pos = i-1
				break
			end
		end
	end
	
	if( not pos ) then
		return
	end
	
	if( pos < id ) or ( (pos == 12 ) and (getglobal("CooldownBar"..pos):IsVisible() ) ) then
		CDB_SetWidths()
		return
	end
	
	CooldownBar_copy(pos+1, pos)
	getglobal("CooldownBar"..(pos+1)):Show()
	CooldownBar_shift(id, pos-1)
	
end

function CooldownBar_Cascade(id)
	if( (id == 12) or (not getglobal("CooldownBar"..(id+1)):IsVisible() ) ) then
		getglobal("CooldownBar"..id):Hide()
		CDB_SetWidths()
		return
	end
	
	CooldownBar_copy(id, id+1)
	CooldownBar_Cascade(id+1)
end

function CooldownBar_copy(to, from)
	
	local barframeto = getglobal("CooldownBar"..to)
	local barto = getglobal("CooldownBar"..to.."Bar")
	local bgto = getglobal("CooldownBar"..to.."BGBar")
	local lefttextto = getglobal("CooldownBar"..to.."BarLeftText")
	local righttextto = getglobal("CooldownBar"..to.."BarRightText")
	local texto = getglobal("CooldownBar"..to.."Icon")
	
	local barframe = getglobal("CooldownBar"..from)
	local bar = getglobal("CooldownBar"..from.."Bar")
	local bg = getglobal("CooldownBar"..from.."BGBar")
	local lefttext = getglobal("CooldownBar"..from.."BarLeftText")
	local righttext = getglobal("CooldownBar"..from.."BarRightText")
	local tex = getglobal("CooldownBar"..from.."Icon")
	
	barframeto.channeling = barframe.channeling
	barframeto.fadeOut = barframe.fadeOut
	barframeto.item = barframe.item
	barframeto.bag = barframe.bag
	barframeto.slot = barframe.slot
	barframeto.bar = barframe.bar
	barframeto.skill = barframe.skill
	barframeto.enemy = barframe.enemy
	barframeto.texture = barframe.texture
	barframeto.name = barframe.name
	barframeto.startTime = barframe.startTime
	barframeto.endTime = barframe.endTime
	barframeto.duration = barframe.duration
	barframeto.kill = false
	
	barto:SetMinMaxValues(barframeto.startTime, barframeto.endTime)
	barto:SetValue(bar:GetValue())
	local r,g,b,a
	if( barframe.item ) then
		r,g,b,a = unpack( cdbvars["itemcolor"] )
	else
		r,g,b,a = unpack( cdbvars["skillcolor"] )
	end
	barto:SetStatusBarColor(r,g,b,a)
	bgto:SetStatusBarColor(r,g,b,0.25*a)
	
	barframeto:SetAlpha(barframe:GetAlpha())
	
	lefttextto:SetText(lefttext:GetText())
	righttextto:SetText(righttext:GetText())
	texto:SetTexture(barframeto.texture)
end

function CDB_ShowGroups()
	if CooldownBarsGroups:IsVisible() then
		CooldownBarsGroups:Hide()
	else
		cdbgroups = {}
		table.insert( cdbgroups, "disabled" )
		cdbmembers = {}
		cdbmembers["disabled"] = {}
		for key, val in pairs(cdbvars["groups"]) do
			--DEFAULT_CHAT_FRAME:AddMessage(key.." "..val)
			if( not cdbmembers[val] ) then
				cdbmembers[val] = {}
				table.insert( cdbgroups, val )
			end
			
			table.insert( cdbmembers[val], key )
		end
		
		for key, val in pairs(cdbvars["omnigroup"]) do 
			if( not cdbmembers[val] ) then
				cdbmembers[val] = {}
				table.insert( cdbgroups, val )
			end
			table.insert( cdbmembers[val], "%"..key )
		end
		
		for key, val in pairs(cdbvars["disabled"]) do 
			table.insert( cdbmembers["disabled"], key )
		end
		
		CDBMembersScrollBar.selected = nil
		CDBGroupsScrollBar.selected = nil

		CDBMembersScrollBar_Update()
		CDBGroupsScrollBar_Update()
		CooldownBarsGroups:Show()
	end
end

function CDB_AddGroup(group)
	if(group) and (group ~= "") and ( not cdbmembers[group] ) then
		cdbmembers[group] = {}
		table.insert( cdbgroups, group )
		CDBMembersScrollBar_Update()
		CDBGroupsScrollBar_Update()
	end
end

function CDBButton_OnClick()
	this:LockHighlight()
	if( string.match(this:GetName(), "Groups") ) then
		CDBGroupsScrollBar.selected = this:GetID() + FauxScrollFrame_GetOffset(CDBGroupsScrollBar)
		CDBMembersScrollBar.selected = nil
		CDBMembersScrollBar_Update()
		CDBGroupsScrollBar_Update()
	else
		CDBMembersScrollBar.selected = this:GetID() + FauxScrollFrame_GetOffset(CDBMembersScrollBar)
	end
end

function CDBMembersScrollBar_Update()
	local line -- 1 through 10 of our window to scroll
	local lineplusoffset -- an index into our data calculated from the scroll offset
	local size = 0
	if( CDBGroupsScrollBar.selected ) then
		size = table.getn( cdbmembers[cdbgroups[CDBGroupsScrollBar.selected]] )
	end
	FauxScrollFrame_Update(CDBMembersScrollBar,size,10,16)
	for line=1,10 do
		lineplusoffset = line + FauxScrollFrame_GetOffset(CDBMembersScrollBar)
		if( lineplusoffset <= size ) and CDBGroupsScrollBar.selected then
			getglobal("CDBMembersButton"..line):SetText(cdbmembers[cdbgroups[CDBGroupsScrollBar.selected]][lineplusoffset])
			getglobal("CDBMembersButton"..line):Show()
		else
			getglobal("CDBMembersButton"..line):Hide()
		end
	end
end

function CDBGroupsScrollBar_Update()
	local line -- 1 through 10 of our window to scroll
	local lineplusoffset -- an index into our data calculated from the scroll offset
	local size = table.getn( cdbgroups )
	FauxScrollFrame_Update(CDBGroupsScrollBar,size,10,16)
	for line=1,10 do
		lineplusoffset = line + FauxScrollFrame_GetOffset(CDBGroupsScrollBar)
		if( lineplusoffset <= size ) then
			getglobal("CDBGroupsButton"..line):SetText(cdbgroups[lineplusoffset])
			getglobal("CDBGroupsButton"..line):Show()
		else
			getglobal("CDBGroupsButton"..line):Hide()
		end
	end
end
 
function CDB_DeleteGroup()
	if( CDBGroupsScrollBar.selected ) then
		cdbmembers[cdbgroups[CDBGroupsScrollBar.selected]] = nil
		table.remove( cdbgroups, CDBGroupsScrollBar.selected )
		CDBGroupsScrollBar.selected = nil
		CDBMembersScrollBar_Update()
		CDBGroupsScrollBar_Update()
	end
end

function CDBPopup_OnUpdate()
	if( not MouseIsOver( this ) ) and ( not MouseIsOver( this:GetParent() ) ) then
		this:Hide()
	end
end

function CDB_DeleteMember()
	if( CDBMembersScrollBar.selected ) then
		table.remove( cdbmembers[cdbgroups[CDBGroupsScrollBar.selected]], CDBMembersScrollBar.selected )
		CDBMembersScrollBar.selected = nil
		CDBMembersScrollBar_Update()
	end
end

function CDB_AddMember(member)
	if (CDBGroupsScrollBar.selected) and (member) and (member ~= "") and ( not cdbmembers[member] ) then
		table.insert( cdbmembers[cdbgroups[CDBGroupsScrollBar.selected]], member )
		CDBMembersScrollBar_Update()
	end
end

function CDB_SaveGroups()
	cdbvars["groups"] = {}
	cdbvars["disabled"] = {}
	for key, val in pairs(cdbmembers) do
		for k, v in pairs(val) do
			if( key == "disabled" ) then
				cdbvars["disabled"][v] = true
			elseif( string.sub( v, 1, 1 ) == "%" ) then
				cdbvars["omnigroup"][string.sub(v, 2 )] = key
			else
				cdbvars["groups"][v] = key
			end
		end
	end
	CooldownBarsGroups:Hide()
end

StaticPopupDialogs["CDB_ADDGROUP"] = {
	text = CDB_ADDGROUP_TEXT,
	button1 = TEXT(ACCEPT),
	button2 = TEXT(CANCEL),
	hasEditBox = 1,
	maxLetters = 30,
	OnAccept = function()
		local editBox = getglobal(this:GetParent():GetName().."EditBox");
		if (editBox:GetText()~=nil) then
			if (string.len(editBox:GetText())~=0) then
				CDB_AddGroup(editBox:GetText());
			end
		end
		this:GetParent():Hide();
	end,
	OnShow = function()
		getglobal(this:GetName().."EditBox"):SetFocus();
	end,
	OnHide = function()
		if ( ChatFrameEditBox:IsVisible() ) then
			ChatFrameEditBox:SetFocus();
		end
		getglobal(this:GetName().."EditBox"):SetText("");
	end,
	EditBoxOnEnterPressed = function()
		local editBox = getglobal(this:GetParent():GetName().."EditBox");
		if (editBox:GetText()~=nil) then
			if (string.len(editBox:GetText())~=0) then
				CDB_AddGroup(editBox:GetText());
			end
		end
		this:GetParent():Hide();
	end,
	EditBoxOnEscapePressed = function()
		this:GetParent():Hide();
	end,
	timeout = 0,
	exclusive = 1,
	whileDead = 1,
	hideOnEscape = 1
};
