


this.autoCompleteClass = function()
{
	var input = document.getElementById('englishInput');
	
	this.subListSelected=-1;

	var englishSeparator = ""; //First instance will be preceding Prefecture name, ie Not needed ...
	var japaneseSeparator = ""; //...buildArrays sets as necessary each load
	
	this.keyboardNavigation = function(event) 
		{
		switch (event.keyCode) {
			case 9: if (event.shiftKey) this.selectPrevious(); else this.selectNext(); return false; //TAB keyup
			case 16: return false; //ignore lifting of SHIFT key
			
			case 13: return true; //EnterKey handled by enterKeyPressed() from onSubmit
			
			case 27: input.value=""; this.clearDropDown(); disableNextButton(); break; //ESC
			case 38: this.selectPrevious(); break; // upArrow
			case 40: this.selectNext(); break; // downArrow
			case 191: showSearch(); input.value=""; break; // '/' move focus to search box
			default: disableNextButton(); this.fillDropDown();
			}		
			
		return false; //disable BackSpace - navigator history etc
		}
		
	this.enterKeyPressed = function() {
		if ( subList.style.display=="block" ) {
				this.itemSelected( this.subListSelected );
				return false;
				}
		else
			return this.gone(this.subListSelected);
		}
		
	this.tabKeyDown = function() { //TAB key moves focus off input box before keyUp is triggered
		return (subList.style.display == "none"); //if no sublist to navigate with TAB, then return true and move off
		}
	this.backSpacePress = function() {
		if ( input.value == "")
			this.goHistory(-1);
		}


		
	var subList = document.getElementById("dropdown");
	this.fillDropDown = function()
		{
		if (englishArray.length==0) this.buildArrays(); //Failsafe - should be built at resultsFrame.onLoad
		input.style.color="black";
		
		if (input.value.charAt(0)>='a') // => lowercase first letter, make UpperCase
			input.value = input.value.charAt(0).toUpperCase() + input.value.substr(1);
		if (input.value.length==2 && input.value.charAt(0)==input.value.charAt(1).toUpperCase()) { //Repeated key-press cycles through current subArray
			input.value = input.value.charAt(0);
			this.selectNext();
			return;
			}
		else if ( this.subListSelected>=0 && subList.style.display!="block" && input.value.length > englishArray[this.subListSelected].length ) 
				{
				input.style.color="gray";
				disableNextButton();
				return; //sub Item already selected, now adding extra - numbers etc
				}
		else if ( this.subListSelected>=0 && input.value==englishArray[this.subListSelected] )
			{
			this.itemSelected( this.subListSelected );
			return;
			}


		this.populateSubArray();
		if (this.subListSelected >= 0) {
			subList.innerHTML = "";
			for (var j=x; j<y; ++j)
				subList.innerHTML += "<a id='subitem" +j+ "' href='#' onmouseover='selectSub(" +j+ ")' onclick='obj.mouseSelection(" +j+ ")'><strong>" + englishArray[j].substr(0,input.value.length) + "</strong>" 
								  + "<span class='selectedText'>" + englishArray[j].substr(input.value.length) + "</span></a>";
			subList.style.display = y>0?"block":"none";
			this.selectSub( this.subListSelected );
			}
		else {
			input.style.color="gray";
			disableNextButton();
			subList.style.display = "none";
			}
		}
	this.clearDropDown = function()
		{
		x=-1; y=-1;
		this.subListSelected=-1;
		subList.innerHTML = "";
		subList.style.display = "none";
		}
	
	
	var x=-1; var y=-1; // subList delimiters
	this.subListSelected=-1;
	this.populateSubArray = function()
		{
		y=-1;//reset
		this.subListSelected=-1;
		if (!input.value.length)
			return false; //No keypress/searchstring to match
	
		for (x=0; x<englishArray.length; ++x)
			if ( englishArray[x].indexOf(input.value) == 0) 
				break;
		if (x == englishArray.length)
			return false; //No matches -> return			
		
		for (y=x; y<englishArray.length; ++y)
			if ( englishArray[y].indexOf(input.value) != 0 ) 
				break; //Break on first non-match
	
		this.subListSelected = x;
		}
		
	
	this.selectSub = function(subItem) 
		{
		if (this.subListSelected>=0) { 
			document.getElementById("subitem" + this.subListSelected).style.background = "white";//"#ffffdd"; //Deselect previous subListSelected in anycase
			}
		if (subItem<x || subItem>=y) {
			//document.getElementById("inputCover").innerHTML = /*englishSeparator + */"<strong>" + addressString + "</strong>";
			return;
			}
	
		document.getElementById("subitem" + subItem).style.background = "#ffffbb";
		this.subListSelected = subItem;
		}
	this.selectNext = function() {
		this.selectSub( (this.subListSelected + 1 >= y)?x:this.subListSelected+1 )
		}
	this.selectPrevious = function() {
		this.selectSub( (this.subListSelected - 1 < x)?y-1:this.subListSelected-1 )
		}
	


	/* *** ********************************************************************************* *** */
	

	// Show selection, Gone
	this.mouseSelection = function(selIndex)
		{
		this.itemSelected(selIndex);
		
		if (linkArray[selIndex]!="srch")
			this.gone(selIndex);		
		}
		
	// Show selection
	this.searchResultSelected = function(selIndex)
		{
		}
	
	this.itemSelected = function( selIndex ) 
		{
		this.subListSelected = selIndex;
		input.value = englishArray[selIndex]; 
		subList.style.display = "none";

		if (linkArray[selIndex]=="srch") { // Search result
			input.value = englishArray[selIndex] + " ";
			input.style.color="gray";
			input.focus();			
			}
		else {
			enableNextButton();
			input.style.color = "black";
			}
		}
	




	/* *** ********************************************************************************* *** */



				
	this.gone = function(selIndex) 
		{
		if (selIndex<0)
			return false;

		if ( linkArray[selIndex]=="#" // => final link, pointing to map address
		  || !nextButtonEnabled() ) // => extra text added after selection => take straight to map
				{
				this.subListSelected=selIndex;
				return this.toMap();
				}

		document.getElementById('loadingPleaseWait').style.display = "block";
		document.getElementById('resultsFrame').src = "fopen.php?url=" + linkArray[selIndex];
//XXX		document.getElementById('resultsFrame').src = "JBrowse.html";

		this.setTitleEntries( englishArray[selIndex], kanjiArray[selIndex], linkArray[selIndex] );

		input.value = "";
//		englishArray.length=0; //XXX NOT NEEDED, buildArrays is done onLoad
		disableNextButton();
		this.clearDropDown();
		
		return false; //disable form submit this time
		}	
		
	var historyArray = new Array();
	this.setTitleEntries = function( english, kanji, link ) 
		{
		var historyEntry = historyArray.push( link ) - 1;
			
		if (!document.getElementById('ehistory' + historyEntry)) {
			document.getElementById("englishTitle").innerHTML += "<span id='ehistory" + historyEntry + "'></span>";
			document.getElementById("japaneseTitle").innerHTML += "<span id='jhistory" + historyEntry + "'></span>";
			}
		document.getElementById('ehistory' + historyEntry).innerHTML = englishSeparator + "<a href='#' onclick=\"obj.goHistory(" + historyEntry + ")\">" + english + "</a>";
		document.getElementById('jhistory' + historyEntry).innerHTML = japaneseSeparator + kanji;
		}
		
	this.goHistory = function( selIndex ) {
		if (selIndex == -1) //selIndex of -1 => call from backSpacePress
			selIndex = historyArray.length-2;
		if (selIndex < 0) { //Back to beginning
			document.location="index.html";
			return;
			}
			
		document.getElementById('loadingPleaseWait').style.display = "block";
		document.getElementById('resultsFrame').src = "fopen.php?url=" + historyArray[selIndex]; 

		//Remove subsequent entries in history list
		for ( var j=selIndex+1; j<historyArray.length; j++ ) {
			document.getElementById('ehistory' + j).innerHTML = "";
			document.getElementById('jhistory' + j).innerHTML = "";
			}
		historyArray.length = selIndex+1;
		input.value = "";
		}
		
	this.clearTitle = function() { //For continuation with Zenkoku mouseOut which fires after mouseClick on map!
		return false;
		}
		
	this.resetTitle = function() {
		historyArray.length = 0;
		document.getElementById("englishTitle").innerHTML = "";
		document.getElementById("japaneseTitle").innerHTML = "";
		input.value = "";
		this.clearDropDown();
		}
		
	
	this.toMap = function()
		{
		if (document.getElementById("mapsRadioButtons1").checked) document.forms['toMapForm'].map.value = "mapion";
			else if (document.getElementById("mapsRadioButtons2").checked) document.forms['toMapForm'].map.value = "mapfan";
			else document.forms['toMapForm'].map.value = "google"; //DEFAULT

		var query = "";//document.getElementById('japaneseTitle').innerHTML;

		for (var i=0; i<historyArray.length; i++) 
			query += document.getElementById('jhistory' + i).innerHTML;
		
		if (this.subListSelected>=0) query += (query.length>0?japaneseSeparator:"") + kanjiArray[this.subListSelected] 
									  + input.value.substr( englishArray[this.subListSelected].length ); //PLUS any extra text (ie numbers)
		else if (input.value != "") query += japaneseSeparator + input.value; //otherwise add whatever text is in there, only USEFUL would be NUMBERS, so we need to add JAPANESE SEPARATOR

		document.forms['toMapForm'].query.value = query.replace(/ /g, "");//Remove all spaces for submission to map sites		
		document.forms['toMapForm'].submit(); 
			// Would like to return true; but need to submit() for mouseClicks from links - seems to work fine ...
		}

	/* *** ********************************************************************************* *** */
	
	var	englishArray = new Array();
	var	kanjiArray;
	var	linkArray;
		
	this.buildArrays = function()
		{
		//top.document.title = document.getElementById('englishTitle').innerHTML
			//		+ " (" + document.getElementById('japaneseTitle').innerHTML + ")";

		var results = document.getElementById("resultsFrame").contentWindow.document.getElementsByTagName('a');
		englishArray = new Array();
		kanjiArray = new Array();
		linkArray = new Array();
		
		var maxLength=10;//Bare minimum for inputBox width
		for (var i=0; i<results.length; ++i) {
			var span = results[i].getElementsByTagName('span');
			if (span[0].className == "addressName") {
				englishArray.push( span[1].innerHTML );
				kanjiArray.push( span[3].innerHTML );
				linkArray.push( span[4].innerHTML );	
				if (span[1].innerHTML.length > maxLength) maxLength=span[1].innerHTML.length;
				}
			else {
				kanjiArray.push( span[1].innerHTML );
				englishArray.push( span[2].innerHTML );
				linkArray.push( span[3].innerHTML );	
				if (span[1].innerHTML.length > maxLength) maxLength=span[1].innerHTML.length;
				}
			}
			
		input.style.width = (maxLength*10) + "px";
		document.getElementById("inputControls").style.width = ((maxLength*10) + 26) + "px";
		input.value = "";	
		this.subListSelected = -1;
		
		// *** Set ',' or '-' separators for title
		titleEnd = document.getElementById("englishTitle").innerHTML.substr(-11-1, 1);//-11 for </a></span>, then -1
			if (titleEnd>=0 && titleEnd<=9) { //if into numbers, separate with dashes
				englishSeparator = "-";
				japaneseSeparator = "-";
				}
			else {
				englishSeparator = ", ";
				japaneseSeparator = " ";
				}
			
		//When done, focus to inputBox
		input.focus();
		}

} //End of autoCompleteClass



