--[[----------------------------------------------
Autorespond created by Ayradyss in the first and enhanced by Chef de Loup

The features of the mod in the following:
- multiply responses with multiply keywords for each response
- responses can be handled as text with links or as script code
- several controls for each response for input and output of a response
--]]-----------------------------------------------


--[[-----------------------------------------------
global variables
--]]-----------------------------------------------
AutoRespondMainOptions = {}; -- SavedVariable - MainOptions
AutoRespondOptions = {}; -- SavedVariable - Responds and Options

local Realm; -- realm of active player
local Player; -- name of active player

local VariablesLoaded = nil; -- flag to check if Variables was loaded
local Initialized = nil; -- flag to check if previous initialize

local ActiveOption = 1; -- position of actual respond
local AR_Version= "2.0.4"; -- version of AR

--[[--------------------------------------------------------------------------------------------
functions for the main frame
--]]--------------------------------------------------------------------------------------------


--[[-----------------------------------------------
function for registering main events and slashcommands of the mod
--]]-----------------------------------------------
function AutoRespond_OnLoad()
	-- register main events
	this:RegisterEvent("PLAYER_ENTERING_WORLD");
	this:RegisterEvent("PLAYER_LEAVING_WORLD");
	this:RegisterEvent("VARIABLES_LOADED");

	-- register slashcommand and handler function
	SlashCmdList["AUTORESPOND"] = AutoRespond_SlashHandler;
	SLASH_AUTORESPOND1 = "/AutoRespond";
	SLASH_AUTORESPOND2 = "/ar";
end


--[[-----------------------------------------------
function for initializing the mod
this function only works once when all needed variables are loaded
--]]-----------------------------------------------
function AutoRespond_InitializeSetup()
	-- check if previous initialized or variables are not loaded
	if not Initialized and VariablesLoaded then
		-- get realm and playername
		Player = UnitName("player");
		Realm = GetRealmName();
	
		-- initialize SavedVariables if not given
		if AutoRespondMainOptions[Realm] == nil then AutoRespondMainOptions[Realm] = {}; end
		if AutoRespondMainOptions[Realm][Player] == nil then
			AutoRespondMainOptions[Realm][Player] = { ActiveMod = 1, InFight = 1, Scaling = 1.0 };
		end
		
		if(AutoRespondOptions[Realm] == nil) then AutoRespondOptions[Realm] = {}; end
		if(AutoRespondOptions[Realm][Player] == nil) then 
			AutoRespondOptions[Realm][Player] = {};
			table.insert( AutoRespondOptions[Realm][Player],{ Active = nil, Script = nil, Keywords = {AUTO_RESPOND_DEFAULT_KEYWORD_TEXT}, Response = {AUTO_RESPOND_DEFAULT_RESPONSE_TEXT}, Options = { Receive = { Guild = nil, Party = nil, Raid = nil, Friends = nil, Names = {} }, Tell = { Guild = nil, Party = nil, Raid = nil } } } );
		end
	
		-- secure function for hooking 
		hooksecurefunc("SetItemRef",AutoRespond_SetItemRef)
		
		AutoRespondFrame:SetScale(AutoRespondMainOptions[Realm][Player]["Scaling"]);
		
		DEFAULT_CHAT_FRAME:AddMessage(string.format(AUTO_RESPOND_LOADED_TEXT,AR_Version));
		
		Initialized = 1;
	end
	
	if VariablesLoaded and AutoRespondMainOptions[Realm][Player]["ActiveMod"] then
		this:RegisterEvent("CHAT_MSG_WHISPER");
	end
end


