// attach the autocompleter, and default select the 'all' tab
function initSuperSearch(hash, search_message, default_tab) {
  var super_search_autocompleter = new Ajax.Autocompleter(
      'ac-input-'+hash, 
      'acc-header-'+hash, 'include/ajaxscripts/autocomplete/search.php', 
      { minChars:2, 
        paramName: 'q', 
        parameters: 'limit=15', 
        callback:createSuperSearchCallback(hash), 
        indicator:'super_search_indicator-'+hash }
    );
  clickSuperSearchTab(hash, default_tab ? default_tab : 'all', false);
}

function changeSuperSearchTab(hash, alias) { 
  // sometimes this function is called when not on homepage, oops
  if($(alias+'-'+hash)) {
    // unselect every tab
    var all_anchors = $$('#super_search_form-' + hash + ' ul.tabs li');
    for(var i = 0; i < all_anchors.length; i++) {
      all_anchors[i].removeClassName('active');
    }
    // select the one tab
    $(alias + '-' + hash).addClassName('active');
    
    if (alias == 'all') {
      alias = 'All Firefly';
    } else {
      alias = alias.capitalize();
    }
    
    var reg = new RegExp("Search .*(\\.)(\\.)(\\.)$");
    if(    reg.test(  $('ac-input-'+hash).value   )         ) {
      $('ac-input-'+hash).value = 'Search ' + alias + '...';
    }
    
  }
}

function clickSuperSearchTab(hash, alias, trigger_key_press) {
  var input = $('ac-input-'+  hash);
  changeSuperSearchTab(hash, alias);
  // if there is text in the search box when switching tabs, then do another request
  if(trigger_key_press && input.value.split('...').length < 2) { 
    fakeKeyPress('ac-input-'+hash); 
  }
  return false;
}

function createSuperSearchCallback(hash) {
  var callback = function(element, entry) {
    // find the selected tab
    var one_selected = $$('#super_search_form-'+hash+' ul.tabs li.active');
    // there can only be one selected element
    var strings = one_selected[0].readAttribute('id').split('-');
    var alias = strings[0];
    return entry+'&page_type='+alias;
  }
  return callback;
}


function fakeKeyPress(input_id) {
  var input = $(input_id);
  // the fake keypress needs to be done twice to work. weird, i know
  for(var i = 0; i < 2; i++ ) {
    if(input.fireEvent) {
      // ie stuff
      var evt = document.createEventObject();
      evt.keyCode = 67;
      $(input_id).fireEvent("onKeyDown", evt);
    } else {
      if (window.KeyEvent) { /* firefox */
        var evt = document.createEvent("KeyboardEvent");
        evt.initKeyEvent('keydown', true, true, null, false, false, false, false, 27, 0);
        var canceled = !$(input_id).dispatchEvent(evt);
      } else { /* safari  11202008, this doesnt work yet */
        var evObj = document.createEvent('UIEvents');
        evObj.initUIEvent('keydown', true, true, window, 1);
        $(input_id).dispatchEvent(evObj);
      }
    }
  }
}
