/* ГАДЖЕТ ПОИСКА В ИНТЕРНЕТЕ */
function __Search(id)
{
	this.lang = Locale.Gadgets.Search;
	this.Core = new __StdModuleCore(this, id, 'zoom', this.lang.title, this.lang.desc);

	this.oForm = false;
	this.mailAccounts = {};

	this.messagesOnPage = 20;
	this.updatePeriod = null;
	this.searchEngines = {'yandex': 'Yandex', 'yahoo': 'Yahoo', 'msn': 'MSN', 'google': 'Google'};

	this.finput = {};
	this.fpanel = {};

	this.currentQuery = {text: '', id: null, numEngines: 0, numEnginesReady: 0}

	this.tabs = {};
	this.hosts = {};
	this.hosts_s = [];
	this.searchResults = {};

	this.createSearchForm();
	this.createHistoryPanel();
	Update.request('Search', 'module', 'startup', {id: this.id}, true);	//запрос истории
}

__Search.prototype.Relay = function(data, part)
{
	switch(data.event.action)
	{
		case 'startup':
			if(!isEmpty(data.variables.settings.history))
			{
				var t = data.variables.settings.history;
				for(var i=0; i<t.length; i++)
				{
					if(t[i])
						this.addHistoryHref(t[i].query, {num: t[i].num, engines: t[i].engines});
				}
			}
			break;

		case 'goSearch':
			if(data.event.item.uID == this.currentQuery.id)
			{
				this.processSearchResults(data);
			}
			break;

		default:
			return false;
			break;
	}
}

__Search.prototype.onDelete = function()
{
	if(this.workspaceId && Desktop.State.cMain.content[this.workspaceId])
		Desktop.DeleteTabByID('cMain', this.workspaceId);
}

__Search.prototype.initTab = function()
{
	if(!this.workspaceId || !Desktop.State.cMain.content[this.workspaceId])
	{
		this.workspaceId = Desktop.NewTab('cMain', this.lang.title, 'zoom', null, null, null, true);
		var t = Desktop.State.cMain.content[this.workspaceId].content;
		t.style.overflow = 'auto';
		this.workspace = ce('LI', t);
		this.workspaceTabs = new __Tabs(this.workspace);
	}
	else
	{
		this.workspaceTabs.removeAll();
	}
	Desktop.SetActiveByID('cMain', this.workspaceId);
}

//-------------------------------------------------------------------------------
//Рисует форму для создания нового аккаунта
__Search.prototype.createSearchForm = function(section)
{
	var self = this;

	this.fpanel.formSearch = ce('FORM', null);
	var oDiv = ce('DIV', this.fpanel.formSearch, null, {marginBottom: '10px'});
	for(var i in this.searchEngines)
	{
		var t = ce('NOBR', oDiv, null, {padding: '10px 3px 10px 0px'});
		ce('INPUT', t, {id: this.id +'_engine_'+ i, type: 'checkbox'});
		ce('IMG', t, {src: '/img/search/'+ i +'.gif', align: 'absMiddle', title: this.searchEngines[i]}, {margin: '0px 5px 0px 3px'});
	}
	this.finput.enginesAll = ce('INPUT', oDiv, {type: 'button', className: 'std_button', value: this.lang['ByAll']}, {marginLeft: '6px'});
	this.finput.enginesAll.onclick = function()	{
		for(var i in self.searchEngines)
		{
			document.getElementById(self.id +'_engine_'+ i).checked = true;
		}
	}
	var oTr = ce('TR', ce('TBODY', ce('TABLE', this.fpanel.formSearch)));
	ce('TD', oTr, {innerHTML: this.lang['NumResults'] +':'}, {verticalAlign: 'middle', paddingRight: '8px'});
	this.finput.num = ce('SELECT', ce('TD', oTr, null, {verticalAlign: 'top', height: '20px'}));
		ce('OPTION', this.finput.num, {value: '20', innerHTML: '20', defaultSelected: true});
		ce('OPTION', this.finput.num, {value: '50', innerHTML: '50'});
		ce('OPTION', this.finput.num, {value: '100', innerHTML: '100'});
	
	this.finput.query = ce('INPUT', this.fpanel.formSearch, {type: 'text'}, {width: '90%', marginTop: '5px'});
	ce('INPUT', this.fpanel.formSearch, {type: 'submit', className: 'std_button', value: Locale['Search']});
	this.Content.appendChild(this.fpanel.formSearch);

	this.fpanel.formSearch.onsubmit = function()
	{
		self.currentQuery.text = self.finput.query.value;
		var options = {num: self.finput.num.value, query: self.currentQuery.text, engines: []};
		for(var i in self.searchEngines)
		{
			if(document.getElementById(self.id +'_engine_'+ i).checked)
				options.engines.push(i);
		}
		self.currentQuery.numEngines = options.engines.length;
		if(self.currentQuery.numEngines == 0)
			return false;
		self.prepareNewProcessing();
		self.currentQuery.id = Update.request('Search', 'module', 'goSearch', {id: self.id}, options, true);
		return false;
	}
}