--[[-----------------------------------------------
function for handling the events
Parameter: 
	event - identifier for the event that occurs
--]]-----------------------------------------------
function AutoRespond_OnEvent(event)
	if event == "CHAT_MSG_WHISPER" then
		if AutoRespondMainOptions[Realm][Player]["InFight"] and UnitAffectingCombat("player") then
			-- send message that the player is busy at the moment
			SendChatMessage(AUTO_RESPOND_DEFAULT_INFIGHT_MESSAGE, "WHISPER", GetDefaultLanguage("player"), arg2);
		else
			-- whisper received, check if you need to respond and by what
			local what = arg1;
			local who = arg2;
			local respond_id = AutoRespond_CheckMessage(what,1);
			
			-- respond by all hits you find
			while respond_id do 
				AutoRespond_SendRespond(who,respond_id);
				respond_id = AutoRespond_CheckMessage(what,respond_id+1);
			end
		end
	elseif(event == "PLAYER_ENTERING_WORLD") then
		-- player has entered world -> check for initialize
		AutoRespond_InitializeSetup();
	elseif(event == "PLAYER_LEAVING_WORLD") then
		-- player leaving world -> unregister event for whisper
		this:UnregisterEvent("CHAT_MSG_WHISPER");
	elseif(event == "VARIABLES_LOADED") then
		-- variables loaded -> set flag and unregister event (can't get same event a second time)
		VariablesLoaded = 1;
		this:UnregisterEvent(event);
	end
end

--[[--------------------------------------------------------------------------------------------
system functions for the mod
--]]--------------------------------------------------------------------------------------------


--[[-----------------------------------------------
hook function for getting links from chat links 
Parameter:
	link - the link of the item as itemid
	text - the link as text
	button - identifier of the button that was pressed 
--]]-----------------------------------------------
function AutoRespond_SetItemRef(link,text,button)
	-- check if you should include the link in responsetext
	if ( IsShiftKeyDown() ) and ( AutoRespondFrame:IsVisible() ) then
		AutoRespondFrame_ResponseFrame_ScrollFrameResponse_ListResponse:Insert(text);
	end
end


--[[-----------------------------------------------
slashhandler of the addon
Parameter:
	msg - the message that was given with the slashcommand
--]]-----------------------------------------------
function AutoRespond_SlashHandler(msg)
	if string.find(msg,"options") then
		AutoRespondOptionsFrame:Show();
	else
		-- none of these above then just show the mainframe of the mod
		AutoRespondFrame:Show();
	end
end


--[[--------------------------------------------------------------------------------------------
functions for the responses
--]]--------------------------------------------------------------------------------------------


--[[-----------------------------------------------
function for checking the whisper to get a response to
Parameter:
	what - the message that was given in the whisper
	index - the index of the response to start from searching
Return
	returns the index of a response that have a matching keyword to the whispered text
	the returned index could be the value of the passed index or higher
	if no match can be found the return value will be nil
--]]-----------------------------------------------
function AutoRespond_CheckMessage(what,index)
	local t = AutoRespondOptions[Realm][Player];
	-- start at given respondindex until last respond
	for i=index,getn(t) do
		-- respond is active?
		if t[i]["Active"] then
			-- check if keyword(s) is found in whisper
	    for k,v in ipairs(t[i]["Keywords"]) do
				if string.find(string.lower(what), string.lower(v), 1, true) then
					-- return immediately with index of matched respond 
					return i;
				end
			end
		end
	end
	return nil;
end


--[[-----------------------------------------------
function for checking the whisper options
these options verify if the originator of the whisper is allowed to get the response
Parameter:
	who - the originator of the whisper
	index - the index of the response to start from
Return:
	nil - the originator should not get this response
	1 - response can be send
--]]-----------------------------------------------
function AutoRespond_CheckCan(who,index)
	local skip,restrict = nil,nil;
	local t = AutoRespondOptions[Realm][Player][index]["Options"]["Receive"];

	-- check for given names
	if t["Names"] then
	    for i,v in ipairs(t["Names"]) do
			if string.lower(v) == string.lower(who) then
			    skip = 1;
			end
		end
		restrict = 1;
	end

	-- check for group restriction
	if t["Party"] and not skip then
		for i=1,GetNumPartyMembers() do
			if UnitName("party"..i) == who then
				skip = 1;
			end
		end
		restrict = 1;
	end

	-- check for raid restriction
	if t["Raid"] and not skip then
		for i=1,GetNumRaidMembers() do
			if UnitName("raid"..i) == who then
				skip = 1;
			end
		end
		restrict = 1;
	end

	-- check for friends restriction
	if t["Friends"] and not skip then
		for i=1,GetNumFriends() do
			if GetFriendInfo(i) == who then
				skip = 1;
			end
		end
		restrict = 1;
	end

	-- check for guild restriction
	if t["Guild"] and not skip then
		for i=1, GetNumGuildMembers(true) do
			if GetGuildRosterInfo(i) == who then
				skip = 1;
			end
		end
		restrict = 1;
	end

	if not restrict then
	    return 1;
	else 
		return skip;
	end
end


--[[-----------------------------------------------
function for getting the response of a respond
Parameter: 
	index - the index of the respond the get the response from
Return:
	returns the response or nil if no response is available
--]]-----------------------------------------------
function AutoRespond_GetResponse(index)
	local t = nil;
	if(AutoRespondOptions[Realm][Player][index]["Response"]) then
		t = AutoRespondOptions[Realm][Player][index]["Response"];
	end
	return t;
end


--[[-----------------------------------------------
function for responding
Parameter: 
	who - the name of the originator to respond to
	index - the index of the respond
--]]-----------------------------------------------
function AutoRespond_SendRespond(who,index)
	-- check restrictions for originator
	if AutoRespond_CheckCan(who,index) then
		local t = AutoRespond_GetResponse(index);
		if t then
			-- if response is a script then use RunScript() else response by SendChatMessage()
			if AutoRespondOptions[Realm][Player][index]["Script"] then
		    for i=1,getn(t) do
		   	   RunScript(string.gsub(t[i],"$t","'"..who.."'"));
		    end
			else
				local channel,receiver = "WHISPER",who;
				if AutoRespondOptions[Realm][Player][index]["Options"]["Tell"]["Guild"] then
					channel = "GUILD";
					receiver = nil;
				elseif AutoRespondOptions[Realm][Player][index]["Options"]["Tell"]["Party"] then
					channel = "PARTY";
					receiver = nil;
				elseif AutoRespondOptions[Realm][Player][index]["Options"]["Tell"]["Raid"] then
					channel = "RAID";
					receiver = nil;
				end
				for i=1,getn(t) do
					if receiver == UnitName("player") then
						DEFAULT_CHAT_FRAME:AddMessage("AutoRespond: "..string.gsub(t[i],"$t",who));
					else
						SendChatMessage(string.gsub(t[i],"$t",who), channel, GetDefaultLanguage("player"), receiver);
					end
				end
			end
		end
	end
end


--[[-----------------------------------------------
function to save the keyword(s) for the response
--]]-----------------------------------------------
function AutoRespond_SaveKeywords()
	local text = this:GetText();
	if ActiveOption > 0 then
		if AutoRespondOptions[Realm][Player][ActiveOption] then
			-- delete old keywords
			if AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"] then
				while getn(AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"]) > 0 do
					table.remove(AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"]);
				end
			end
			AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"] = {};
			
			-- check if text is given
			if text and (text ~= "") then
				for keyword in string.gmatch(text, "[^,]+") do
					AutoRespond_SaveToTable(strtrim(keyword), AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"])
				end
			end
		end
	end
end


--[[-----------------------------------------------
function to update the visible keywords
--]]-----------------------------------------------
function AutoRespond_UpdateKeywords()
	local text = "";
	if ActiveOption > 0 then
		if AutoRespondOptions[Realm][Player][ActiveOption] and AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"] then
			local max = getn(AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"]);
			for i,v in ipairs(AutoRespondOptions[Realm][Player][ActiveOption]["Keywords"]) do
				text = text..v;
				if i < max then
					text = text..", ";
				end
			end
		end
	end
	this:SetText(text);
end


--[[-----------------------------------------------
function setting the usability of the ButtonListKeywords
--]]-----------------------------------------------
function AutoRespond_UpdateButtonListKeywords()
	if ActiveOption == 0 then
		this:Disable();
	else
		this:Enable();
	end
end


--[[-----------------------------------------------
function for saving the response text
--]]-----------------------------------------------
function AutoRespond_SaveResponse()
	local text = this:GetText();
	if ActiveOption > 0 then
		if AutoRespondOptions[Realm][Player][ActiveOption] then
			-- delete old response
			if AutoRespondOptions[Realm][Player][ActiveOption]["Response"] then
				while getn(AutoRespondOptions[Realm][Player][ActiveOption]["Response"]) > 0 do
					table.remove(AutoRespondOptions[Realm][Player][ActiveOption]["Response"]);
				end
			end
			AutoRespondOptions[Realm][Player][ActiveOption]["Response"] = {};
			
			if text and text~="" then
				for line in string.gmatch(text, "[^\r\n]+") do
					AutoRespond_SaveToTable(line,AutoRespondOptions[Realm][Player][ActiveOption]["Response"]);
				end
			end
		end
	end
end


--[[-----------------------------------------------
function for saving text in a table
Parameter:
	text - the text to save
	var - the table to save to
--]]-----------------------------------------------
function AutoRespond_SaveToTable(text,var)
	if text and (text ~= "") then
		table.insert(var,text);
	end
end


--[[-----------------------------------------------
function to update the visible response
--]]-----------------------------------------------
function AutoRespond_UpdateResponse()
	local text = "";
	if ActiveOption > 0 then
		if AutoRespondOptions[Realm][Player][ActiveOption] and AutoRespondOptions[Realm][Player][ActiveOption]["Response"] then
			local max = getn(AutoRespondOptions[Realm][Player][ActiveOption]["Response"]);
			for i,v in ipairs(AutoRespondOptions[Realm][Player][ActiveOption]["Response"]) do
				 text = text..v;
				 if i < max then
			     	 text = text.."\n";
				 end
			end
		end
	end
	this:SetText(text);
end

function AutoRespond_UpdateButtonListResponse()
	if ActiveOption == 0 then
		this:Disable();
	else
		this:Enable();
	end
end


--[[-----------------------------------------------
functions for the link button
--]]-----------------------------------------------
function AutoRespond_ButtonAddLinkOnShow()
	if ActiveOption == 0 then
		this:Disable();
	else
		this:Enable();
	end
end

function AutoRespond_ButtonAddLinkOnClick()
	if CursorHasItem() then
		for i=0,4 do
			if GetBagName(i) then
				for j=1, GetContainerNumSlots(i) do
					local _,_,locked = GetContainerItemInfo(i,j);
					if locked and GetContainerItemLink(i,j) then
						getglobal(this:GetParent():GetName().."_ScrollFrameResponse_ListResponse"):Insert(GetContainerItemLink(i,j));
						SetCursor(nil);
						return;
					end
				end
			end
		end
		SetCursor(nil);
	end
	local temp = GetCraftSkillLine(1);
	if temp then
		local index = GetCraftSelectionIndex();
		if (index) and (index < GetNumCrafts()) then
			local link = GetCraftItemLink(index);
			if link then
				getglobal(this:GetParent():GetName().."_ScrollFrameResponse_ListResponse"):Insert(link);
  		else
  			DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_NO_LINK_ITEM);
  		end
		end
	else
		local index = GetTradeSkillSelectionIndex();
		if index then
	    local link = GetTradeSkillItemLink(index);
			if link then 
		    getglobal(this:GetParent():GetName().."_ScrollFrameResponse_ListResponse"):Insert(link);
			else
				DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_NO_LINK_ITEM);
			end
		else
			DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_NO_SELECTED_TRADESKILL);
		end
	end
end


--[[-----------------------------------------------
functions for the reagent button
--]]-----------------------------------------------
function AutoRespond_ButtonAddReagentOnShow()
	if ActiveOption == 0 then
		this:Disable();
	else
		this:Enable();
	end
end

function AutoRespond_ButtonAddReagentOnClick()
	local text = "";
	if GetCraftSkillLine(1) then
		local index = GetCraftSelectionIndex();
		if (index) and (index < GetNumCrafts()) then
			for i=1,GetCraftNumReagents(index) do
				local _,_,num = GetCraftReagentInfo(index,i);
				text = text..num.."x"..GetCraftReagentItemLink(index,i)..";";
			end
		end
	else
		local index = GetTradeSkillSelectionIndex();
    	if (index) and (index < GetNumTradeSkills()) then
		    for i=1,GetTradeSkillNumReagents(index) do
		   		local _,_,num = GetTradeSkillReagentInfo(index, i);
				text = text..num.."x"..GetTradeSkillReagentItemLink(index, i)..";";
			end
		end
	end
	if text ~= "" then
		getglobal(this:GetParent():GetName().."_ScrollFrameResponse_ListResponse"):Insert(text);
	end
end


--[[--------------------------------------------------------------------------------------------
functions for the options of the response
--]]--------------------------------------------------------------------------------------------


--[[-----------------------------------------------
functions for the active-option of the response
--]]-----------------------------------------------
function AutoRespond_UpdateActive()
	if ActiveOption == 0 then
		this:Disable();
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Active"]);
	end
end

function AutoRespond_ToggleActive()
	AutoRespondOptions[Realm][Player][ActiveOption]["Active"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for the script-option of the response
--]]-----------------------------------------------
function AutoRespond_UpdateScript()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Script"]);
	end
end

function AutoRespond_ToggleScript()
	AutoRespondOptions[Realm][Player][ActiveOption]["Script"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for the CanGuild-option of the response
--]]-----------------------------------------------
function AutoRespond_InitCanGuild()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Guild"]);
	end
