// Jeremy Nixon <jeremy@exit109.com>

// Cookie class - creates, deletes, loads cookies.

function Cookie(name) {
  this.$name = name;
  this.$expiration = new Date((new Date()).getTime()+31536000000);
  if (is_nav) this.$path = document.location.pathname;
}

function _Cookie_store() {
  var cookieval = "";
  for(var prop in this) {
    if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
      continue;
    if (cookieval != "") cookieval += '|';
    cookieval += escape(prop) + ':' + escape(this[prop]);
  }
  var cookie = this.$name + '=' + cookieval;
  cookie += '; expires=' + this.$expiration.toGMTString();
  if (is_nav) cookie += '; path=' + this.$path;
  document.cookie = cookie;
}

function _Cookie_load() {
  var allcookies = document.cookie;
  if (allcookies == "") return false;
  var start = allcookies.indexOf(this.$name + '=');
  if (start == -1) return false;
  start += this.$name.length + 1;
  var end = allcookies.indexOf(';', start);
  if (end == -1) end = allcookies.length;
  var cookieval = allcookies.substring(start,end);

  if (this.$name == "formsettings") {
    var a = cookieval.split('&');
  } else {
    var a = cookieval.split('|');
  }
  for(var i=0; i < a.length; i++)
    a[i] = a[i].split(':');
  for(var i=0; i < a.length; i++) {
    this[unescape(a[i][0])] = unescape(a[i][1]);
  }
  if (this.$name == "filter")
    filters._makelist(this);
  return true;
}

function _Cookie_remove() {
  var cookie;
  cookie = this.$name + '=';
  if (is_nav && this.$name != "formsettings") cookie += '; path=' + this.$path;
  cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';
  document.cookie = cookie;
}
new Cookie();
Cookie.prototype.store = _Cookie_store;
Cookie.prototype.load = _Cookie_load;
Cookie.prototype.remove = _Cookie_remove;

function create_prefs_cookie() {
  // create a Cookie, grab the appropriate form values, and set.
  var formprefs = new Cookie("formprefs");
  formprefs.defaultOp = document.ds.defaultOp.selectedIndex;
  formprefs.DBS = document.ds.DBS.selectedIndex;
  formprefs.OP = document.ds.OP.selectedIndex;
  formprefs.LNG = document.ds.LNG.selectedIndex;
  formprefs.svcclass = document.ds.svcclass.selectedIndex;
  formprefs.showsort = document.ds.showsort.selectedIndex;
  formprefs.maxhits = document.ds.maxhits.selectedIndex;
  formprefs.format = document.ds.format.selectedIndex;
  formprefs.store();
}

function remove_cookie(name) {
  var c = new Cookie(name);
  c.remove();
}

function remove_prefs_cookie() {
  remove_cookie("formprefs");
  reset_prefs();
}

function set_prefs() {
  if (formprefs.defaultOp) document.ds.defaultOp.selectedIndex = formprefs.defaultOp;
  if (formprefs.DBS) document.ds.DBS.selectedIndex = formprefs.DBS;
  if (formprefs.OP) document.ds.OP.selectedIndex = formprefs.OP;
  if (formprefs.LNG) document.ds.LNG.selectedIndex = formprefs.LNG;
  if (formprefs.svcclass) document.ds.svcclass.selectedIndex = formprefs.svcclass;
  if (formprefs.showsort) document.ds.showsort.selectedIndex = formprefs.showsort;
  if (formprefs.maxhits) document.ds.maxhits.selectedIndex = formprefs.maxhits;
  if (formprefs.format) document.ds.format.selectedIndex = formprefs.format;
}

function reset_prefs() {
    document.ds.defaultOp.selectedIndex = 0;
    document.ds.DBS.selectedIndex = 0;
    document.ds.OP.selectedIndex = 0;
    document.ds.LNG.selectedIndex = 0;
    document.ds.svcclass.selectedIndex = 0
    document.ds.showsort.selectedIndex = 0
    document.ds.maxhits.selectedIndex = 2;
    document.ds.format.selectedIndex = 1;
}

// FilterList class - stores the list of saved filters.

function FilterList() {
  this.$maxfilters = 7;
  this.$index = new Array();
}

function _List_makecookie() {
  // Make a cookie out of all the entries in the object.
  var pname;
  var flt = new Cookie("filter");
  // If there are no entries, delete the cookie.
  if (this.$index.length == 0) {
    flt.remove();
    return;
  }
  for (var f in this) {
    if ((f.charAt(0) == '$') || (typeof this[f] == 'function') || !f) continue;
    for (var prop in this[f]) {
      if ((typeof this[f][prop] == 'function') || (prop == 'name')) continue;
	pname = f + '~' + prop;
	flt[pname] = this[f][prop]
    }
  }
  flt.store();
}

