//* **************************************************************************************
// * 
// * DataClass
//*		Holds recycling address Arrays, and persistant historyArray 
// * 
//* **************************************************************************************	
AddressDataClass = function() {
	this.historyArray = new Array();

	this.initialize = function() {	
			// *** First use initialize here for Zenkoku 
			this.englishArray = new Array( "Aichi", "Akita", "Aomori", "Chiba", "Ehime", "Fukui", "Fukuoka", "Fukushima", "Gifu", "Gunma", "Hiroshima", "Hokkaido", "Hyogo", "Ibaraki", "Ishikawa", "Iwate", "Kagawa", "Kagoshima", "Kanagawa", "Kochi", "Kumamoto", "Kyoto", "Mie", "Miyagi", "Miyazaki", "Nagano", "Nagasaki", "Nara", "Nigata", "Oita", "Okayama", "Okinawa", "Osaka", "Saga", "Saitama", "Shiga", "Shimane", "Shizuoka", "Tochigi", "Tokushima", "Tokyo", "Tottori", "Toyama", "Wakayama", "Yamagata", "Yamaguchi", "Yamanashi");
			this.kanjiArray = new Array("°¦ÃÎ¸©", "½©ÅÄ¸©", "ÀÄ¿¹¸©", "ÀéÍÕ¸©", "°¦É²¸©", "Ê¡°æ¸©", "Ê¡²¬¸©", "Ê¡Åç¸©", "´ôÉì¸©", "·²ÇÏ¸©", "¹­Åç¸©", "ËÌ³¤Æ»", "Ê¼¸Ë¸©", "°ñ¾ë¸©", "ÀÐÀî¸©", "´ä¼ê¸©", "¹áÀî¸©", "¼¯»ùÅç¸©", "¿ÀÆàÀî¸©", "¹âÃÎ¸©", "·§ËÜ¸©", "µþÅÔÉÜ", "»°½Å¸©", "µÜ¾ë¸©", "µÜºê¸©", "Ä¹Ìî¸©", "Ä¹ºê¸©", "ÆàÎÉ¸©", "¿·³ã¸©", "ÂçÊ¬¸©", "²¬»³¸©", "²­Æì¸©", "ÂçºåÉÜ", "º´²ì¸©", "ºë¶Ì¸©", "¼¢²ì¸©", "Åçº¬¸©", "ÀÅ²¬¸©", "ÆÊÌÚ¸©", "ÆÁÅç¸©", "ÅìµþÅÔ", "Ä»¼è¸©", "ÉÙ»³¸©", "ÏÂ²Î»³¸©", "»³·Á¸©", "»³¸ý¸©", "»³Íü¸©" );
			this.linkArray = new Array( "23/index.html", "05/index.html", "02/index.html", "12/index.html", "38/index.html", "18/index.html", "40/index.html", "07/index.html", "21/index.html", "10/index.html", "34/index.html", "01/index.html", "28/index.html", "08/index.html", "17/index.html", "03/index.html", "37/index.html", "46/index.html", "14/index.html", "39/index.html", "43/index.html", "26/index.html", "24/index.html", "04/index.html", "45/index.html", "20/index.html", "42/index.html", "29/index.html", "15/index.html", "44/index.html", "33/index.html", "47/index.html", "27/index.html", "41/index.html", "11/index.html", "25/index.html", "32/index.html", "22/index.html", "09/index.html", "36/index.html", "13/index.html", "31/index.html", "16/index.html", "30/index.html", "06/index.html", "35/index.html", "19/index.html" );
			}

	// *** Subsequent uses, rebuild arrays here	
	this.buildArrays = function() {
		//top.document.title = document.getElementById('englishTitle').innerHTML
			//		+ " (" + document.getElementById('japaneseTitle').innerHTML + ")";					var results = document.getElementById("resultsFrame").getElementsByTagName('a');
		this.englishArray = new Array();
		this.kanjiArray = new Array();
		this.linkArray = new Array();
		
		var longestString=10;// initialize a bare minimum for inputBox width
		for (var i=0; i<results.length; ++i) {

			var span = results[i].getElementsByTagName('span');
			if (span[0].className == "addressName") {
				this.englishArray.push( span[1].innerHTML );
				this.kanjiArray.push( span[3].innerHTML );
				this.linkArray.push( span[4].innerHTML );	
				if (span[1].innerHTML.length > longestString) longestString=span[1].innerHTML.length;
				}
			else {
				this.kanjiArray.push( span[1].innerHTML );
				this.englishArray.push( span[2].innerHTML );
				this.linkArray.push( span[3].innerHTML );	
				if (span[1].innerHTML.length > longestString) longestString=span[1].innerHTML.length;
				}

			}
						
		return longestString;
		}

	this.pushHistory = function( index ) {
		return this.historyArray.push( this.linkArray[index] );	
		}
	this.popHistory = function() {
		this.historyArray.pop();	// We have no need for return value 
		}
	this.getHistoryCurrent = function() {
		return this.historyArray[ this.historyArray.length - 1 ];
		}


	} // end of addressData class 
	