/* *** ********************************************************************************* *** */
//Global functions


function toggleMapsRadioLayer() {
	 if ( document.getElementById('mapsRadioLayer').style.display != 'block') {
		document.getElementById('mapsRadioLayer').style.display = 'block';
		document.getElementById('mapsRadioButtons1').focus();
		}
	else
		document.getElementById('mapsRadioLayer').style.display = 'none';
	 }

function mapsRadioButtonsClick( button )
	{
	document.getElementById("googleButton").style.display = (button==0)?"block":"none";
	document.getElementById("mapionButton").style.display = (button==1)?"block":"none";
	document.getElementById("mapfanButton").style.display = (button==2)?"block":"none";

	document.getElementById("mapsRadioButtons" + button ).checked = "checked";
	document.getElementById('mapsRadioLayer').style.display="none";
	}

function disableNextButton() { document.getElementById("nextButton").style.top = "-24px";	}
function enableNextButton() { document.getElementById("nextButton").style.top = "0";	}
function nextButtonEnabled() { return document.getElementById("nextButton").style.top!="-24px"; }
	


function showSearch() {
	document.getElementById('search').style.display='block';
	document.getElementById('search').focus();
	}

function yuubinSearch() 
		{	
		//obj.hidePrefecturesList();

		document.getElementById('loadingPleaseWait').style.display = "block";
		document.getElementById("resultsFrame").style.display="block";

		//Clear any previous entries
		obj.resetTitle();
		
		obj = new autoCompleteClass();
		}


