/**
* (Grant) 617-233-1132
* Friday 7pm - Milrose Games - espn2 HD
 *  The ServerSuggestion class encapsulates the Ajax functionality needed for us to implement an
 *  Auto-Suggest box. In conjunction with the autogsuggestion.js file, this file provides an implementation for doing so.
 *  In this implementation a hidden txt box may be used to assist in passing back results to the server once the form is
 *  submitted.
 *
 *  Usage:
 * window.onLoad= function() {
 *  var oTextbox = new AutoSuggestControl(document.getElementById("txt0"), new ServerSuggestions("hiddenBox"));
 *  // where "txt0" is the textbox that is the main actor of the auto-suggest
 *  // and "hiddenBox" is where the server response, mapping display text to ids, is stored
 * }
 *
 * To be place in a form somwehere: <input type="text" id="contacts" name="contacts" size="500" value=""/><br>
 *  <input type="hidden" id="txt1" name="txt1" size="100" value="" />
 *
 * If it is desirable that the form is not submitted on keypress, then set the input boxes onkeypress method to call "return blockSubmit(textbox, event)"
 *
 * ENHANCEMENTS that need to be made:
 * 1. If a given contact is already in the input box, don't show it anymore in the autosuggest popup box
 * 2. How do we prevent a user from entering contacts, without putting a space
 *      - maybe we should give an option to disgard a contact on the c.jsp page in case they made an error
 */

var xmlhttp = null;         // the XMLHttpRequest object
var response = []; // the Response text from the server

/**
 * Provides suggestions for state names (USA).
 * @class
 * @scope public
 */
function ServerSuggestions() {
}

/**
 * Request suggestions for the given autosuggest control. 
 * @scope protected
 * @param oAutoSuggestControl The autosuggest control to provide suggestions for.
 */
ServerSuggestions.prototype.requestSuggestions = function (oAutoSuggestControl /*:AutoSuggestControl*/) {
    var sTextboxValue = oAutoSuggestControl.textbox.value;
   /* if(sTextboxValue.lastIndexOf(" ") == sTextboxValue.length - 1
            && sTextboxValue.length > 1){ //spacebar was pressed, setup for the next entry, otherwise the autosuggester will thing the value is one string and will not auto-suggest
        oAutoSuggestControl.textbox.value = sTextboxValue + "; ";
        return;
    }*/
    // get the value after the last semicolon.
    while (sTextboxValue.indexOf("; ")>0) {
        sTextboxValue = sTextboxValue.substr(sTextboxValue.indexOf("; ")+2);
    }
    if (!sTextboxValue.length > 0) //populate the array first
        return;
    this.fetchSuggestionsFromServer("/SC?q=", sTextboxValue, oAutoSuggestControl);
};

/**
 *
 * @param url           - the link to which the XMLHttp object should send a GET request
 * @param sTextboxValue - the value to be queried upon by the server
 */
ServerSuggestions.prototype.fetchSuggestionsFromServer = function (url, sTextboxValue, oAutoSuggestControl ){
  if(window.XMLHttpRequest){    //Netscape/Firefox/Opera
      xmlhttp   = new XMLHttpRequest();
  }else if(window.ActiveXObject){
      xmlhttp   = new ActiveXObject("Microsoft.XMLHTTP"); //IE
  }
  url= url + sTextboxValue;
  if(xmlhttp != null){
//      xmlhttp.onreadystatechange = state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200)
            {
                response = xmlhttp.responseText.split(",");
                this.aSuggestions = parseResults();
                //provide suggestions to the control
                oAutoSuggestControl.autosuggest(this.aSuggestions);  //
            }else{
                alert("Problem retrieving XML data");
            }
        }
      }
      xmlhttp.send(null);
  }else{
      alert("Your browser does not support XMLHTTP.");
  }
}

/**
 * parses out the response string and compare the displayText with the desc text returned from the server
 * @requires this.suggestions is delimited by "|"
 * @param sTextboxValue
 * @param aSuggestions
 */
function parseResults(){
    if(this.txtHidden == null){
        this.txtHidden = document.getElementById("c2");
    }

    this.aSuggestions = []; // initialize this
    for (var i=0; i < this.response.length; i++) {
//        alert(i + ". response = " + this.response[i]);
        var entry       = this.response[i].split("|");
//        alert(i + ". entry = " + entry[0]);
        this.aSuggestions.push(entry[0]);
//        alert("Pushing into asuggestions = " + this.aSuggestions[i]);
        this.txtHidden.value = this.txtHidden.value + this.response[i] + ",";
//        alert("txt hidden = " + this.txtHidden.value);
//         PUT THIS INSIDE OF YOUR SERVLET FOR EVENTS!
        // if (entry[0].toLowerCase().indexOf(sTextboxValue.toLowerCase().replace("\n","")) >= 0) {
//            aSuggestions.push(entry[0]);
//            this.txtHidden.value = this.txtHidden.value + this.suggestions[i] + ",";
//        }
    }
    return this.aSuggestions;
 }

/**
 * Disables a text field from submitting the form (in which it's contained) upon pressing the enter key.
 * @param field
 * @param e
 * Usage: set the onKeypress method of the textField to call blockSubmit(this, event);
 */
function blockSubmit(field, e){
    var keynum;
    var keychar;
    if(window.event) //IE
        keynum = e.keyCode;
    else if(e.which) //Netscapre/Firefox/Opera
        keynum = e.which;
    keychar = String.fromCharCode(keynum);
    if(keynum == 13){
        //prevent form submission
        return false;
     }
    else
        return true;
}