end

function AutoRespond_ToggleCanGuild()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Guild"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for the CanParty-option of the response
--]]-----------------------------------------------
function AutoRespond_InitCanParty()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Party"]);
	end
end

function AutoRespond_ToggleCanParty()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Party"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for the CanRaid-option of the response
--]]-----------------------------------------------
function AutoRespond_InitCanRaid()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Raid"]);
	end
end

function AutoRespond_ToggleCanRaid()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Raid"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for the CanFriends-option of the response
--]]-----------------------------------------------
function AutoRespond_InitCanFriends()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Friends"]);
	end
end

function AutoRespond_ToggleCanFriends()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Friends"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for the CanNames-option of the response
--]]-----------------------------------------------
function AutoRespond_InitCanNames()
	local text = "";
	if ActiveOption > 0 then
		if AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Names"] then
			local max = getn(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Names"]);
			for i,v in ipairs(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Names"]) do
				text = text..v;
				if i < max then
					text = text..", ";
				end
			end
		end
	end
	this:SetText(text);
end

function AutoRespond_SaveCanNames()
	if AutoRespondOptions[Realm][Player][ActiveOption] and AutoRespondOptions[Realm][Player][ActiveOption]["Options"] and AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"] then
		if this:GetNumLetters() > 0 then
			AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Names"] = {};
			local function towords(word) if word then table.insert(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Names"],word); end end
			if not string.find(string.gsub(this:GetText(), "%w+", towords), "%S") then end;
		else
			AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Receive"]["Names"] = nil;
		end
	end
end

function AutoRespond_UpdateButtonListCanNames()
	if ActiveOption == 0 then
		this:Disable();
	else
		this:Enable();
	end
end


--[[-----------------------------------------------
functions for TellGuild-option of the reponse
--]]-----------------------------------------------
function AutoRespond_InitTellGuild()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Tell"]["Guild"]);
	end
end

function AutoRespond_ToggleTellGuild()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Tell"]["Guild"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for TellParty-option of the reponse
--]]-----------------------------------------------
function AutoRespond_InitTellParty()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Tell"]["Party"]);
	end
end

function AutoRespond_ToggleTellParty()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Tell"]["Party"] = this:GetChecked();
end


--[[-----------------------------------------------
functions for TellRaid-option of the reponse
--]]-----------------------------------------------
function AutoRespond_InitTellRaid()
	if ActiveOption == 0 then
		this:Disable();
		this:SetChecked(nil);
	else
		this:Enable();
		this:SetChecked(AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Tell"]["Raid"]);
	end
end

function AutoRespond_ToggleTellRaid()
	AutoRespondOptions[Realm][Player][ActiveOption]["Options"]["Tell"]["Raid"] = this:GetChecked();
end


--[[--------------------------------------------------------------------------------------------
functions for the whole Responds
--]]--------------------------------------------------------------------------------------------

--[[-----------------------------------------------
function to create a new respond
--]]-----------------------------------------------
function AutoRespond_ButtonNew()
	AutoRespondFrame:Hide();
	table.insert( AutoRespondOptions[Realm][Player], { Active = nil, Script = nil, Keywords = {AUTO_RESPOND_DEFAULT_KEYWORD_TEXT}, Response = {AUTO_RESPOND_DEFAULT_RESPONSE_TEXT}, Options = { Receive = { Guild = nil, Party = nil, Raid = nil, Friends = nil, Names = {} }, Tell = { Guild = nil, Party = nil, Raid = nil } } } );
	DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_ADD_NEW_TEXT);
	ActiveOption = getn(AutoRespondOptions[Realm][Player]);
	AutoRespondFrame:Show();
end


--[[-----------------------------------------------
function to check status for delete-button
--]]-----------------------------------------------
function AutoRespond_ButtonOnShow()
	if ActiveOption == 0 and getn(AutoRespondOptions[Realm][Player]) == 0 then
		this:Disable();
	else
		this:Enable();
	end
end


--[[-----------------------------------------------
function to delete a respond
--]]-----------------------------------------------
function AutoRespond_ButtonDelete()
	local index = getn(AutoRespondOptions[Realm][Player]);
	if index >= ActiveOption and index > 0 then
		AutoRespondFrame:Hide();
		table.remove(AutoRespondOptions[Realm][Player],ActiveOption);
		DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_DELETED_TEXT);
		if(ActiveOption == index) then
			ActiveOption = ActiveOption - 1;
		end
		AutoRespondFrame:Show();
	else
		DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_EMPTY_LIST_TEXT);
	end