__Search.prototype.prepareNewProcessing = function()
{
	this.initTab();
	this.currentQuery.numEnginesReady = 0;
	this.hosts = {};
	this.hosts_s = [];
}

//Обрабатывает очередную порцию результатов поиска
__Search.prototype.processSearchResults = function(d, fromCache)
{
//	this.parent.oLevelATitle.innerHTML = '<a href="'+ dataObj.data.ResultSet.link +'" target="_blank"><strong>'+ dataObj.data.ResultSet.title +'</strong></a>';
	var self = this;
	var data = d.variables;
	var i = null;
	var k = null;
	var descId = null;
	var n = 50;
	var rank = 0;
	var t = null;	//временная хранилка объектов
	var tmp = 0;	//временная переменная
	var query = '';
	if(!isEmpty(data))
	{
		for(sSystem in data)	//данные группированы по поисковым системам
		{
			if(this.currentQuery.numEnginesReady == 0)
				this.searchResults = {};
			this.searchResults[sSystem] = data[sSystem];	//сохраняем данные от сервереа
			this.currentQuery.numEnginesReady++;	//кол-во принятых поисковиков по текущему запросу
			this.tabs[sSystem] = this.workspaceTabs.create(
				this.id +'_'+ sSystem,
				'<img src="/img/search/'+ sSystem +'.gif" width="16" height="16" align="absmiddle" style="margin: 0px 5px;" alt="'+ this.searchEngines[sSystem] +'" title="'+ this.searchEngines[sSystem] +'"/>'+this.searchEngines[sSystem]
			);	//собираем вкладки по отдельным поисковикам
			this.tabs[sSystem].style.backgroundColor = '#F0F0F0';
			ce('DIV', this.tabs[sSystem], {innerHTML: this.lang.msg['Results'] +' <strong>'+ Locale['Chars']['html']['lq'] + this.currentQuery.text + Locale['Chars']['html']['rq'] +'</strong>:'});
			var oUl = ce('UL', this.tabs[sSystem], null, {marginTop: '12px', borderTop: '1px solid #888888'});
			for(i=0; i<data[sSystem].results.length; i++)
			{
				var oLi = ce('LI', oUl, null, {padding: '8px 0px', borderBottom: '1px solid #888888'});	//отдельные вкладки
				ce('A', oLi, {href: data[sSystem].results[i].url, onclick: go, innerHTML: '<strong>'+ data[sSystem].results[i].title +'</strong>'});
				ce('DIV', oLi, {innerHTML: '<small>'+ data[sSystem].results[i].desc +'</small>'});
				ce('A', ce('SMALL', oLi), {href: data[sSystem].results[i].url, onclick: go, innerHTML: this.cutUrl(data[sSystem].results[i].url)});
				rank = n-i;	//далее готовим данные для метапоиска
				if(!this.hosts[data[sSystem].results[i].host])	//такого хоста ещё нет
				{
					this.hosts[data[sSystem].results[i].host] = {};
					this.hosts[data[sSystem].results[i].host].rank = rank;
					this.hosts[data[sSystem].results[i].host].inSystems = {};
					this.hosts[data[sSystem].results[i].host].inSystems[sSystem] = true;
					this.hosts[data[sSystem].results[i].host].urls = {};
					this.hosts[data[sSystem].results[i].host].num = 0;
					this.hosts[data[sSystem].results[i].host].sindex = null;
				}
				else	//добавляем хост
				{
					this.hosts[data[sSystem].results[i].host].rank += rank;	//увеличиваем рейтинг на текущее значение
					if(!this.hosts[data[sSystem].results[i].host].inSystems[sSystem])
					{
						this.hosts[data[sSystem].results[i].host].inSystems[sSystem] = true;
					}
				}
				if(t = this.hosts[data[sSystem].results[i].host].urls[data[sSystem].results[i].url])
				{
					t.rank += rank;
					if(rank > t.maxrank)	//если у нового экз-ра рейтинг больше, берём в расчёт его title и desc
					{
						t.maxrank = rank;
						t.title = data[sSystem].results[i].title;
						if(t.desc.length < data[sSystem].results[i].desc.length) t.desc = data[sSystem].results[i].desc;	//примитивненько проверяем ценность
					}
				}
				else
				{	//добавляем урл
					this.hosts[data[sSystem].results[i].host].urls[data[sSystem].results[i].url] = {
						title: data[sSystem].results[i].title,
						desc: data[sSystem].results[i].desc,
						rank: rank,
						maxrank: rank
					}
				}
				if(++this.hosts[data[sSystem].results[i].host].num == 1)	//2 действия в 1
					this.hosts[data[sSystem].results[i].host].sindex = this.hosts_s.push({host: data[sSystem].results[i].host, rank: this.hosts[data[sSystem].results[i].host].urls[data[sSystem].results[i].url].rank}) - 1;
				else	//синхронизируем рейтинги в сорт. массиве хостов
					this.hosts_s[this.hosts[data[sSystem].results[i].host].sindex].rank = this.hosts[data[sSystem].results[i].host].rank;
			}
			this.workspaceTabs.show(this.tabs[sSystem].id);
		}
	}

	if(!isEmpty(d.errors))
	{
		for(var i=0; i<d.errors.length; i++)
		{
			if(this.searchEngines[d.errors[i].type])
			{
//				window.alert('При получении данных от сервера "'+ this.searchEngines[d.errors[i].type] +'" произошла ошибка');
				this.currentQuery.numEngines--;
			}
		}
	}

	if(this.currentQuery.numEnginesReady == this.currentQuery.numEngines)
	{	//принят последний поисковик
		this.processSearchMeta();
		if(!fromCache)
			gCache.add('searchGadget', 'qData_'+ this.addHistoryHref(this.currentQuery.text), this.searchResults);
	}

	function go()
	{
		NavBar.go(this.href);
		return false;
	}
}

