// QUERY object library -------------------------------------------

// constructor ------------------------
function Query () {
  var qString = document.referrer.replace(/^[^\?]+\??/,'');// ||
//  	 document.search.replace(/^\?/,''); // what does this reference?

  qString = qString.replace(/#[^#]*$/, '');
  if ( qString ) {
     this.queryString = qString;
     this.params = this.parseQuery();
  }
}

// -----------------------------------
Query.prototype.parseQuery = function () {  
  var Params = new Object();
  if ( ! this.queryString ) return Params;
  var Pairs = this.queryString.split(/[&;]/);

  for ( var i = 0; i < Pairs.length; i++ ) {
    var KeyVal = Pairs[i].split('=');
    if ( ! KeyVal.length == 2 ) continue;
    if ( ! ( KeyVal[0] || KeyVal[1] ) ) continue;
    var key = unescape( KeyVal[0] );
    var val = unescape( KeyVal[1] );
    val = val.replace(/\+/g, ' ');
    Params[key] = val;
  }
  return Params;
}

// -----------------------------------
Query.prototype.chooseBest = function () {
  // build an associative array of terms to scores
  var scoredParams = this.scoredParams();

  var max = 0;
  var choice = '';
  for ( var qVal in scoredParams ) {
    if ( scoredParams[qVal] > max ) {
       choice = qVal;
       max = scoredParams[qVal];
     }
  }
  return choice;
}

// -----------------------------------
Query.prototype.scoredParams = function () {
  var params = this.params;

  var Scored = new Object(); // Scored["value"] = numeric_score_of_value

  for ( var key in params ) {
    var val = params[key];

    var weight = 0;

    // count things that look like words, min of 3 "letters"
    var wordlikes = val.match(/(\w[-'\w]+\w\s)|(\w[-'\w]+\w)$/gi);
    weight += wordlikes ? wordlikes.length : 0;

    // we know some keys are real indicators so we'll score on them too
    if ( key.match(/^(q|p)$/) ) weight += 2;
    if ( key.match(/query|search/i) ) weight++;

    // heavily discount that which we know to be wrong
    var badChars = val.match(/[^-a-zA-Z'" ]/g);
    weight -= badChars ? ( badChars.length * 2 ) : 0;

    // value probably shouldn't talk about searches or queries
    weight -= val.match(/query|search/i) ? 1 : 0;

    Scored[val] = weight;
  }
  return Scored;
}
