// JavaScript Document
/*
~ need to perform check to see if there are any links to list	
*/

function footnoteLinks(containerID, targetID) {
	if (!document.getElementById ||
      !document.getElementsByTagName ||
      !document.createElement) return false;
  	
	if (!document.getElementById(containerID) ||
      !document.getElementById(targetID)) return false;
  
 // get the container and target
	var container = document.getElementById(containerID);
	var target = document.getElementById(targetID);

// create a heading for the footnotes
	var h2 = document.createElement('h2');
	addClass.apply(h2,['printOnly']);
	var h2_txt = document.createTextNode('Links');
	h2.appendChild(h2_txt);
	
 // create an <ol> to contain the footnotes
	var ol = document.createElement('ol');
	addClass.apply(ol,['printOnly']);
	
 // create an array to store used links so we can check 
 // for duplicates
	var myArr = []; // to store all the links
	var thisLink;   // to store each link individually
	
 // create a variable to keep track of the number used for each   
 // link, so we have it for footnote references
	var num = 1;

// collect all of the elements in the specified container  
 // into an array
	var coll = container.getElementsByTagName('*');
	
 // cycle through the elements in that array, looking for hrefs 
 // and citations
 for (var i=0; i<coll.length; i++) {
	 var thisClass = coll[i].className;
	 
  // check for our attributes
 	 if ((coll[i].getAttribute('href')||
       coll[i].getAttribute('cite')) &&
          (thisClass == '' ||
           thisClass.indexOf('ignore') == -1) ) {
    // grab the reference
    thisLink = coll[i].getAttribute('href') ? coll[i].href 
                                            : coll[i].cite;
											
	// build the <sup> and append after the reference
    var note = document.createElement('sup');
    addClass.apply(note,['printOnly']);
	var note_txt;
	var j = inArray.apply(myArr,[thisLink]);
    if ( j || j===0 ) { 
	// if a duplicate
      // get the corresponding number from the array of 
      // used links
      note_txt = document.createTextNode(j+1);
    } else { 
	// if not a duplicate
	// build the <li> and append to the <ol>
    var li = document.createElement('li');
    var li_txt = document.createTextNode(thisLink);
    li.appendChild(li_txt);
    ol.appendChild(li);
    // store the link in the array
    myArr.push(thisLink);
	note_txt = document.createTextNode(num);
	// increment the number variable
    num++;
  }
	note.appendChild(note_txt);
		if (coll[i].tagName.toLowerCase() == 'blockquote') {
   			var lastChild = lastChildContainingText.apply(coll[i]);
		    lastChild.appendChild(note);
		  } else {
			coll[i].parentNode.insertBefore(note, coll[i].nextSibling);
  		}
    }
  }
  	target.appendChild(h2);
  	target.appendChild(ol);
	addClass.apply(document.getElementsByTagName('html')[0],['noted']);
	
  return true;
}