var tag_state = {};
var state_store;
var tag_add_msg = "Add to My References";
var tag_del_msg = "Remove from My References";

function tagToggle (tagged) {
  var flag = document.createElement ("img");
  if (tagged) {
    flag.setAttribute ("src", "/img/flagged.gif");
    flag.setAttribute ("alt", tag_del_msg);
    flag.setAttribute ("title", tag_del_msg);
  } else {
    flag.setAttribute ("src", "/img/unflagged.gif");
    flag.setAttribute ("alt", tag_add_msg);
    flag.setAttribute ("title", tag_add_msg);
  }
  return flag;
}

function tagMessage (tagged) {
  var message = document.createElement ("span");
  if (tagged) {
    message.appendChild (document.createTextNode (tag_del_msg))
  } else {
    message.appendChild (document.createTextNode (tag_add_msg))
  }
  return message;
}

function setTagToggleImg (element, tagged) {
  var children = element.childNodes;
  for (var i = 0; i < children.length; ++i) {
    var nodeName = children[i].nodeName.toUpperCase ();
    if (nodeName == "IMG") {
      element.replaceChild (tagToggle(tagged), children[i]);
    } else if (nodeName == "SPAN") {
      element.replaceChild (tagMessage (tagged), children[i]);
    }
  }
}

function makeRequest(element) {
  var url = element.href;
  var http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      http_request.overrideMimeType('text/xml');
    }
  } else if (window.ActiveXObject) { // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
	http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }

  if (!http_request) {
    // Unrecoverable error: cannot create an XMLHTTP instance.
    return false;
  }

  http_request.onreadystatechange = function() {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
	var tagged;
	var okay = false;
	var response = http_request.responseXML.documentElement;
	switch (response.nodeName) {
	case "tagged":
	  tagged = true;
	  okay = true;
	  break;
	case "untagged":
	  tagged = false;
	  okay = true;
	  break;
	case "nosession":
	  alert("You must be logged in to save records.");
	  break;
	default:
	  alert("Error tagging record. Unexpected response from the server.");
	}
	if (okay.valueOf ()) {
	  tag_state[element.parentNode.id] = tagged;
	  state_store.value = tag_state.toJSONString ();
	  setTagToggleImg (element, tagged);
          // Update the My References list.
          var ref_list = document.getElementById ("my-references-list");
	  if (ref_list) {
	    var li_id = response.getAttribute("id");
	    if (tagged) {
	      var title = response.childNodes[0].nodeValue;
	      var li = document.createElement ("li");
	      li.setAttribute ("id", li_id);
	      li.appendChild (document.createTextNode (title));
	      ref_list.insertBefore (li, ref_list.firstChild);
	    }
	    else { // untagged
	      var li = document.getElementById (li_id);
	      if (li) {
		ref_list.removeChild (li);
	      }
	    }
	  }
	}
      } else {
	alert('Error tagging record. No response from server.');
      }
    }
  };
  // Try to fool the IE page cache...
  url += "&random=";
  url += String(Math.random ());
  http_request.open('GET', url, true);
  http_request.setRequestHeader ("X-Method", "ajax");
  http_request.send(null);
}

function tagRecord(whichRec) {
  if (document.getElementById) {
    makeRequest(whichRec);
  }
  return false;
}

function restoreState () {
  for (var rid in tag_state) {
    var element = document.getElementById (rid);
    if (element) {
      var children = element.childNodes;
      for (var i = 0; i < children.length; ++i) {
	if (children[i].nodeName.toUpperCase () == "A") {
	  setTagToggleImg (children[i], tag_state[rid]);
	  break;
	}
      }
    }
  }
}

function checkState() {
  state_store = document.getElementById("state");
  if (state_store.value) {
    tag_state = state_store.value.parseJSON ();
    restoreState ();
  }
}

function truncate_title(title)
{
  if (title.length > 50) {
    return title.substring (0, 50)+"...";
  } else {
    return title;
  }
}