var addressData = new AddressDataClass(); 







//* **************************************************************************************
// * 
// * CONTROL class for first page: ZenkokuClass 
//*
//* **************************************************************************************	
ZenkokuControl = function() {
	this.currentLink = 0;
	addressData.initialize(); 

	//*** resetTempTitle gets disabled in gone(), so must be re-enabled each 			
	zenkoku.enableResetTitle(); 
	zenkoku.resetTempTitle();

				
	//* **************************************************************************************
	// * 
	// * EVENT CONTROL 
	//*
	//* **************************************************************************************	
	this.keyboardNavigation = function( event )
		{
		input.value = "";
		
		zenkoku.showPrefecturesList();
		switch (event.keyCode) {
			case 8: // Disable BackSpace key
				return false; 						case 13: // Disable enter: Handled by enterKeyPress below
				return false; 

			case 27: // ESC
				zenkoku.hidePrefecturesList(); document.getElementById('search').style.display='none'; return; 
			case 37: // Up 
				newLink = this.currentLink - 1; break;
			case 39: // Down 
				newLink = this.currentLink + 1; break;
			case 191: //  '/' slash key: reveal and focus searchbox 
				setSearch(); zenkoku.hidePrefecturesList(); return; // '/' move focus to search box
			default: 
				newLink = this.findNext( String.fromCharCode(event.keyCode) );
			}

		if (newLink != this.currentLink) 
			{
			zenkoku.highlightSpan( document.getElementById(newLink) );			
			if (this.currentLink>0) 			//Reset previously highlighted link
				zenkoku.unHighlightSpan( document.getElementById(this.currentLink) );
			this.currentLink = newLink; 
			}
		} //end of keyboardNavigation 


	// *** cycle through list of prefectures beginning with char 'searchKey'
	this.findNext = function( searchKey ) {
			var i = this.currentLink + 1; //start cycle from immediate next link	
			for ( i; i<=47; ++i )
				if (addressData.englishArray[i-1].charAt(0)==searchKey) 
					return i;		
			//If cycled to end with no result	
			for ( i=1; i<this.currentLink; ++i )
				if (addressData.englishArray[i-1].charAt(0)==searchKey) 
					return i;
			//If still nothing	
			return this.currentLink;
			}




		
	this.enterKeyPressed = function() {
		this.gone(this.currentLink);
		return false; //stop form submit
		}


		
	/* *** ************************************************************************************* *** */

	this.gone = function( prefecture ) {
//		if (this.currentLink>0) prefecture=this.currentLink; //'enter' keypress sometimes coming from focused map-item, NOT pref list as expected!
//		else this.currentLink = prefecture;
		
		zenkoku.hidePrefecturesList();		
		zenkoku.clearTempTitle();
		
		//*** mouseout is calling resetTitle AFTER / simultaneous thread, to autoCompleteClass!		
		zenkoku.disableResetTitle();//resetTempTitle = function() {};
		
//		document.getElementById("JapanMap").innerHTML = ""; // *** free-up extensive mouse-overs on base layer (sometimes still active past edges of resultsFrame) 
		document.getElementById("resultsFrame").style.display="block"; 	

		// Set hidden form value for fopen.php 
			document.getElementById("pref").value = addressData.linkArray[prefecture-1].substr(0,2);
			document.getElementById("prefName").value = addressData.englishArray[prefecture-1];

		// Move control over to main autoComplete object 
		obj = new autoCompleteClass();
			addressData.englishArray[prefecture-1] += (prefecture==41?" Met": " Pref");
			obj.setTitle( prefecture-1 );
			obj.processAddressURL( addressData.linkArray[prefecture-1] ); //+ "&ecomposite=" + addressData.englishArray[prefecture-1] ); 
		}


	//For consistency with AutoComplete.js
	this.goHistory = function( ref ) {
		return false; //No use on first page, do nothing
		}
		
		
} // *** End of Zenkoku class ************************************************************************






