﻿//  ================================================================== Presentation Layer
//   Used by Champion Tree search page - called from CTdataEntry.htm
//  ================================================================== Tested: IE6 IE7 Firefox  Safari3.0

//  This code creates the ajax object and implements the search 'suggest box'

//  Found at: www.dynamicajax.com/fr/AJAX_Suggest_JavaScript-271_290_312_314.html
//  Called by: devlwww.dnr.state.wi.us/forestry/UF/champion/testServer/suggestTEst6.htm

var divPosition = 0;            // Used for keeping our place in the suggest box div entries
var divPositionMax = 0;         // Used to store total # of div's in for each suggest box
var direction = 'down';         // Used to keep track of up-arrow down-arrow direction
var veryFirstDownArrow = true;  // Boolean 
var controlId = 'aaa';
var prevControlId = '';         // Used to find out when user clicks a different box
var browserIsIE = false;        // Using 'isIE6' now        IE cache wont let go of this ! ! !
var keyCode = '';               // Used for keyboard key ID
var keyCharacter = '';          //  "   "       "   character ID




//Gets the browser-specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
//	    browserIsFF = true;
//      alert('getXml: browserIsFF=' + browserIsFF + '\nbrowserIsIE=' + browserIsIE);   //2nd
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
	  //browserIsIE = true;
//      alert('getXml: browserIsFF=' + browserIsFF + '\nbrowserIsIE=' + browserIsIE);
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		alert("Your browser may be out of date!\nIt's about time to upgrade don't you think?");
	}
}


//Our XmlHttpRequest object to get the auto suggest
var searchReq = getXmlHttpRequestObject();
var searchType;


// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//Called from keyup on the search textbox.
//Starts the AJAX request.
function searchSuggest(evt, type) {
    //PASSED IN VALUES FOR type:  Genus,  CN,  Cty

    //WE NEED TO EXCLUDE THE CASE WHERE DOWN or UP ARROW IS PRESSED
  //if (browserIsIE) { var evt=window.event;  keyCode = evt.keyCode }
	if (isIE6) { var evt=window.event;  keyCode = evt.keyCode } 
	if (isIE7) { keyCode = evt.keyCode } 
	else { keyCode = evt.which } //FFox, Mozilla or Safari
	keyCharacter = String.fromCharCode(keyCode);

    //alert('In searchSuggest() \n keyCode='+keyCode + '\nCharacter was ' + keyCharacter);     

     if (keyCode == 40) {
     //    alert('in searchSuggest from down-arrow keyup');  //Do nothing
     }
     else if (keyCode == 38) { 
     //    alert('in searchSuggest from up-arrow keyup');    //Do nothing
     }
     else if (keyCode == 13) { 
     //    alert('in searchSuggest from Enter');             //Do nothing
     }
     else {    
        searchType = type;
        //alert('searchSuggest()  type = ' + searchType);
	    if (searchReq.readyState == 4 || searchReq.readyState == 0) {
	        //get contents of search textbox and URL encode it w javascript escape function so we can pass it in our URL querystring.
		    var str = escape( document.getElementById('txt'+type).value );      //.toUpperCase()
	        //alert('str = ' + str);
	        if (searchType == 'Species') {
	            var genusStr = escape( document.getElementById('txtGenus').value );
	                    //             document.getElementById
	            // www.nicknettleton.com/zine/javascript/trim-a-string-in-javascript
	            // www.w3schools.com/jsref/jsref_replace.asp
	            var trimmed = genusStr.replace(/ /, "") ;   //not working
    		    var URLstring = 'CTxmlSuggest.asp?type=' + type  +  '&genus=' + trimmed ;
    //   		alert(URLstring);
    	    }
            else {
		        var URLstring = 'CTxmlSuggest.asp?search=' + str  +  '&type=' + type ;
		    }
   		    searchReq.open("GET", URLstring, true);
		    searchReq.onreadystatechange = handleSearchSuggest; 
		    searchReq.send(null);
    		
		    //Now show the div
		    document.getElementById('search_suggest_'+type).style.visibility = 'visible';
	    }
      }		
}


// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//Called when the AJAX response is returned.
//called every time the state of the searchReq XmlHttpRequest object changes
function handleSearchSuggest() {
    //make sure our response is ready
    //alert('handleSearchSuggest()  type = ' + searchType);
    //document.write('<br clear="all" />');
	if (searchReq.readyState == 4) {
	    //get a reference to our search_suggest DIV on HTML page. (is just a shortcut since we'll be adding & removing items from this DIV.)
		var ss = document.getElementById('search_suggest_'+searchType)      // <---------------- line 51
		ss.innerHTML = '';
    
		//Get text from response and split up into array of strings:
		var str = searchReq.responseText.split("\n");   //alert(str);
		//str contains all words from the xml that begin with the entered letter(s).

		//Loop through each string and add a new DIV to our search_suggest.  (This can be more elegant in FF by using DOM to create DIV element, but IE doesn't recognize dynamically added attributes for some reason, so JavaScript wouldn't work.  
		//Instead simply construct the DIV as a string and add it to innerHTML of search_suggest DIV.
		for(i=0; i < str.length - 1; i++) {             // str.length is # of words found
			//Build our element string.  This is cleaner using the DOM, but
			//  IE doesn't support dynamically added attributes.
			
			//We assign each newly created DIV mouse over, mouse out, and click events.  This is an over simplified version, and in a real implementation, we would probably have functions so we could use the arrow keys to select each entry.
			var suggest = '<div id="div' + searchType + i + '" onmouseover="javascript:suggestOver(this);" ';
			suggest += 'onmouseout="javascript:suggestOut(this);" ';
			suggest += 'onclick="javascript:setSearch(this.innerHTML);" ';
			suggest += 'title="' + str[i].substr(0,str[i].length-1) + '"';      //remove space at end of data
			suggest += 'class="suggest_link">' + str[i] + '</div>';
			ss.innerHTML += suggest;       
			
			//VERY USEFUL FOR DEBUGGING:
			//alert(ss.innerHTML);
			
            //Reset all up-arrow down-arrow variables !
			divPositionMax = i;     //We are grabbing the value last time thru the loop -- NEED
		}
		veryFirstDownArrow = true;
		divPosition = 0
	}
//Copy value into textbox 
//alert('ok');
divBox=searchType;  divPosition=1;
//eval( "document.getElementById('txt' + divBox).value = div" + divBox + divPosition + ".innerHTML;" );
//eval( "document.getElementById('txt' + divBox).value = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );
//eval( "document.getElementById('txt' + divBox).value = document.getElementById('div + divBox + divPosition').innerHTML;" );
//  eval( "document.getElementById('txt" + divBox + "').value = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );

//document.getElementById('testdiv').contentWindow.document.body.innerHTML
}


// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//mouse over function
function suggestOver(div_value) {
	div_value.className = 'suggest_link_over';
}

// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//mouse out function
function suggestOut(div_value) {
	div_value.className = 'suggest_link';
}


// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//mouse click function - sets the text of search textbox when a suggested item is clicked. 
function setSearch(value) {
    //document.getElementById('txtSearch').value = value;
    //alert('txt'+searchType);
	document.getElementById('txt'+searchType).value = value;
    //Once an Item is clicked, remove all of the suggested items, thus making the suggested DIV disappear.
	//document.getElementById('search_suggest_Cty').innerHTML = '';       // <---------------- 
	document.getElementById('search_suggest_'+searchType).style.visibility = 'hidden';  //  WORKS BETTER ! !
	//document.getElementById('search_suggest_Cty').style.background-color = 'red';     BREAKS EVERYTHING
}


// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
//function handleKeyDown(controlId) {
//function handleKeyDown(evt, controlId) {
function handleKeyDown(evt) {
    //PASSED IN VALUES FOR controlId:  txtGenus, txtSpecies, txtCN, or txtCty

    //document.getElementById('txtCty').value = 'in handleKeyDown()';
    //On a down-arrow or up-arrow, a letter or letters have been previously entered and handleSearchSuggest() 
    //has generated the div containers. Other keys are ignored.

    //Grab the keycode pressed
  //if (browserIsIE) { var evt=window.event;  keyCode = evt.keyCode }
	if (isIE6) { var evt=window.event;  keyCode = evt.keyCode }
	if (isIE7) { keyCode = evt.keyCode } 
	else { keyCode = evt.which } //FFox, Mozilla or Safari
	keyCharacter = String.fromCharCode(keyCode);

    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
        //alert('controlId='+controlId);
        //document.getElementById('txtCty').value = controlId;      SPECIES IS UNDEFINED FFox
    //  if (!controlId) { controlId='txtSpecies'; }                 FIXED NOW by passing evt param in CTdivsAndBoxes            
    //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 


	//Useful for debugging:
    //alert('keyCode='+keyCode + '\nCharacter was ' + keyCharacter);     
	
    if ( ((keyCode == 40) || (keyCode == 38)) && (controlId != prevControlId) ) {
    //For up or down arrow
    //Try intitalizing some vars here
		prevControlId = controlId;
        //veryFirstDownArrow = true

        //We only want  'Genus'  'Species'  'CN'  or  'Cty' :
        divBox = controlId.substring(3, controlId.length );

        //document.getElementById('txtCN').value = divBox;
        //alert('divBox='+divBox);
    }

	if (keyCode == 16) { 	 }  //exclude shift key   Do nothing  
    
	if (keyCode == 40) {   //down arrow
	    //alert('//down arrow   '+direction+divPosition+divPositionMax);
        if (veryFirstDownArrow) { divPosition -= 2 ; veryFirstDownArrow = false }
	         
        //See if we just reversed direction: up -> down
	    if ((divPosition < divPositionMax) && (direction == 'up'))   { backOne = divPosition; divPosition += 0;  direction = 'down'  }
        
        //See if we're going the same direction (down)
	    if ((divPosition < divPositionMax) && (direction == 'down')) { backOne = divPosition; divPosition += 1; }
	    
	    //Remove style from previous div (back one div up)
        if (divPosition > 0)  { eval( "document.getElementById('div" + divBox + backOne + "').className = 'suggest_link';" ) } //works FF

        //Now apply style to current div
 	    eval( "document.getElementById('div" + divBox + divPosition + "').className = 'suggest_link_over';" ) 

        // 	    eval( "'div" + divBox + divPosition + "'.className = 'suggest_link_over';" )        //works FF  not IE
        //        temp = document.getElementById('div' + divBox + backOne).className;               //works FF
        //        alert(temp);                                                                      //works FF

		//Fill text box with current div contents
        eval( "document.getElementById('txt" + divBox + "').value = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );
		
		//Fill title attribute with the same thing
        eval( "document.getElementById('txt" + divBox + "').title = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );
    }
   
    if (keyCode == 38) {   //up arrow

        //See if we just reversed direction: down -> up
	    if ((divPosition > 0) && (direction == 'down')) { backOne = divPosition; divPosition -= 0; direction = 'up' }
	    
        //See if we're going the same direction (up)
	    if ((divPosition > 0) && (direction == 'up'))   { backOne = divPosition; divPosition -= 1 }

	    //Remove style from previous div (back one div down)
        // if  (divPosition < divPositionMax) { eval( "div" + divBox + backOne + ".className = 'suggest_link';" );  };  NO!
        if  (divPosition < divPositionMax) { eval( "document.getElementById('div" + divBox + backOne + "').className = 'suggest_link';" ) } //works FF

        //Now apply style to current div
      //eval( "div" + divBox + divPosition + ".className = 'suggest_link_over';" ) 
 	    eval( "document.getElementById('div" + divBox + divPosition + "').className = 'suggest_link_over';" ) 

		//Fill text box with current div contents
        eval( "document.getElementById('txt" + divBox + "').value = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );
		
		//Fill title attribute with the same thing
        eval( "document.getElementById('txt" + divBox + "').title = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );
    }
    
    if (keyCode == 13) {   //Enter key
    
        //Copy value into textbox   XXXX   THIS NOT WORKING for FFox
      //if (browserIsIE) { 
        if (isIE6) { 
            eval( "document.getElementById('txt' + divBox).value = div" + divBox + divPosition + ".innerHTML;" );
        } else {                    //SO TRY THIS - XXXX  NOT WORKING EITHER
            //eval( "'txt" + divBox + "'.value = div" + divBox + divPosition + ".innerHTML;" );
            //eval( "'div" + divBox + divPosition + "'.className = 'suggest_link_over';" )
          //eval( "document.getElementById('txt' + divBox).value = div" + divBox + divPosition + ".innerHTML;" );
            eval( "document.getElementById('txt" + divBox + "').value = document.getElementById('div" + divBox + divPosition + "').innerHTML;" );
            //THIS ONE WQRKS ^
        }
        
        //Hide drop-down list
	    eval( "document.getElementById('search_suggest_' + divBox).style.visibility = 'hidden'; " );
	    
        if (searchType == 'Genus')  {
        //In this case we need the user to fill in the Species box 
            document.getElementById('txtSpecies').focus()  }
        //document.getElementById('txtCty').value = '';
        
        if (isSafari) { //key does = 13
        //www.arraystudio.com/as-workshop/disable-form-submit-on-enter-keypress.html
            //alert('isSafari');  works
            return false;   //DISABLES ENTER KEY EVENT SEQUENCE
            }  
        //else { return true; } 
                    
    } //if (keyCode == 13)   
} //handleKeyDown()