function display_feed(feed) {
  var feed_div_id;
  var link = document.createElement ("a");
  link.href = "/feed-reader"+feed["type"];
  if (feed["type"] == '/saved-searches/') {
    feed_div_id = "search-history";
    link.title = "View and edit your search history";
  } else {
    feed_div_id = "my-references";
    link.title = "View and edit your references";
  }
  var feed_div = document.getElementById (feed_div_id);
  if (feed_div) {
    var h2 = document.createElement ("h2");
    link.appendChild (document.createTextNode (feed["title"]));
    h2.appendChild (link);
    feed_div.appendChild (h2);
    var ul = document.createElement ("ul");
    if (feed["type"] == '/saved-searches/') {
      ul.id = "search-history-list";
    } else {
      ul.id = "my-references-list";
    }
    ul.setAttribute ("class", "feed-list");
    for (var i = 0; i < feed["items"].length; ++i) {
      var item = feed["items"][i];
      var li = document.createElement("li");
      if (item["href"]) {
	var link = document.createElement ("a");
	link.href = item["href"];
	link.title = "View search results";
	link.appendChild (document.createTextNode (truncate_title (item["title"])));
	li.appendChild (link);
      } else {
	li.appendChild (document.createTextNode (truncate_title (item["title"])));
      }
      if (item["hits"]) {
	li.appendChild (document.createTextNode (" : "+item["hits"]+" hits."));
      }
      if (item["date"]) {
	li.appendChild (document.createTextNode (" "+item["date"]+"."));
      }
      if (item["id"]) {
	li.id = item["id"];
      }
      if (i % 2 == 0) {
	li.setAttribute ("class", "highlight");
      }
      ul.appendChild (li);
    }
    feed_div.appendChild (ul);
  }
}

function load_feed(type, num_to_load) {
  var feed_script = document.getElementById(type+"-script");
  if (!feed_script) {
    var scriptElement = document.createElement("script");
    scriptElement.setAttribute("id", type+"-script");
    scriptElement.setAttribute("src",
			       "http://"+location.host+"/bin/feed-json/"+type+"/?callback=display_feed&show="+num_to_load);
    scriptElement.setAttribute("type", "text/javascript");
    document.documentElement.firstChild.appendChild(scriptElement);
  }
}

function load_feeds(num) {
  var num_to_load = 6;
  if (num) {
    num_to_load = num;
  }
  if (document.cookie.indexOf ('SID=!') == -1) {
    load_feed ("saved-searches", num_to_load);
    load_feed ("my-references", num_to_load);
  } else {
    div = document.getElementById ("search-history");
    if (div) {
      p = document.createElement ("p");
      p.appendChild (document.createTextNode ("You can keep a record of your searches and save references by logging into Copac."));
      div.appendChild (p);
    }
  }
}

// The following is taken from http://www.json.org/json.js

/*
    json.js
    2007-02-18

    Public Domain

    This file adds these methods to JavaScript:

        array.toJSONString()
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString()
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.
*/

