//Array of existing typehead windows
var searchBoxList = new Array();

// Set properties for typeahead text window
function SetProperties(xElem,xHidden,xDomainName,xserverCode,xshowResultsCount){
	var props={
	elem: xElem,
	hidden: xHidden,
	domainName: xDomainName,
	serverCode: xserverCode,
	showResultsCount: xshowResultsCount
	};
	AddHandler(xElem);
	searchBoxList.push(xElem);
	return props;
}

//Add handlers 
var isOpera=(navigator.userAgent.toLowerCase().indexOf("opera")!= -1);
function AddHandler(objText){
	objText.onkeyup = GiveOptions;
	objText.onblur = function() {
		showResultBox = false;
	}
	objText.onfocus = ShowOptions;
	if(isOpera)objText.onkeypress = GiveOptions;
}

var linkSearchResults = new Array();
var countrySearchResults = new Array();
var strLastValue = ""; // Last string from text window
var bMadeRequest; // Is ajax request send to server?
var lastRequestValue = "";
var theTextBox;
var showResultBox = true;
var currentSelected = -1;
var orderID = -1;
var titleList = new Array();

function GiveOptions(e){
	var intKey = -1;	
	if(window.event){
     	intKey = event.keyCode;
		theTextBox = event.srcElement;
	}
	else{
     	intKey = e.which;
		theTextBox = e.target;
	}
	if(intKey == 13) {
		gotoSearch();
		return false;
	}
	else if(intKey == 38) {
		MoveHighlight(-1);
		return false;
	}
	else if(intKey == 40) {
		MoveHighlight(1);
		return false;
	}
	if(theTextBox.value.length == 0 && !isOpera){
		linkSearchResults = new Array();
		countrySearchResults = new Array();
     	HideSearchBox();
		strLastValue = "";
          return false;
     }	
	if(theTextBox.value != strLastValue) {
		HideSearchBox();
		if(((theTextBox.value.indexOf(strLastValue) != 0) ||
		   (linkSearchResults.length==0 && countrySearchResults.length==0)) && !bMadeRequest){
		   	bMadeRequest = true;
		   	TypeAhead(theTextBox.value);
		}
		else if(!bMadeRequest){
			BuildList(theTextBox.value);
		}
		strLastValue = theTextBox.value;
	}
}

function ShowOptions() {
	BuildList(this.value);
}

function HideSearchBox() {
	currentSelected = -1;
	orderID = -1;
	var searchBox = document.getElementById("searchbox");
	addCSSClass(searchBox,"no_display");
}

function gotoSearch() {
	TypeAheadStat('http://'+theTextBox.obj.domainName+'/search.php?visa_search='+theTextBox.value, 'search');
}

function MoveHighlight(step) {
	if(orderID < 0)
		return false;
	var pos = currentSelected + step;
	if(pos < 0)
		currentSelected = orderID;
	else if(pos > orderID)
		currentSelected = 0;
	else
		currentSelected = pos;
	for(var i=0; i<=orderID; i++)
	{
		var searchResultID = document.getElementById("search_result_div_"+i);
		if(searchResultID) {
			if(currentSelected == i) {
				searchResultID.style.background = "#D5EBBA";
				theTextBox.value = titleList[i];
			}
			else
				searchResultID.style.background = "#FFFFFF";
		}
	}
}

//Send request to the server
function TypeAhead(xStrText){
	lastRequestValue = xStrText;
	var strParams = "q=" + xStrText;
    var loader1 = new net.ContentLoader('/'+theTextBox.obj.serverCode,BuildChoices,null,"POST",strParams);
}

function BuildChoices(){
	var strXML = this.req.responseXML;
	var xmlLinkResults = strXML.getElementsByTagName("LinkResult");
	bMadeRequest = false;
	if(xmlLinkResults) {
		var lrlen = xmlLinkResults.length;
		if(lrlen>0) 
			linkSearchResults = xmlLinkResults;
	}
	var xmlCountryResults = strXML.getElementsByTagName("CountryResult");
	if(xmlCountryResults) {
		var crlen = xmlCountryResults.length;
		if(crlen>0) 
			countrySearchResults = xmlCountryResults;
	}
	BuildList(theTextBox.value)
}

function BuildList(textBoxValue) {
	if(textBoxValue.length>0)
	{
		orderID = -1;
		currentSelected = -1;
		titleList = new Array();
		if(textBoxValue.indexOf(lastRequestValue) == 0) {
			var searchBox = document.getElementById("searchbox");
			var searchResults = document.getElementById("searchresults");
			searchResults.innerHTML = '';
			var checkResult = false;
			var resCount = 0;
			var lrlen = linkSearchResults.length;
			for(var i = 0; i<lrlen; i++) {
				if(BuildLinkResult(searchResults,linkSearchResults[i],textBoxValue)) {
					checkResult = true;
					resCount++;
					if(resCount>=theTextBox.obj.showResultsCount)
						break;
				}
			}
			var crlen = countrySearchResults.length;
			for(var i = 0; i<crlen; i++) {
				if(BuildCountryResult(searchResults,countrySearchResults[i],textBoxValue)) {
					checkResult = true;
					resCount++;
					if(resCount>=theTextBox.obj.showResultsCount)
						break;
				}
			}
			if(checkResult)
				removeCSSClass(searchBox,"no_display");
		}
		else
			TypeAhead(textBoxValue);
	}
}