//Выводит мета-результаты поиска
__Search.prototype.processSearchMeta = function()
{
	var self = this;
	this.hosts_s.sort(
		function(a,b)
		{
			if(a.rank > b.rank) return -1;
			if(a.rank < b.rank) return 1;
			if(String(a.host) > String(b.host))	return 1; //a.num == b.num
			if(String(a.host) < String(b.host))	return -1;
			return 0;
		}
	);

	this.tabs.meta = this.workspaceTabs.create(this.id +'_'+ 'meta', 'Метапоиск', true);
	this.tabs.meta.style.backgroundColor = '#F0F0F0';
	this.workspaceTabs.show(this.tabs.meta.id);

	ce('DIV', this.tabs.meta, {innerHTML: this.lang.msg['Results'] +' <strong>'+ Locale['Chars']['html']['lq'] + this.currentQuery.text + Locale['Chars']['html']['rq'] +'</strong>:'});

	for(var i=0; i<this.hosts_s.length; i++)
	{
		var oUl = ce('UL', this.tabs.meta, null, {marginTop: '12px', borderTop: '1px solid #888888'});
		var oLi = ce('LI', oUl, null, {paddingTop: '8px'});
		ce('IMG', oLi, {src: '/img/icons/blt1.gif', align: 'absMiddle'}, {marginRight: '7px'});
		ce('A', oLi, {href: 'http://'+this.hosts_s[i].host+'/', onclick: go, innerHTML: '<strong>'+this.hosts_s[i].host+'</strong>'});
		ce('SPAN', oLi, {innerHTML: ' ('+ this.hosts[this.hosts_s[i].host].num +')'});
		for(var k in this.hosts[this.hosts_s[i].host].inSystems)
		{
			ce('IMG', oLi, {src: '/img/search/'+k+'.gif', alt: this.searchEngines[k], align: 'absMiddle'}, {marginLeft: '10px'});
		}
		for(k in this.hosts[this.hosts_s[i].host].urls)
		{
			oLi = ce('LI', oUl, null, {marginLeft: '20px', width: 'auto', border: 'none'});
			ce('A', oLi, {href: k, onclick: go, innerHTML: '<strong>'+ this.hosts[this.hosts_s[i].host].urls[k].title +'</strong>'});
			ce('DIV', oLi, {innerHTML: this.hosts[this.hosts_s[i].host].urls[k].desc});
			ce('A', oLi, {href: k, onclick: go, innerHTML: this.cutUrl(k)});
			ce('IMG', oLi, {src: '/img/dialog/open_newtab.gif', title: Locale['ToOpenInNewWindow'], className: 'href', url: k, onclick: openInNewWindow, align: 'absMiddle'}, {marginLeft: '10px'});
		}
	}

	function go()
	{
		NavBar.go(this.href);
		return false;
	}
}