end


--[[-----------------------------------------------
function to check status for previous-button
--]]-----------------------------------------------
function AutoRespond_ButtonPreviousOnShow()
	if ActiveOption <= 1 then
		this:Disable();
	else
		this:Enable();
	end
end


--[[-----------------------------------------------
function to go to previous response
--]]-----------------------------------------------
function AutoRespond_ButtonPreviousOnClick()
	AutoRespondFrame:Hide();
	ActiveOption = ActiveOption - 1;
	AutoRespondFrame:Show();
end


--[[-----------------------------------------------
function to check status for next-button
--]]-----------------------------------------------
function AutoRespond_ButtonNextOnShow()
	if ActiveOption == (getn(AutoRespondOptions[Realm][Player])) then
		this:Disable();
	else
		this:Enable();
	end
end


--[[-----------------------------------------------
function to go to next response
--]]-----------------------------------------------
function AutoRespond_ButtonNextOnClick()
	AutoRespondFrame:Hide();
	ActiveOption = ActiveOption + 1;
	AutoRespondFrame:Show();
end


--[[--------------------------------------------------------------------------------------------
functions for the main-options
--]]--------------------------------------------------------------------------------------------


--[[-----------------------------------------------
function to show the actual status of the ActiveMod option
--]]-----------------------------------------------
function AutoRespondOptions_InitActiveMod()
	this:SetChecked(AutoRespondMainOptions[Realm][Player]["ActiveMod"]);