function _List_makelist(ck) {
  // Populate the object with the entries from the passed cookie.
  var flt;
  for(var prop in ck) {
    if ((prop.charAt(0) == '$') || ((typeof ck[prop]) == 'function')) continue;
    var a = prop.split('~');
    if (!this[a[0]]) this[a[0]] = new SearchFilter(a[0]);
    this[a[0]][a[1]] = ck[prop];
  }
  this._names();
} 

function _List_add(name) {
  this[name] = new SearchFilter(name);
  this[name].grab();
  this._names();
  this._makecookie();
}

function _List_del(name) {
  this[name] = null;
  this._names();
  this._makecookie();
}

function _List_names() {
  // Make a list of filters in the object.
  var a = new Array();
  var i = 0;
  for (var f in this) {
    if ((f.charAt(0) == '$') || (typeof this[f] == 'function')) continue;
    a[i] = f;
    i++;
  }
  this.$index = a;
}

var filters = new FilterList();
FilterList.prototype._makecookie = _List_makecookie;
FilterList.prototype._makelist = _List_makelist;
FilterList.prototype._add = _List_add;
FilterList.prototype._del = _List_del;
FilterList.prototype._names = _List_names;

// SearchFilter class - a single saved search filter.

function SearchFilter(newname) {
  this.name = newname;
}

function _Filter_grab() {
  // Grab the form values.
  if (document.ds.subjects.value) this.subjects = document.ds.subjects.value;
  if (document.ds.groups.value) this.groups = document.ds.groups.value;
  if (document.ds.authors.value) this.authors = document.ds.authors.value;
  if (document.ds.fromdate.value) this.fromdate = document.ds.fromdate.value;
  if (document.ds.todate.value) this.todate = document.ds.todate.value;
}

function _Filter_setform() {
  // Take the values and set the form entries to them.
  if (this.subjects) document.ds.subjects.value = this.subjects
    else document.ds.subjects.value = '';
  if (this.groups) document.ds.groups.value = this.groups
    else document.ds.groups.value = '';
  if (this.authors) document.ds.authors.value = this.authors
    else document.ds.authors.value = '';
  if (this.fromdate) document.ds.fromdate.value = this.fromdate
    else document.ds.fromdate.value = '';
  if (this.todate) document.ds.todate.value = this.todate
    else document.ds.todate.value = '';
}
new SearchFilter();
SearchFilter.prototype.grab = _Filter_grab;
SearchFilter.prototype.setform = _Filter_setform;

function clear_filter_form() {
  document.ds.subjects.value = '';
  document.ds.groups.value = '';
  document.ds.authors.value = '';
  document.ds.fromdate.value = '';
  document.ds.todate.value = '';
  document.ds.subjects.focus();
}

function clear_query_form() {
  document.ds.QRY.value = '';
  document.ds.QRY.focus();
}

function save_filter() {
  if (filters.$index.length >= filters.$maxfilters) {
    alert("You can't have more than " + filters.$maxfilters + " filters.\n" +
          "You must delete one first.");
    return;
  }
  var name = window.prompt("Enter a name for the filter.", "");
  if (!name) return;

  if (name.indexOf("~") != -1) {
    alert("Sorry, you can't use a tilde in your filter name.\n" +
          "Please try again.");
    return;
  }
  if (name.charAt(0) == '$' || name.charAt(0) == '_') {
    alert("Sorry, you can't use a dollar-sign or underscore as the\n" +
          "first character in a filter name.  Please try again.");
    return;
  }
  if (typeof filters[name] != "undefined") {
    if (confirm("You already have a filter called " + name + ".\nOverwrite it?")) {
      filters[name] = null;
    } else {
      return;
    }
  }
  filters._add(name);
  document.location.reload();
  return;
}

function apply_filter(num) {
  if (typeof filters[filters.$index[num]] != "undefined")
    filters[filters.$index[num]].setform();
  document.ds.QRY.focus();
}

function delete_filter(num) {
  if (typeof filters[filters.$index[num]] != "undefined") {
    if (confirm("Really delete filter " + filters.$index[num] + "?")) {
      filters._del(filters.$index[num]);
    } else {
      return;
    }
  }
  document.location.reload();
}