//Оформляет URL
__Search.prototype.cutUrl = function(url)
{
	if(url.indexOf('http://') > -1)
		url = url.substr(7);
	if(url.length > 70)	//на скору руку
		url = url.substring(0, 69) +'<strong>...</strong>';
	return url;
}

//Добавляет ссылку на панель истории запросов и оснащает её необходимой функциональностью
__Search.prototype.addHistoryHref = function(query, options)
{
	var self = this;
	if(!options)
		cacheFlag = true;
	else
		cacheFlag = false;
	var k = this.historyLinks.length;
	if(k > 4 && this.historyLinks[0].cid)
	{
		gCache.remove('searchGadget', 'qData_'+this.historyLinks[0].cid);
		var t = this.historyLinks.shift().parentNode;
		t.parentNode.removeChild(t);
	}
	if(query.length > 30) var tmp = query.substr(0, 27) +'...';
	else var tmp = query;
	k = this.historyLinks.push(ce('A', ce('LI', this.fpanel.history), {href: '#', q: query, innerHTML: tmp}));
	k--;
	if(cacheFlag)
	{
		if(k>0)
			var j = this.historyLinks[k-1].cid + 1;
		else
			var j = 0;
		this.historyLinks[k].cid = j;
		this.historyLinks[k].onclick = getFromHistory;
		return this.historyLinks[k].cid;
	}
	else
	{
		this.historyLinks[k].style.color = '#A369CD';
		this.historyLinks[k].d = options;
		this.historyLinks[k].onclick = initQuery;
		return;
	}

	function getFromHistory()
	{
		self.prepareNewProcessing();
		var t = {variables: gCache.get('searchGadget', 'qData_'+ this.cid)};
		self.currentQuery.text = this.q;
		self.currentQuery.numEngines = sizeof(t.variables);
		self.processSearchResults(t, true);
	}

	function initQuery()
	{
		self.finput.query.value = this.q;
		var tmp = null;
		for(var i in self.searchEngines)
		{
			tmp = document.getElementById(self.id +'_engine_'+ i);
			if(tmp.checked)
				tmp.checked = false;
		}
		for(var i=0; i<this.d.engines.length; i++)
		{
			if(tmp = document.getElementById(self.id +'_engine_'+ this.d.engines[i]))
				tmp.checked = true;
		}
		for(i=0; i<self.finput.num.options.length; i++)
		{
			if(self.finput.num.options[i].value == this.d.num)
				self.finput.num.options[i].selected = true;
		}
		self.finput.query.nextSibling.focus();
//		self.fpanel.formSearch.submit();
	}
}

__Search.prototype.createHistoryPanel = function()
{
	this.Options.innerHTML = '<h4>'+ this.lang.msg['PrevQueries'] +':</h4>';
	this.fpanel.history = ce('UL', this.Options);
	this.historyLinks = [];
}