end


--[[-----------------------------------------------
function to save the status of the InFight option
--]]-----------------------------------------------
function AutoRespondOptions_ToggleActiveMod()
	AutoRespondMainOptions[Realm][Player]["ActiveMod"] = this:GetChecked();
end


--[[-----------------------------------------------
function to show the status of the actual InFight option
--]]-----------------------------------------------
function AutoRespondOptions_InitInFight()
	this:SetChecked(AutoRespondMainOptions[Realm][Player]["InFight"]);
end


--[[-----------------------------------------------
function to save the status of the InFight option
--]]-----------------------------------------------
function AutoRespondOptions_ToggleInFight()
	local infight = this:GetChecked();
	if infight then
		AutoRespondFrame:RegisterEvent("CHAT_MSG_WHISPER");
	else
		AutoRespondFrame:UnregisterEvent("CHAT_MSG_WHISPER");
	end
	AutoRespondMainOptions[Realm][Player]["InFight"] = infight;
end


--[[-----------------------------------------------
function to show the actual scaling and texts for the scale-widget
--]]-----------------------------------------------
function AutoRespondOptions_Scaling_OnShow()
	local scaling = AutoRespondMainOptions[Realm][Player]["Scaling"];
	getglobal(this:GetName().."High"):SetText("150%");
	getglobal(this:GetName().."Low"):SetText("50%");
	getglobal(this:GetName() .. "Text"):SetText("Scaling - " .. (scaling*100));
	
	this:SetMinMaxValues(0.5, 1.5);
	this:SetValueStep(0.01);
	this:SetValue(scaling);