function write_menu() {
  if (is_opera) {
    document.writeln("<p>&nbsp;</p>");
    return;
  }
  document.writeln("<p>&nbsp;<strong>Saved Search Filters</strong><br>");
  for(var i=0; i < filters.$index.length; i++) {
    document.writeln('&nbsp;&nbsp;&nbsp;<a href="javascript:delete_filter(' + i +
                     ')" title="Delete filter" class="del">'+
                     '<font color="#e40000"><strong>x</strong></font></a>');
    document.writeln('&nbsp;&nbsp;&nbsp;<a href="javascript:apply_filter('+ i +
                     ')" title="Apply filter" class="filter">'+
                     filters.$index[i] + '</a><br>');
  }
  document.writeln('</p><p>');
  document.writeln('&nbsp;<a href="javascript:save_filter()" '+
                   'title="Save Filter" class="filter">Save this filter</a>');
  document.writeln('&nbsp;&nbsp;&nbsp;<a href="javascript:void 0" '+
                   'onClick="clear_filter_form()" title="Clear Filter" class="filter">Clear form</a>');
  document.writeln('&nbsp;&nbsp;&nbsp;' +
                   '<a href="javascript:help_window(\'dejasfhelp.html\')" ' +
                   'title="Get Help" class="filter">Help</font></a>');
  document.writeln('</p>');
}

function settings_menu() {
  if (is_opera) {
    document.writeln("Javascript cookie features do not work in Opera.");
  } else {
    document.writeln("Save your settings:&nbsp;");
    document.writeln('<a href="javascript:create_prefs_cookie()">Save settings</a>');
    document.writeln("\n&nbsp;&nbsp;");
    document.writeln('<a href="javascript:remove_prefs_cookie()">Erase and reset</a>');
    document.writeln("\n&nbsp;&nbsp;");
    document.writeln('<a href="javascript:help_window(\'dejaprefhelp.html\')">Help</a>');
  }
}

function offer_help() {
  if (is_opera) {
    document.writeln('<a href="http://www.deja.com/help/help_lang.shtml">' +
                     'Deja\'s Search Language Help</a>');
  } else {

    document.writeln('<a href="javascript:help_window(\'dejahelpindex.html\')">Help</a>');
    document.writeln('&nbsp;&nbsp; Or ' +
                     '<a href="http://www.deja.com/help/help_lang.shtml">' +
                     'Deja\'s Search Language Help</a>');
  }
}

function query_clear_link() {
  document.writeln('&nbsp;&nbsp;<a href="javascript:clear_query_form()" '+
  'title="Clear Query">Clear</a> &nbsp;&nbsp; ');
}

function help_window(doc) {
  window.open(doc,"helpwin","scrollbars,height=370,width=420",false);
}

function read_cookies() {
  formprefs = new Cookie("formprefs");
  var formsettings = new Cookie("formsettings");
  formsettings.load();
  if (formsettings.defaultOp) {
    formprefs = formsettings;
    formsettings.remove();
    formprefs.$name = "formprefs";
    formprefs.store();
  } else {      
    formprefs.load();
  }
  var savedfilters = new Cookie("filter");
  savedfilters.load();
}

function startup_stuff() {
  if (!is_opera) set_prefs();
  document.ds.subjects.onfocus = new Function ("window.defaultStatus = 'Limit by subject.  Example: faq | (\"frequently asked questions\")'");
  document.ds.subjects.onblur = new Function ("window.defaultStatus = ''");
  document.ds.groups.onfocus = new Function ("window.defaultStatus = 'Limit by group.  Exmaple: alt.fan.*'");
  document.ds.groups.onblur = new Function ("window.defaultStatus = ''");
  document.ds.authors.onfocus = new Function ("window.defaultStatus = 'Limit by author.  Example: president@whitehouse.gov'");
  document.ds.authors.onblur = new Function ("window.defaultStatus = ''");
  document.ds.fromdate.onfocus = new Function ("window.defaultStatus = 'Starting date.  Example: Apr 1 1997'");
  document.ds.fromdate.onblur = new Function ("window.defaultStatus = ''");
  document.ds.todate.onfocus = new Function ("window.defaultStatus = 'Ending date.  Example: Jun 10 1999'");
  document.ds.todate.onblur = new Function ("window.defaultStatus = ''");
  document.ds.QRY.focus();
}

var agt = navigator.userAgent.toLowerCase(); 
var is_opera = (agt.indexOf("opera") != -1); 
var is_nav = ((agt.indexOf('mozilla') != -1) && (agt.indexOf('spoofer') == -1) 
 && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera') == -1) 
 && (agt.indexOf('webtv') == -1)); 

var formprefs; // Needs to be global.
if (!is_opera) read_cookies();