//* **************************************************************************************
// * 
// * DISPLAY class for first page: ZenkokuDisplay
//*
//* **************************************************************************************		
ZenkokuDisplay = function() {
	var eTitle = document.getElementById('englishTitle');
	var jTitle = document.getElementById('japaneseTitle');
	
	/* onHistory, return Zenkoku display to original page */	
	this.resetAll = function() {
		document.getElementById("helpBox").style.left = "460px";
		input.style.width = "150px";
		setHelpText( helpText.helpZenkoku, obj._isResult ); 
	
	
		}

	/* *** ************************************************************************************* *** */
	/* Title setting only temporary in Zenkoku. 
	/*		  Must be REVOKED immediately on GONE() otherwise mouseOut can fire and blank the title!
	/* *** ************************************************************************************* *** */
	this.setTempTitle = function( linkNumber )	{
		eTitle.innerHTML = addressData.englishArray[linkNumber - 1];
		jTitle.innerHTML = addressData.kanjiArray[linkNumber - 1];
		input.value = "";
		}
	this.clearTempTitle = function() {
		eTitle.innerHTML = "";
		jTitle.innerHTML = "";
		}

	this.resetTempTitle;		
	resetTitle = function() {	
		eTitle.innerHTML = "<span style='font-size: 16'>Select your</span>";
		jTitle.innerHTML = "<span style='font-size: 16'> prefecture ...</span>";
		}

	// *** disable() called from gone()
	this.disableResetTitle = function() { 
			this.resetTempTitle = function() {}
			}
	// *** enable() called from CTR for ZenkokuControl (ie on first load, plus any subsequent history back to first page)
	this.enableResetTitle = function() {
			this.resetTempTitle = function() { resetTitle(); }
			}		 

  this.highlightSpan = function( item ) {
			item.innerHTML = item.innerHTML.replace("unselected","selected");
			this.setTempTitle( item.id );	
			this.myMouseOver( item.id );
			}
	this.unHighlightSpan = function( item ) {
			item.innerHTML = item.innerHTML.replace("selected","unselected");
			this.myMouseOut( item.id );
			}
		

	this.myMouseOver = function(prefID) {
		document.getElementById(addressData.englishArray[prefID - 1] + '0').style.backgroundRepeat = "repeat-x";
		}
	this.myMouseOut = function(prefID) {
		document.getElementById(addressData.englishArray[prefID - 1] + '0').style.backgroundRepeat = "no-repeat";
		}


	//************************************************************************************************
	
	this.showPrefecturesList = function()	{
		document.getElementById('links').style.display = 'block';
		document.getElementById('background').style.display = 'block';
		document.getElementById('ShowPrefectures').style.display = 'none';
		}
	this.hidePrefecturesList = function() {
		document.getElementById('links').style.display = 'none';
		document.getElementById('background').style.display = 'none';
		document.getElementById('ShowPrefectures').style.display = 'block';
		if (obj.currentLink > 0) 
				this.unHighlightSpan( document.getElementById(obj.currentLink) );	
		obj.currentLink=0;
		this.resetTempTitle();
		}
	

}	//* *** End of ZenkokuDisplay class ****************************************************************









/* *** ************************************************************************************* *** */
/* Search routines
/* *** ************************************************************************************* *** */ 
function setSearch() {
	document.getElementById('searchBox').onmouseout = ""; //disable onMouseOut 
	document.getElementById('searchQuery').style.display='block';
	
	this.prevHelp = document.getElementById('tipNumber').innerHTML - 1;
	setHelpText( 0, true ); 

	document.getElementById('searchQuery').focus();
	document.getElementById('searchQuery').select();
	}
	
function unsetSearch() {
	document.getElementById('searchBox').onmouseout = hideSearch; // re-enable onMouseOut 
	document.getElementById('searchQuery').style.display='none';

	if (this.prevHelp >= 0) {
			setHelpText( this.prevHelp, obj._isResult );
			this.prevHelp = -1; // Neutralise this flag once reset to prevent repeated resets 
			}
	}