end


--[[-----------------------------------------------
function to save the scaling when changed
--]]-----------------------------------------------
function AutoRespondOptions_Scaling_OnValueChanged()
	scaling = floor(this:GetValue()*100+0.5)/100;
	getglobal(this:GetName() .. "Text"):SetText("Scaling - " .. (scaling*100) .. "%");
	AutoRespondMainOptions[Realm][Player]["Scaling"] = scaling;
	AutoRespondOptions_ScaleFrame(scaling);
end


--[[-----------------------------------------------
function to set the scale of the mainframe
--]]-----------------------------------------------
function AutoRespondOptions_ScaleFrame(scaling)
	AutoRespondFrame:SetScale(scaling);
end


--[[--------------------------------------------------------------------------------------------
special functions for macros or scripts
--]]--------------------------------------------------------------------------------------------

--[[-----------------------------------------------
function to promote a response to a channel
Parameter:
	index - the index of the response to promote
	channel - the identifier of the channel to promote to
	number - only with channel "CHANNEL" where number is the numeric id of the channel to promote to
--]]-----------------------------------------------
function AutoRespond_PromoteResponse(index,channel,number)
	if channel and index and (index <= getn(AutoRespondOptions[Realm][Player])) then
		for i,v in AutoRespondOptions[Realm][Player][index]["Response"] do
	    if channel == "CHANNEL" then
	    	if number then
					SendChatMessage(v,channel,GetDefaultLanguage("player"),number);
				else
					DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_PROMOTE_CHANNEL_ERROR);
				end
			else
				SendChatMessage(v,channel,GetDefaultLanguage("player"));
			end
		end
	end
