// Autocomp.js
var bProcessingAutoComp = false;

function doAutoComp(e,obj,loc,action) {
  try {
    e = e || window.keyup;
    var code = e.keyCode || e.which;
    var form = obj.form;
    
    var sLastVal= obj.value;
    
    if ( code == 40) { // check to see if the down error is pressed
      if (document.getElementById('autocomplete') != null) {
        document.getElementById('autocomplete').focus();
        return;
      }
    }
    
    if ( code == 13 ) {
      //enter key, handle later todo
      //would submit normal search query
      //location.href = ... or something similar
    } else if ( code == 27 ) {
      //esc key.  do nothing
      //alert('esc key, do nothing');
      return;
    } else {
      if ( sLastVal.length > 1 ) {
        setTimeout(function(){
          var newobj = obj;
          var path = setNewPath(loc,action,form);
          
          var curVal = obj.value;
          
          if (curVal == sLastVal) doAjaxCall(path,newobj);
        }, 250);  //wait for user to pause/stop typing before submitting
      }
    } //end if-elses
  } catch(error) {
  }
} //end doAutoComp

function doAjaxCall(path,obj) {  
  if (!bProcessingAutoComp) {
    bProcessingAutoComp = true;
    dojo.xhrGet( {
      url: path,
      handleAs: 'text',
      timeout: 10000,
      load: function(response, ioArgs) {
        if (rmWhiteSpace(response).length > 0) {	
          Popup.AutoComplete('autocomplete',obj.id,response,true);
        }
        bProcessingAutoComp = false;
        return response;
      },
      error: function(response, ioArgs) {
        console.error("HTTP status code", ioArgs.xhr.status);
        bProcessingAutoComp = false;
        return response;
      }
    } );
  }
}

function rmWhiteSpace(str) {
    spaceFree = str.replace(/\s+/g,'');
 
    return spaceFree;   
}

function setNewPath(location, action, form) {
  var action = "action=" + action;
  var path = SITE_ROOT + location + "?" + action;
  
  for(var i=0; i<form.length; i++) {
    if ((form[i].name != 'action') && ((form[i].name != '') && (form[i].value != ''))) {
      if ((form[i].type == 'text') || (form[i].type == 'hidden')) {
        path += "&" + form[i].name + "=" + form[i].value;
      } else {
        if (form[i].checked) path += "&" + form[i].name + "=" + form[i].value;
      }
    }
  }
  
  return path;
}