function BuildLinkResult(searchResults,linkResult,compareValue)
{
	var linkTitle = getElementContent(linkResult,'LinkTitle');
	var linkKeywords = getElementContent(linkResult,'LinkKeywords');
	if(FilterValues(linkTitle,compareValue) || FilterValues(linkKeywords,compareValue)) {
		orderID++;
		var linkPath = getElementContent(linkResult,'LinkPath');
		var linkImage = getElementContent(linkResult,'LinkImage');
		searchResults.innerHTML += '<div id="search_result_div_'+orderID+'" class="searchresult"><img src="'+linkImage+'" alt=""><a href="'+linkPath+'" class="uspasssearch" onclick="javascript:TypeAheadStat(\''+linkPath+'\',\'link\');return false;">'+linkTitle+'</a><div class="clear"></div></div>';
		titleList[orderID] = linkTitle;
		/*var div = document.createElement("div");
		div.id = "search_result_div_"+orderID;
		div.className = "searchresult";
		var img = document.createElement("img");
		img.src = linkImage;
		img.alt = "";
		var a = document.createElement("a");
		a.href = "javascript:void(0)";
		a.onclick = function(){TypeAheadStat(linkPath,'link')};
		a.className = "searchresult";*/
		return true;
	}
	return false;
}

function BuildCountryResult(searchResults,countryResult,compareValue)
{
	var countryTitle = getElementContent(countryResult,'CountryTitle');
	var countrySyn = getElementContent(countryResult,'CountrySyn');
	if(FilterValues(countryTitle,compareValue) || FilterValues(countrySyn,compareValue)) {
		orderID++;
		var countryVisa = getElementContent(countryResult,'CountryVisa');
		var countryEmbassy = getElementContent(countryResult,'CountryEmbassy');
		var countryCustoms = getElementContent(countryResult,'CountryCustoms');
		var countryImage = getElementContent(countryResult,'CountryImage');
		searchResults.innerHTML += '<div id="search_result_div_'+orderID+'" class="searchresult"><img src="'+countryImage+'" alt=""><p><strong>'+countryTitle+'</strong><br><a href="'+countryVisa+'" onclick="javascript:TypeAheadStat(\''+countryVisa+'\',\'country\');return false;">Visa</a> | <a href="'+countryEmbassy+'" onclick="javascript:TypeAheadStat(\''+countryEmbassy+'\',\'country\');return false;">Embassy</a> | <a href="'+countryCustoms+'" onclick="javascript:TypeAheadStat(\''+countryCustoms+'\',\'country\');return false;">Customs</a></p><div class="clear"></div></div>';
		titleList[orderID] = countryTitle;
		return true;
	}
	return false;
}

function FilterValues(matchValue,compareValue)
{
	var regExp = new RegExp("\\b" + compareValue,"gi");
	var test = regExp.test(matchValue);
	return test;
}

function getElementContent(element,tagName) 
{
	var childElement = element.getElementsByTagName(tagName)[0];
	if(childElement!=undefined)
		return childElement.text != undefined ? childElement.text : childElement.textContent;
	else
		return undefined;
}

//Send request to the server
function TypeAheadStat(theLinkPath,theType){
	var strParams = "q=" + escape(theTextBox.value) + "&page=" + escape(theLinkPath) + "&type=" + theType;
     var loader2 = new net.ContentLoader("/typeahead_stat.php",StatCallBack,null,"POST",strParams);
}

function StatCallBack()
{
	var theLinkPath = this.req.responseText;
	window.location.href = theLinkPath;
}

function searchFormSubmit() {
	return false;
}

document.onclick = function(e) {
	if(typeof(showResultBox) != "undefined" && showResultBox == false) {
		var mouseLeft = 0;
		var mouseTop = 0;
	  	if (!e) e = window.event;
	  	if (e.pageX || e.pageY) {
	    	mouseLeft = e.pageX;
	    	mouseTop = e.pageY;
	  	}
	  	else if (e.clientX || e.clientY) {
	    	mouseLeft = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
	    	mouseTop = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
	  	}
		var searchBox = document.getElementById("searchbox");
		if(typeof(searchBox) != "undefined") {
			searchPos = getElementPosition(searchBox);
			if(mouseTop>(searchPos.top+searchPos.height) || mouseTop<searchPos.top || mouseLeft>(searchPos.left+searchPos.width) || mouseLeft<searchPos.left) {
				HideSearchBox();
				showResultBox = true;
			}
		}
	}
}


function initSearch()
{

	var compEl = document.forms["typeAheadSearch"].typeAheadText; 


	compEl.onfocus = focusSearch;
	compEl.onblur = blurSearch;
	return;
}

function focusSearch(e)
{
	var reg = /[\s]*Search[\s]+VisaHQ\.com[\s]*/;
	var reg_ca = /[\s]*Search[\s]+VisaHQ\.ca[\s]*/;
	if(reg.test(this.value) || reg_ca.test(this.value))
		this.value = '';
	this.className = "regfield";
	return;
}

function blurSearch(e)
{

	var reg = /^[\s]*$/;
	if(reg.test(this.value))
	{
		sub_arr_domain_1=document.location.host.split('.');
		if(sub_arr_domain_1[3]==null)
			my_result_domain_string=sub_arr_domain_1[2];
		else
			my_result_domain_string=concat(consub_arr_domain_1[2],".",sub_arr_domain_1[3]);
		
		this.className = "regfieldb";
		this.value = "Search VisaHQ."+my_result_domain_string;
	}
	return;
}