if (!Object.prototype.toJSONString) {

  Array.prototype.toJSONString = function () {
    var a = ['['],  // The array holding the text fragments.
      b,          // A boolean indicating that a comma is required.
      i,          // Loop counter.
      l = this.length,
      v;          // The value to be stringified.

    function p(s) {
      // p accumulates text fragments in an array. It inserts a comma
      // before all except the first fragment.
      if (b) {
        a.push(',');
      }
      a.push(s);
      b = true;
    }

    // For each value in this array...
    for (i = 0; i < l; i += 1) {
      v = this[i];
      switch (typeof v) {

	// Values without a JSON representation are ignored.

      case 'undefined':
      case 'function':
      case 'unknown':
        break;

	// Serialize a JavaScript object value. Ignore objects thats lack the
	// toJSONString method. Due to a specification error in ECMAScript,
	// typeof null is 'object', so watch out for that case.

      case 'object':
        if (v) {
          if (typeof v.toJSONString === 'function') {
            p(v.toJSONString());
          }
        } else {
          p("null");
        }
        break;

	// Otherwise, serialize the value.

      default:
        p(v.toJSONString());
      }
    }

    // Join all of the fragments together and return.
    a.push(']');
    return a.join('');
  };

  Boolean.prototype.toJSONString = function () {
    return String(this);
  };

  Date.prototype.toJSONString = function () {
    // Ultimately, this method will be equivalent to the
    // date.toISOString method.

    function f(n) {
      // Format integers to have at least two digits.
      return n < 10 ? '0' + n : n;
    }

    return '"' + this.getFullYear() + '-' +
      f(this.getMonth() + 1) + '-' +
      f(this.getDate()) + 'T' +
      f(this.getHours()) + ':' +
      f(this.getMinutes()) + ':' +
      f(this.getSeconds()) + '"';
  };

  Number.prototype.toJSONString = function () {
    // JSON numbers must be finite. Encode non-finite numbers as null.
    return isFinite(this) ? String(this) : "null";
  };

  Object.prototype.toJSONString = function () {
    var a = ['{'],  // The array holding the text fragments.
      b,          // A boolean indicating that a comma is required.
      k,          // The current key.
      v;          // The current value.

    function p(s) {
      // p accumulates text fragment pairs in an array. It inserts a
      // comma before all except the first fragment pair.
      if (b) {
        a.push(',');
      }
      a.push(k.toJSONString(), ':', s);
      b = true;
    }

    // Iterate through all of the keys in the object, ignoring the proto chain.
    for (k in this) {
      if (this.hasOwnProperty(k)) {
        v = this[k];
        switch (typeof v) {

	  // Values without a JSON representation are ignored.

        case 'undefined':
        case 'function':
        case 'unknown':
          break;

	  // Serialize a JavaScript object value. Ignore objects that lack the
	  // toJSONString method. Due to a specification error in ECMAScript,
	  // typeof null is 'object', so watch out for that case.

        case 'object':
          if (v) {
            if (typeof v.toJSONString === 'function') {
              p(v.toJSONString());
            }
          } else {
            p("null");
          }
          break;
        default:
          p(v.toJSONString());
        }
      }
    }

    // Join all of the fragments together and return.

    a.push('}');
    return a.join('');
  };

  (function (s) {

    // Augment String.prototype. We do this in an immediate anonymous
    // function to avoid defining global variables.
    // m is a table of character substitutions.
    var m = {
      '\b': '\\b',
      '\t': '\\t',
      '\n': '\\n',
      '\f': '\\f',
      '\r': '\\r',
      '"' : '\\"',
      '\\': '\\\\'
    };

    s.parseJSON = function (filter) {
      // Parsing happens in three stages. In the first stage, we run
      // the text against a regular expression which looks for
      // non-JSON characters. We are especially concerned with '()'
      // and 'new' because they can cause invocation, and '=' because
      // it can cause mutation. But just to be safe, we will reject
      // all unexpected characters.
      try {
        if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
                        test(this))  // "
	{
	  // In the second stage we use the eval function to compile
	  // the text into a JavaScript structure. The '{' operator is
	  // subject to a syntactic ambiguity in JavaScript: it can
	  // begin a block or an object literal. We wrap the text in
	  // parens to eliminate the ambiguity.

          var j = eval('(' + this + ')');

	  // In the optional third stage, we recursively walk the new
	  // structure, passing each name/value pair to a filter
	  // function for possible transformation.

          if (typeof filter === 'function') {
	    
            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }
	    
            walk('', j);
          }
          return j;
        }
      } catch (e) {
	
	// Fall through if the regexp test fails.

      }
      throw new SyntaxError("parseJSON");
    };

    s.toJSONString = function () {
      // If the string contains no control characters, no quote
      // characters, and no backslash characters, then we can simply
      // slap some quotes around it.  Otherwise we must also replace
      // the offending characters with safe sequences.

      if (/["\\\x00-\x1f]/.test(this)) { // "]/) {
	return '"' + this.replace(/([\x00-\x1f\\"])/g, function(a, b) {//"])/){
          var c = m[b];
          if (c) {
            return c;
          }
          c = b.charCodeAt();
          return '\\u00' +
            Math.floor(c / 16).toString(16) +
            (c % 16).toString(16);
        }) + '"';
      }
      return '"' + this + '"';
    };
  })(String.prototype);
}
