var headSearchBox, missSearchBox;
var LIMIT_LINKS = 1, LIMIT_COUNTRY = 4, LIMIT_FAQ = 2;
$(function()
{
	var head = $('input#typeAheadText').get(0), miss = $('input#search404').get(0);
	if (head)
	{
		var div = $('div#searchbox');
		headSearchBox = new VhqSearchBox(head, div.find('div#searchresults').get(0));
		$(head.parentNode.parentNode).submit(function(){return false;});
		div.find('div.viewallresult').find('a').click(function(){headSearchBox.submit();});
	}
	if (miss)
	{
		var div = $('div.search404').find('form').find('div#searchbox');
		missSearchBox = new VhqSearchBox(miss, div.find('div#searchresults').get(0));
		$(miss.parentNode).submit(function(){return false;});
		$(miss).next().click(function(){
			if (missSearchBox.selected == -1 || missSearchBox.hidden)
				missSearchBox.submit();
		});
		div.find('div.viewallresult').find('a').click(function(){headSearchBox.submit();});
	}
	$(document).mouseup(vhqHidePopup);
	$(document).keyup(function(e){
		if (e.keyCode == 9)
			vhqHidePopup();
	});
});
$(document).unload(function()
{
	for (var i in vhqSearchFound.items)
		for (var j in vhqSearchFound.items[i].content)
			vhqSearchFound.items[i].content[j] = null;
	headSearchBox = null;
	missSearchBox = null;
});
function vhqHidePopup(e)
{
	if (e)
	{
		var head = $('div#searchbox *'), miss = $('div.search404 form div#searchbox *');
		head = $.makeArray(head);
		head.push(headSearchBox.input);
		if (missSearchBox)
		{
			miss = $.makeArray(miss);
			miss.push(missSearchBox.input);
		}
		if ($.inArray(e.target, head) == -1)
		{
			$(headSearchBox.resultBox.parentNode).addClass('no_display');
			headSearchBox.hidden = true;
		}
		if (missSearchBox && $.inArray(e.target, miss) == -1)
		{
			$(missSearchBox.resultBox.parentNode).addClass('no_display');
			missSearchBox.hidden = true;
		}
	}
	else
	{
		$(headSearchBox.resultBox.parentNode).addClass('no_display');
		headSearchBox.hidden = true;
		if (missSearchBox)
		{
			$(missSearchBox.resultBox.parentNode).addClass('no_display');
			missSearchBox.hidden = true;
		}
	}
}
function VhqSearchBox(input, resultBox)
{
	this.input = input;
	this.input.blur();
	this.resultBox = resultBox;
	this._searchValue = '';
	this.inputValue = '';
	this.visibleRows = new Array(LIMIT_LINKS + LIMIT_COUNTRY + LIMIT_FAQ);
	this.selected = -1;
	this.hidden = true;
	this.init();
}
VhqSearchBox.prototype = {
	input:null,
	resultBox:null,
	visibleRows:null,
	selected:null,
	hidden:null,
	init:function()
	{
		$(this.input).focus(this.focus);
		$(this.input).blur(this.blur);
		$(this.input).keyup(this.keyup);
	},
	_searchValue:null,
	inputValue:null,
	searchValue:function(val)
	{
		if (this._searchValue != val)
		{
			this._searchValue = val;
			if (!vhqSearchFound.items[val])
				return true;
		}
		return false;
	},
	focus:function()
	{
		if (this.value == vhqvars.defaultValueSearchField)
			this.value = '';
	},
	blur:function(e)
	{
		if (this.value == '')
			this.value = vhqvars.defaultValueSearchField;
	},
	keyup:function(e)
	{
		var obj;
		if (this.id == 'typeAheadText')
			obj = headSearchBox;
		else if (this.id == 'search404')
			obj = missSearchBox;
		else
			return;
		switch (e.keyCode)
		{
			case 13: case 38: case 40:
				if (e.keyCode == 40 || e.keyCode == 38)
				{
					if ($(obj.resultBox).html() != '' && $.trim(this.value) && obj.hidden)
					{
						$(obj.resultBox.parentNode).removeClass('no_display');
						obj.hidden = false;
					}
					else
						obj.lightItem(e.keyCode);
				}
				else
				{
					if (obj.selected == -1 || obj.hidden)
						obj.submit();
					else
						obj.goTo(obj.getUrl(), obj.getType());
				}
				break;
			default:
				var val = $.trim(this.value).replace(/\s+/g, ' ').replace(/[\[\]\\]/gi, '');
				if (obj.inputValue == val)
					return;
				obj.selected = -1;
				obj.inputValue = val;
				if (val == '')
					$(obj.resultBox).parent().addClass('no_display');
				else
				{
					if (obj.searchValue(val.substring(0, 1).toUpperCase()))
						obj.search();
					else
						obj.build();
				}
		}
	},
	lightItem:function(key)
	{
		var limit = LIMIT_LINKS + LIMIT_COUNTRY + LIMIT_FAQ, prev = this.selected;
		for (var i = limit - 1; i >= 0; i--)
			if (typeof(this.visibleRows[i]) != 'number')
				limit--;
			else
				break;
		switch (key)
		{
			case 38:
				this.selected--;
				if (this.selected <= -2)
					this.selected = limit-1;
				break;
			case 40:
				this.selected++;
				if (this.selected >= limit)
					this.selected = -1;
				break;
		}
		var children = $(this.resultBox).children();
		if (prev != -1)
			children.eq(prev).css('background', '#fff');
		if (this.selected != -1)
			children.eq(this.selected).css('background', '#d5ebba');
	},
	search:function()
	{
		var obj;
		if (this.input.id == 'typeAheadText')
			obj = headSearchBox;
		else if (this.input.id == 'search404')
			obj = missSearchBox;
		else
			return;
		var value = this._searchValue;
		$.ajax({
			type:'post',
			dataType: $.browser.msie?'text':'xml',
			data:'q=' + encodeURIComponent(value),
			url:'/type_ahead.php',
			success:function(xmlData)
			{
				var data;
				if (typeof(xmlData) == 'string')
				{
					data = new ActiveXObject('Microsoft.XMLDOM');
					data.async = false;
					data.loadXML(xmlData);
				}
				else
					data = xmlData;
				$('LinkResult', data).each(function(){vhqSearchFound.init('link', $(this), value);});
				$('CountryResult', data).each(function(){vhqSearchFound.init('cntr', $(this), value);});
				$('FaqResult', data).each(function(){vhqSearchFound.init('faq', $(this), value);});
				obj.build();
			}
		});
	},
	build:function()
	{
		vhqSearchFound.search(this);
		var html = '', obj = 'headSearchBox', val = this._searchValue;
		if (this.input.id == 'search404')
			obj = 'missSearchBox';
		for (var i = 0, num = this.visibleRows.length; i < num; i++)
			if (typeof(this.visibleRows[i]) == 'number')
				html += vhqSearchFound.items[val].content[this.visibleRows[i]].getHtml(obj);
		$(this.resultBox).html(html);
		if (html != '')
		{
			$(this.resultBox.parentNode).removeClass('no_display');
			this.hidden = false;
		}
		else
		{
			$(this.resultBox.parentNode).addClass('no_display');
			this.hidden = true;
		}
	},
	_submit:false,
	submit:function()
	{
		if (this._submit || this.inputValue == '')
			return;
		this._submit = true;
		var url = vhqvars.urlPath+'search.php?visa_search='+encodeURIComponent(this.inputValue);
		this.sendStatistic(url, 'search');
	},
	goTo:function(url, type)
	{
		this.sendStatistic(url, type);
	},
	getUrl:function()
	{
		return vhqSearchFound.items[this._searchValue].content[this.visibleRows[this.selected]].url;
	},
	getType:function()
	{
		return vhqSearchFound.items[this._searchValue].content[this.visibleRows[this.selected]].type;
	},
	sendStatistic:function(url, type)
	{
		$.ajax({
			type:'post',
			data:'q=' + encodeURIComponent(this.inputValue)+'&page='+encodeURIComponent(url)+'&type='+encodeURIComponent(type),
			url:'/typeahead_stat.php',
			success:function(page)
			{
				$(window).attr('location', page);
			}
		});
	}
}
var vhqSearchFound = {
	items:{},
	init:function(type, elem, index)
	{
		if (typeof(index) != 'undefined' && !this.items[index])
			this.items[index] = {
				content:new Array()
			};
		if (!elem)
			return;
		var item;
		switch (type)
		{
			case 'link':
				item = new VhqSearchLink(elem);
				break;
			case 'cntr':
				item = new VhqSearchCountry(elem);
				break;
			case 'faq':
				item = new VhqSearchFaq(elem);
				break;
		}
		if (item)
			this.items[index].content.push(item);
		item = null;
	},
	search:function(obj)
	{
		var val = obj.inputValue, index = obj._searchValue;
		if (!this.items[index])
			this.items[index] = {
				content:new Array()
			};
        var limit = LIMIT_LINKS + LIMIT_COUNTRY + LIMIT_FAQ, i = 0, j = 0;
		var found = new Array(), link = 0, cntr = 0, faq = 0;
		for (var z = 0, num = this.items[index].content.length; z < num; z++)
			if (this.items[index].content[z].search(val.toLowerCase()))
			{
				found.push(z);
				switch (this.items[index].content[z].type)
				{
					case 'link': link++; break;
					case 'country': cntr++; break;
					case 'faq': faq++; break;
				}
			}
		var limits = this.countRows(new Array(link, cntr, faq));
		link = limits[0];
		cntr = limits[1];
		faq = limits[2];
		while (i < limit && j < found.length)
		{
			switch (this.items[index].content[found[j]].type)
			{
				case 'link':
					if (link > 0)
					{
						link--;
						obj.visibleRows[i++] = found[j];
					}
					break;
				case 'country':
					if (cntr > 0)
					{
						cntr--;
						obj.visibleRows[i++] = found[j];
					}
					break;
				case 'faq':
					if (faq > 0)
					{
						faq--;
						obj.visibleRows[i++] = found[j];
					}
					break;
			}
			j++;
		}
		while (i < limit)
			obj.visibleRows[i++] = null;
	},
	countRows:function(limits)
	{
		var limit = LIMIT_LINKS + LIMIT_COUNTRY + LIMIT_FAQ;
		var summ = limit, link = limits[0], country = limits[1], faq = limits[2];
		if (link > LIMIT_LINKS)
			link = LIMIT_LINKS;
		summ -= link;
		if (country > LIMIT_COUNTRY)
			country = LIMIT_COUNTRY;
		summ -= country;
		if (faq > LIMIT_FAQ)
			faq = LIMIT_FAQ;
		summ -= faq;
		while (summ > 0 && limit > 0)
		{
			if (limits[1] > country && summ > 0)
			{
				country++;
				summ--;
			}
			if (limits[0] > link && summ > 0)
			{
				link++;
				summ--;
			}
			if (limits[2] > faq && summ > 0)
			{
				faq++;
				summ--;
			}
			limit--;
		}
		return new Array(link, country, faq);
	}
}
function VhqSearchLink(elem)
{
	this.title = elem.find('LinkTitle').text();
	this.keyword = elem.find('LinkKeywords').text();
	this.url = elem.find('LinkPath').text();
	this.image = elem.find('LinkImage').text();
}
VhqSearchLink.prototype = {
	title:null,
	keyword:null,
	url:null,
	image:null,
	type:'link',
	search:function(val)
	{
		return (this.keyword.toLowerCase().search(val) != -1);
	},
	getHtml:function(obj)
	{
		var html = '<div class="searchresult search_link" style="background:#fff;"><img src="' + this.image;
		html += '" alt="" title=""><a style="cursor:pointer;" class="uspasssearch" onclick="'+obj+'.goTo(\''+this.url+'\', \'link\')">' + this.title;
		html += '</a><div class="clear"></div></div>';
		return html;
	}
}
function VhqSearchFaq(elem)
{
	this.faq = elem.find('FaqQuestion').text();
	this.url = elem.find('FaqLink').text();
	this.image = elem.find('FaqImage').text();
}
VhqSearchFaq.prototype = {
	faq:null,
	url:null,
	image:null,
	type:'faq',
	search:function(val)
	{
		return (this.faq.toLowerCase().search(val) != -1);
	},
	getHtml:function(obj)
	{
		var line = this.faq.length >= 23? 'line-height:14px !important;': '';
		var html = '<div class="searchresult search_faq" style="background:#fff;"><img src="' + this.image;
		html += '" alt="" title=""><a style="cursor:pointer;'+line+'" onclick="'+obj+'.goTo(\''+this.url+'\', \'faq\');" class="uspasssearch">' + this.faq;
		html += '</a><div class="clear"></div></div>';
		return html;
	}
}
function VhqSearchCountry(elem)
{
	this.title = elem.find('CountryTitle').text();
	this.syn = elem.find('CountrySyn').text();
	this.url = elem.find('CountryVisa').text();
	this.embassy = elem.find('CountryEmbassy').text();
	this.customs = elem.find('CountryCustoms').text();
	this.image = elem.find('CountryImage').text();
	this.keyword = elem.find('CountryKeywords').text();
}
VhqSearchCountry.prototype = {
	title:null,
	syn:null,
	url:null,
	embassy:null,
	customs:null,
	image:null,
	keyword:null,
	type:'country',
	search:function(val)
	{
		return (this.title.toLowerCase().search(val) != -1 || this.syn.toLowerCase().search(val) != -1 || this.keyword.toLowerCase().search(val) != -1);
	},
	getHtml:function(obj)
	{
		var html = '<div class="searchresult search_country" style="background:#fff;"><img src="' + this.image;
		html += '" alt="" title=""><p><strong>' + this.title + '</strong><br><a style="cursor:pointer;" onclick="'+obj+'.goTo(\'';
		html += this.url+'\', \'country\');">'+vhqvars.searchText.visa+'</a> | <a style="cursor:pointer;" onclick="'+obj+'.goTo(\'';
		html += this.embassy+'\', \'country\');">'+vhqvars.searchText.embassy+'</a> | <a style="cursor:pointer;" onclick="'+obj;
		html += '.goTo(\''+this.customs+'\', \'country\');">'+vhqvars.searchText.customs+'</a></p><div class="clear"></div></div>';
		return html;
	}
}