function hideSearch() {	document.getElementById('searchQuery').style.display = "none"; }

function yuubinSearch( searchstr ) {
		var searchURL = "search.php?" + "q=" + searchstr;

		var hasPref = document.getElementById('ehistory1');
		if (hasPref) {
				searchURL += "&pref=" + addressData.historyArray[0].substring(0,2)
								+ "&prefName=" + hasPref.innerHTML.replace(/\<[^\>]*\>|\&nbsp\;|,/gi, "");	//remove all tags, &nbsp and commas
				}

		/* obj.hidePrefecturesList(); */ 		document.getElementById('mapLayer').style.display = 'none'; 
		document.getElementById('loadingPleaseWait').style.display = "block";
		document.getElementById("resultsFrame").style.display="block";

		this.prevHelp = -1; // effectively disable reset helpText 
		ajaxFunction( searchURL, ajaxSearchHandler ); 	
		}

ajaxSearchHandler = function( responseText ) {
		document.getElementById('loadingPleaseWait').style.display = 'none'; 
   	document.getElementById('resultsFrame').innerHTML = responseText;
		document.getElementById("titleSpacer").style.display = "none"; 	//Allow englishInput to take whole of title bar. 
		input.focus();

		/* If no negative result quoted*/
   	if ( responseText.search(/0 matches/)==-1 ) {
				/* Clear any previous entries */				obj = new autoCompleteClass();
				obj.resetTitle();		
				obj.initialize();
		   	document.getElementById('resultsFrame').scrollTop = 0;
				}
		else
   			setSearch();
		}





//*** ******************************************
//*
//* Help display function, and text entries
//* 
//********************************************** 
function showHelp(onoff) {
		document.getElementById('helpBox').style.display = (onoff? 'block':'none');
	// Ensure key-press focus remains in the input box 	
		input.focus();
	}
	
var helpText =  { "helpZenkoku" : 0, "helpNewPage" : 1, "helpDropDownVisible" : 2, "helpSubListSelected" : 3, "helpExtraInput" : 4 };
function setHelpText( n, _isResult ) {
	document.getElementById('tipNumber').innerHTML = (1.0 + n);
	document.getElementById('helpText').innerHTML = _isResult? resultsHelpArray[n] : helpTextArray[n];
	}
	
const helpTextArray= new Array(	
			"First select your desired prefecture from the map, or press \
				any key to display a list of all forty seven prefectures and cycle through \
				each that begin with that letter.",
			"Select a sub-address from the results table, or begin typing your desired entry \
					for autocomplete to generate a drop down list of matches.",
			 "Continue typing to refine the list, or navigate the available choices \
					with the Up/Down arrow keys, or Tab/Shift-Tab, and press Enter to pre-select.\
					<br>You can also select with the mouse.",
			"Now that you have selected a sub-address, you can \
					click on the green 'Next' button &lt;Enter key&gt; to generate that item's listing; \
					 <br> \
					 or if appropriate 	you can directly add the district/block/house numbers to go straight to the map.",
			"When you have completed the address numbers, press Enter to go directly to the map.\
					 <br>\
					You can also click the Google Maps button at the top-right when ready,\
					or choose a different external map site from the drop down list."					 
			);
const resultsHelpArray = new Array(	
			"&lt;&lt;&lt;&lt; Search Mode: \
			 Enter a query string to find any matching addresses. \
			 <br>&nbsp;(Note that the official romanised spellings of  \
			 Japanese place names often cause difficulties here)",
			"Click on a result, or begin typing your desired entry \
					for autocomplete to generate a drop down list of matches.\
					<br>&nbsp;For a smaller result set, try first choosing a prefecture before performing the search.",
			 "Continue typing to refine the list, or navigate the available choices \
					with the Up/Down arrow keys, or Tab/Shift-Tab, and press Enter to pre-select.\
					<br>You can also select with the mouse.",
			"Now that you have selected a search result, you can \
					press Enter to go straight to the map. \
					<br>&nbsp;\
					Or you may add the district/block/house numbers to locate a specific address.",
			"When you have completed the address numbers, press Enter to go directly to the map.\
					 <br>&nbsp;\
					You can also click the Google Maps button at the top-right,\
					or choose a different external map site from the drop down list."					 
			);