end


--[[-----------------------------------------------
function to promote all keywords of response(s) to a channel
Parameter:
	index - the index of the response, if nil all active responses will be used
	channel - the identifier of the channel to promote to
	number - only with channel "CHANNEL" where number is the numeric id of the channel to promote to
--]]-----------------------------------------------
function AutoRespond_PromoteKeywords(index,channel, number)
	local s,e = 1,getn(AutoRespondOptions[Realm][Player]);
	if index then
		s = index;
		e = index;
	end
	for i=s,e do
		if AutoRespondOptions[Realm][Player][i] and AutoRespondOptions[Realm][Player][i]["Active"] then
		   	if AutoRespondOptions[Realm][Player][i]["Keywords"] then
				local text,max = "", getn(AutoRespondOptions[Realm][Player][i]["Keywords"]);
				for j,v in ipairs(AutoRespondOptions[Realm][Player][i]["Keywords"]) do
					text = text..v;
					if j < max then
						text = text..", ";
					end
				end
				if channel == "CHANNEL" then
					if number then
						SendChatMessage(text,channel,GetDefaultLanguage("player"),number);
					else
						DEFAULT_CHAT_FRAME:AddMessage(AUTO_RESPOND_PROMOTE_CHANNEL_ERROR);
					end
				else
					SendChatMessage(text,channel,GetDefaultLanguage("player"));
				end
			end
		end
	end
end