/* Dynamically adds urchin tracker links to documents on the page */
/*

Copyright © Josh Comgle 2017

This code will add the necessary functionality to add document tracking
for Google Analytics to your page(s).

Setup:

1)	Modify ***1***, adding any document types required to the collection.
	i)	When adding a new document type, you must add both
		a) docTypes[x][0]	= '.txt';
		b) docTypes[x][1]	= 'text';

		Where '.txt', put whatever document type you want
		Where 'text', put what directory prefix you want Google Analytics
		to store this document type as. For example, with the above settings
		the file "mytextfile.txt" would be logged as "/text/mytextfile.txt"
		in Google Analytics
	ii)	Don't forget to update the "count" variable, which indicates how
		many document types are listed
2)	Add a reference to this code in your page
3)	Add a call to addUrchin() AFTER the page contents
4)	To test, remove the comments for the line headed ***2***, which adds an
	alert message with the line used for the urchinTracker

*/
function getFileName(prefix,str){
	if(endsWith(str,'/'))
		str = str.substr(0,str.length-1);
	if(str.indexOf('/')==-1)
		str = '/' + str;
	if(endsWith(prefix,"/"))
		prefix = prefix.substr(0,prefix.length-1);
	var index = str.lastIndexOf('/');
	return prefix + str.substr(index);
}
function endsWith(s, endsWith){
    if ('string' != typeof endsWith)
        throw('IllegalArgumentException: Must pass a ' +
            ' string to String.prototype.endsWith()');

    var start = s.length - endsWith.length;
    return s.substring(start) == endsWith;
}

var hshTable = new Hashtable();

// ***1***
var count = 6;
var docTypes = new Array(count);
for (i=0; i <count; i++)
	docTypes[i]=new Array(1)

// PDF
docTypes[0][0]	= '.pdf';
docTypes[0][1]	= 'docs'
// DOC	
docTypes[1][0]	= '.doc';
docTypes[1][1]	= 'docs';
// EXE
docTypes[2][0]	= '.exe';
docTypes[2][1]	= 'apps';
// ZIP
docTypes[3][0]	= '.zip';
docTypes[3][1]	= 'apps';
// XLS
docTypes[4][0]	= '.xls';
docTypes[4][1]	= 'excel';

docTypes[5][0]	= '.csv';
docTypes[5][1]	= 'excel';

function addUrchin(){
	var aTags = document.getElementsByTagName('a');
	
	for(var i=0;i<aTags.length;i++){
		for(var j=0;j<docTypes.length;j++){
			if(endsWith(aTags[i].href,docTypes[j][0])){
				// Add the prefix for this a tag to the hash table
				hshTable.put(aTags[i].href,docTypes[j][1]);
				addEventDirect(aTags[i], 'click', function(){ urchinTracker(getFileName("/"+hshTable.get(this.href)+"/",this.href)); })

				// ***2***
				// Remove the comments on this line to test the script
				//addEventDirect(aTags[i], 'click', function(){ urchinTracker(getFileName("/"+hshTable.get(this.href)+"/",this.href));alert(getFileName("/"+hshTable.get(this.href)+"/",this.href)); })
				break;
			}
		}
	}
}

function addEvent(objID, type, fn){ 
	addEvent(document.getElementById(objID),type,fn);
}

function addEventDirect(obj, type, fn){ 
	if (obj.attachEvent){ 
		obj['e'+type+fn] = fn; 
		obj[type+fn] = function(){obj['e'+type+fn]( window.event );} 
		obj.attachEvent( 'on'+type, obj[type+fn] ); 
	}
	else{
		obj.addEventListener( type, fn, false ); 
	}
}


/**
    Created by: Michael Synovic
    on: 01/12/2003
    
    This is a Javascript implementation of the Java Hashtable object.
    
    Contructor(s):
     Hashtable()
              Creates a new, empty hashtable
    
    Method(s):
     void clear() 
              Clears this hashtable so that it contains no keys. 
     boolean containsKey(String key) 
              Tests if the specified object is a key in this hashtable. 
     boolean containsValue(Object value) 
              Returns true if this Hashtable maps one or more keys to this value. 
     Object get(String key) 
              Returns the value to which the specified key is mapped in this hashtable. 
     boolean isEmpty() 
              Tests if this hashtable maps no keys to values. 
     Array keys() 
              Returns an array of the keys in this hashtable. 
     void put(String key, Object value) 
              Maps the specified key to the specified value in this hashtable. A NullPointerException is thrown is the key or value is null.
     Object remove(String key) 
              Removes the key (and its corresponding value) from this hashtable. Returns the value of the key that was removed
     int size() 
              Returns the number of keys in this hashtable. 
     String toString() 
              Returns a string representation of this Hashtable object in the form of a set of entries, enclosed in braces and separated by the ASCII characters ", " (comma and space). 
     Array values() 
              Returns a array view of the values contained in this Hashtable. 
            
*/
function Hashtable(){
    this.clear = hashtable_clear;
    this.containsKey = hashtable_containsKey;
    this.containsValue = hashtable_containsValue;
    this.get = hashtable_get;
    this.isEmpty = hashtable_isEmpty;
    this.keys = hashtable_keys;
    this.put = hashtable_put;
    this.remove = hashtable_remove;
    this.size = hashtable_size;
    this.toString = hashtable_toString;
    this.values = hashtable_values;
    this.hashtable = new Array();
}

/*=======Private methods for internal use only========*/

function hashtable_clear(){
    this.hashtable = new Array();
}

function hashtable_containsKey(key){
    var exists = false;
    for (var i in this.hashtable) {
        if (i == key && this.hashtable[i] != null) {
            exists = true;
            break;
        }
    }
    return exists;
}

function hashtable_containsValue(value){
    var contains = false;
    if (value != null) {
        for (var i in this.hashtable) {
            if (this.hashtable[i] == value) {
                contains = true;
                break;
            }
        }
    }
    return contains;
}

function hashtable_get(key){
    return this.hashtable[key];
}

function hashtable_isEmpty(){
    return (parseInt(this.size()) == 0) ? true : false;
}

function hashtable_keys(){
    var keys = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null) 
            keys.push(i);
    }
    return keys;
}

function hashtable_put(key, value){
    if (key == null || value == null) {
        throw "NullPointerException {" + key + "},{" + value + "}";
    }else{
        this.hashtable[key] = value;
    }
}

function hashtable_remove(key){
    var rtn = this.hashtable[key];
    this.hashtable[key] = null;
    return rtn;
}

function hashtable_size(){
    var size = 0;
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null) 
            size ++;
    }
    return size;
}

function hashtable_toString(){
    var result = "";
    for (var i in this.hashtable)
    {      
        if (this.hashtable[i] != null) 
            result += "{" + i + "},{" + this.hashtable[i] + "}\n";   
    }
    return result;
}

function hashtable_values(){
    var values = new Array();
    for (var i in this.hashtable) {
        if (this.hashtable[i] != null) 
            values.push(this.hashtable[i]);
    }
    return values;
}

