// ==UserScript==
// @name           ArticleTitles
// @namespace      http://www.scottklement.com/scripts/articletitles
// @description    Add Article Titles to Newsletter Index
// @include        http://systeminetwork.com/archivesearch/issue/*
// @include        http://systeminetwork.com/sism
// @include        http://systeminetwork.com/sipt
// @include        http://systeminetwork.com/nd
// @include        http://systeminetwork.com/systeminews
// @include        http://systeminetwork.com/myi
// @include        http://systeminetwork.com/inwuk
// @include        http://systeminetwork.com/rpgcoder
// ==/UserScript==

GM_addStyle('.sckarticles { list-style-type: none; }');
GM_addStyle('.sckarticles li a{ color: #88801E; font-size: 90%; }');

var allLinks, thisLink;

   allLinks = document.evaluate(
       '//a[@href]',
       document,
       null,
       XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
       null);

   for (var i = 0; i < allLinks.snapshotLength; i++) {
       thisLink = allLinks.snapshotItem(i);
       if (thisLink.href.indexOf("/archivesearch/issue") != -1
           && thisLink.innerHTML.length>6 ) {
           var artTitles = GM_getValue(thisLink.href, "null");
           if (artTitles.length > 20) {
              setTitles(thisLink, artTitles);
           } else {
              get(thisLink.href, getTitles);
           }
       }
   }



function getTitles(xhr) {
   var text = xhr.responseText;
   var start = text.search("<ul class='resultissuearticles'>");
   var text2 = text.slice(start);
   var end   = text2.search("</ul>");
   var text3 = text2.slice(0, end+5);
   var text4 = text3.replace("resultissuearticles", "sckarticles");
   var allLinks, thisLink;

   allLinks = document.evaluate(
       '//a[@href]',
       document,
       null,
       XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE,
       null);

   for (var i = 0; i < allLinks.snapshotLength; i++) {
       thisLink = allLinks.snapshotItem(i);
       var testURL = xhr.finalUrl;
       if (testURL == thisLink.href) {
          GM_setValue(thisLink.href, text4);
          setTitles(thisLink, text4);
       }
   }
}

function setTitles(afterThis, titles) {
   var newdiv = document.createElement("div");
   newdiv.innerHTML = titles;
   afterThis.parentNode.appendChild(newdiv);
} 

function get(gurl, cb) {
  GM_xmlhttpRequest({
    method: "GET",
     url: gurl,
     onload: function(xhr) { cb(xhr); }
  });
}
