--[[    Simple search sample

luamacro(search.Search, Default)
luamacro(search.Search(Google), Google)
luamacro(search.Search(Yahoo), Yahoo)
luamacro(search.Search(Wikipedia), Wikipedia)
luamacro(search.Search(Dictionaries), Dictionaries)
luamacro(search.Search(KM), K-Meleon Forums)
luamacro(search.Search(URL), URL)
--
luamacro(search.SetSearch, Set Default Engine)
--
luamacro(search.SetOpen(0), Open results in current page);
luamacro(search.SetOpen(1), Open results in new page);
luamacro(search.SetOpen(2), Open results in background);

]]

require "hook"

search = {
	mes = {
		prompt_caption = "Search",
		prompt_prompt = "Search %s for:",
		select_prompt = "Select search engine",
		select_caption = "Change search engine",
		enter_url = "Enter URL:",
		go_url = "Go URL",
	},
	
	se = "kmeleon.plugins.luamacro.search.searchEngine",
	so = "kmeleon.plugins.luamacro.search.searchOpen",
	layers = "kmeleon.plugins.layers.load",
	
	encode = function (query)
		return string.gsub(query, "([^a-zA-Z0-9_%.%-])", function (s)
			if s == " " then
				return "+"
			else
				return string.format("%%%02X", string.byte(s))
			end
		end)
	end,
	
	utf8encode = function (query)
		return search.encode(EncodeUTF8(query))
	end,
}

search.engines = {
	URL = {
		name = nil,
		url = "%s",
		filter = nil,
	},
	Google = {
		name = "Google",
		url = "http://www.google.com/search?q=%s",
		filter = search.utf8encode,
	},
	Yahoo = {
		name = "Yahoo!",
		url = "http://search.yahoo.com/bin/search?p=%s",
		filter = search.encode,
	},
	Wikipedia = {
		name = "Wikipedia",
		url = "http://en.wikipedia.org/wiki/%s",
		filter = search.utf8encode,
	},
	Dictionaries = {
		name = "Dictionaries (One Look)",
		url = "http://www.onelook.com/?w=%s",
		filter = search.encode,
	},
	KM = {
		name = "K-Meleon Forums",
		url = "http://kmeleon.sourceforge.net/forum/search.php?f=3&globalsearch=1&match=1&date=0&fldsubject=1&fldbody=1&search=%s",
		filter = search.encode,
	},
}

search.layer = getpref(TYPE_BOOL, search.layers)
search.eng = getpref(TYPE_STRING, search.se)
if search.eng == "" then
	search.eng = "Google"
end


local function resetURL()
	local url
	
	url = GetGlobalVar(TYPE_STRING, "URL")
	if url and url ~= "" then
		setclipboard(url)
		id("ID_SELECT_URL")
		id("ID_EDIT_PASTE")
		id("ID_SELECT_URL")
	end
end

local function searchNew(url)
	resetURL()
--	if search.layer then
--		pluginmsg("layers", "OpenURL", url)
--	else
		NavigateTo(url, OPEN_NEWTAB)
--	end
end

local function searchBack(url)
	resetURL()
--	if search.layer then
--		pluginmsg("layers", "OpenURLBg", url)
--	else
		NavigateTo(url, OPEN_BACKGROUNDTAB)
--	end
end

local function openSearch(engine, word)
	local how, filter, url
	
	filter = search.engines[engine].filter
	if filter and type(filter) == "function" then
		word = filter(word)
	end
	url = string.format(search.engines[engine].url, word)
	how = getpref(TYPE_INT, search.so)
	if how == 0 then
		NavigateTo(url, OPEN_NORMAL)
	elseif how == 1 then
		searchNew(url)
	else
		searchBack(url)
	end
end

local function promptSearch(engine, clip)
	local word, tip = "", title
	
	if engine == "URL" then
		tip = search.mes.enter_url
		title = search.mes.go_url
	else
		tip = search.engines[engine].name
		if not tip or tip == "" then
			tip = engine
		end
		tip = string.format(search.mes.prompt_prompt, tip)
		title = search.mes.prompt_caption
	end
	setclipboard(clip)
	word = prompt(tip, title)
	if word and word ~= "" then
		openSearch(engine, word)
	end
end

local function urlBarSearch(engine,  clip)
	local word, url
	
	--id("ID_SELECT_URL")
	--id("ID_EDIT_COPY")
	--word = GetGlobalVar(TYPE_STRING, "URLBAR")
	word=GetWindowVar(Window_UrlBar)
	url = GetGlobalVar(TYPE_STRING, "URL")
	--word = getclipboard()
	if word == "" or word == url then
		promptSearch(engine, clip)
	else
	--alert(word)
		openSearch(engine, word)
	end
end

local function sync(set)
	if set then
		if search.eng then
			SetCheck("luamacro(search.Search(" .. search.eng .. ")", false)
		end
		search.eng = set
		setpref(TYPE_STRING, search.se, set)
		SetCheck("luamacro(search.Search(" .. set .. ")", true)
	end
end


function search.SetOpen(set)
	local c
	if set == "0" or set == "1" or set == "2" then
		c = getpref(TYPE_INT, search.so)
		if c == 0 or c == 1 or c == 2 then
			SetCheck("luamacro(search.SetOpen(" .. c .. ")", false)
		end
		setpref(TYPE_INT, search.so, set)
	end
	c = getpref(TYPE_INT, search.so)
	if c == 0 or c == 1 or c == 2 then
		SetCheck("luamacro(search.SetOpen(" .. c .. ")", true)
	end
end

function search.SetSearch(set)
	local names, tbl, i
	
	if not set or set == "" then
		tbl, names = {}, {}
		table.foreach(search.engines, function (item)
			if search.engines[item].name then
				table.insert(tbl, item)
				table.insert(names, search.engines[item].name)
			end
		end)
		i = choose(search.mes.select_prompt, search.mes.select_caption, unpack(names))
		if i then
			set = tbl[i]
		end
	end
	if not search.engines[set] then
		return
	end
	sync(set)
end

function search.Search(engine)
	local clip, word, title, url
	
	if engine == "" or not search.engines[engine] then
		engine = search.eng
	end
	if engine == "" then
		engine = "Google"
	end
	if not search.engines[engine].url then
		return
	end
	clip = getclipboard()
	setclipboard("")
	id("ID_EDIT_COPY")
	word = getclipboard()
	-- alert(#word)
	if #word == 0 then
		urlBarSearch(engine, clip)
	else
		title, url = GetDocInfo()
		if word == url then
			promptSearch(engine, clip)
		else
			openSearch(engine, word)
		end
	end
	setclipboard(clip)
end

if hook then
	hook.add(StartupHook, function ()
		sync(search.eng)
		search.SetOpen()
	end)
end

-- luamacro(search.Search(Baidu), Baidu)
search.engines.Baidu = {
	name = "Baidu",
	url = "http://www.baidu.com/s?ie=utf-8&wd=%s",
	filter = search.utf8encode,
}

-- luamacro(search.Search(MW), Merriam-Webster)
search.engines.MW = {
	name = "Merriam-Webster",
	url = "http://www.m-w.com/dictionary/%s",
	filter = search.utf8encode,
}

-- luamacro(search.Search(IMDB), IMDB)
search.engines.IMDB = {
	name = "IMDB",
	url = "http://www.imdb.com/find?q=%s",
	filter = search.utf8encode,
}

search.engines.dictcn = {
	name = "dict.cn",
	url = "http://www.dict.cn/search/?q=%s",
	filter = search.utf8encode,
}