// Add domains to exclude here
var excludeList = new Array();

var domain = new RegExp("/"+location.hostname+"/","");
var mail   = new RegExp("mailto:");
var domainRef = location.hostname + location.pathname;

var track_mailto = true;
var track_files = true;
var track_ext_domains = true;


var attemptCount = 0;

var log = false;

if (typeof jQuery == 'undefined') {
    var script = document.createElement('script');
    script.type = "text/javascript";
    script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js";
    document.getElementsByTagName('head')[0].appendChild(script);
}

function init() {
    // quit if this function has already been called
    if (arguments.callee.done) return;

    // create the "JQuery loaded" message
    var text;
    var countText;
    if (typeof jQuery != 'undefined') {
        // flag this function so we don't do the same thing twice
        arguments.callee.done = true;

        
    } 
    jQuery(function() {
    	trackLinks();
    });
    
}

function waitForJQuery() {
    attemptCount++;
    if (typeof jQuery != 'undefined') { // JQuery is loaded!
        init();
        return;
    }
    if (attemptCount < 100) {
        setTimeout(waitForJQuery, 100); // Check 10x a second
    }
    return;
}

// What to do for Chrome?

// Mozilla, Opera and webkit nightlies currently support this event
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, false);
// If IE event model is used
} else if (document.attachEvent) {
    waitForJQuery();
}

// setTimeout hack also Works for Chrome - but seems less than elegant
//waitForJQuery();

// for other browsers
window.onload = init;

function trackLinks(){
 links = document.getElementsByTagName("a");
    linkList = Array();
    for (var i = 0; i < links.length; i++){
        linkList.push(links[i]);
   }
    addFormSubmits(linkList);
    for (var i = 0; i < linkList.length; i++){
     exclude = false;
       for(var j = 0; j < excludeList.length; j++){
           tmp = linkList[i] + "";
            if (tmp.match(new RegExp("/"+excludeList[j]+"/","i"))) {
               exclude = true;
            }
      }
        if(!exclude){
          linkList[i].onclick = function(){
              link = this + "";
              if(this.tagName != 'A') link = this.getAttribute('href');

             // Finds the filename (or folder)
              filename = link.split("/").pop().split("?").shift();
                // Check that the link is infact pointing to a file, and not a subfolder
	       if(link.toLowerCase().match(mail) && track_mailto){
                   // Track mailto link
                    if(log) console.log("email: " + link);
					_gaq.push(['_trackEvent', 'email', link, domainRef]);
              }
               else if(filename.indexOf(".") != -1){
                   // Matches .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf etc
                 matches = Array("doc","docx","xls","xlsx","ppt","pptx","pdf","jpg","gif","tiff","png");
                    ext = filename.split(".").pop().toLowerCase();
                 if(matches.contains(ext) && track_files){
                     // Track file
                      file = 'file-'+ext;
                      _gaq.push(['_trackEvent', file, filename, domainRef]);
                      if(log) console.log("file: " + file);
                 }
              }
                else if(!link.match(domain) && track_ext_domains){
        	          // External, or a subdomain
					_gaq.push(['_trackEvent', 'ext', link, domainRef]);
					if(log) console.log("External: " + link);
              }
          }
      }
  }
}
/*
 * Special case not found: When a link is outside the form element, or the type="submit" attribute is missing
 */
function addFormSubmits(linkList){
 forms = document.getElementsByTagName("form");
 for (var i = 0; i < forms.length; i++){
        // Find the submit element; whatever type of element it is
     children = forms[i].childNodes;
        for(var j = 0; j < children.length; j++){
          if(children[j].attributes != null && children[j].getAttribute('type')){
                if(children[j].getAttribute('type') == 'submit'){
                  // Add this node to the linkList, with the form action attribute as a href
                 node = children[j];
                    node.setAttribute('href',forms[i].getAttribute('action'));
                     linkList.push(node);
                   }
              }
          }
      }
  }
    Array.prototype.contains = function(obj) {
     var i = this.length;
       while (i--) {
          if (this[i] === obj) {
             return true;
           }
      }
      return false;
  }
