/*********************************************************/
/*                                                       */
/* Put together the right tracking code for each domain. */
/*                                                       */
/*********************************************************/

var _this = this;
var _gaq = _gaq || [];

// List of Google Analytics Profiles
/* NOTE: This is hard-coded for now. At some point we might want to grab it from
a dynamically generated profiles.json. */
var profiles = {
	"www.naz.edu"               : "UA-4159588-1",
	"visit.naz.edu"             : "UA-4159588-2",
	"admissions.naz.edu"        : "UA-4159588-5",
	"naz.typepad.com/darin"     : "UA-4159588-8",
	"blogs.naz.edu/darin"       : "UA-4159588-8",
	"naz.typepad.com/braveman"  : "UA-4159588-9",
	"blogs.naz.edu/braveman"    : "UA-4159588-9",
	"nazareth2014.ning.com"     : "UA-4159588-10",
	"interfaith2010.naz.edu"    : "UA-4159588-13",
	"alumni.naz.edu"            : "UA-4159588-14",
	"grad.naz.edu"              : "UA-4159588-15",
	"radio.naz.edu"             : "UA-4159588-16",
	"athletics.naz.edu"         : "UA-4159588-17",
	"www.naz.edu/ewing"         : "UA-4159588-18",
	"forcollegeandcommunity.org": "UA-4159588-20",
	"artscenter.naz.edu"        : "UA-4159588-22",
	"forms.naz.edu"             : "UA-4159588-23",
	"directories.naz.edu"       : "UA-4159588-24",
	"m.naz.edu"                 : "UA-4159588-25"
};
// "naz.edu" : "UA-4159588-19", This is the generic profile. DO NOT PUT IT IN THE PROFILES DICT

/** UTILITY FUNCTIONS **/
function getLinkLocation(href) {
	// split up a URL into component parts similar
	// to a window.location object.
	// [protocol]:(//)?[hostname](:[port])?([pathname])?([hash])?([search])?
	// host = hostname + ":" + port
	// Finally, rebuild the href so it looks like the sum of those parts.
	// (Some user agents do this for us, others don't.)
	var protos = {"http:":80,"https:":443}; // don't worry about protos that can't use Javascript
	var rest = href;
	var search = "";   if (rest.indexOf("?") >= 0) { search   = "?" + rest.split("?").slice(1).join("?"); rest = rest.split("?")[0]; }
	var hash = "";     if (rest.indexOf("#") >= 0) { hash     = "#" + rest.split("#").slice(1).join("#"); rest = rest.split("#")[0]; }
	var protocol = ""; if (rest.indexOf(":") >= 0) { protocol = rest.split(":")[0] + ":"; rest = rest.split(":").slice(1).join(":"); }
	var host = "";
	var hostname = "";
	var port = "";
	var pathname = "";
	// If the protocol contains anything besides
	// ASCII alphabetical characters [a-z]
	// it's not really a protocol, and the link
	// is relative. Rebuild the URL for consistency.
	if (!/^[a-z]+:$/.test(protocol)) {
		protocol = window.location.protocol; // already has the ":"
		hostname = window.location.hostname;
		port = window.location.port;
		if (rest.charAt(0) == "/") {
			// if (console && console.log) console.log("Site-relative URL: '%s'", href);
			pathname = rest;
		} else if (rest.charAt(0) in {"#":1,"?":1} || window.location.pathname.charAt(window.location.pathname.length - 1) == "/") {
			// if (console && console.log) console.log("Path-relative URL: '%s'", href);
			pathname = window.location.pathname + rest;
		} else {
			// if (console && console.log) console.log("Path-relative URL: '%s'", href);
			pathname = window.location.pathname.split("/").slice(0, window.location.pathname.split("/").length - 1).join("/") + "/" + rest;
		}
		port = port || (protocol in protos && protos[protocol]);
		host = hostname + ":" + port;
		href = protocol + "//" + host + pathname + hash + search;
	} else if (rest.indexOf("//") == 0) {
		// URL is absolute
		host = rest.split("/")[2];
		pathname = "/" + rest.split("/").slice(3).join("/");
		hostname = host.split(":")[0];
		port = host.split(":")[1];
		port = port || (protocol in protos && protos[protocol]);
	} /* else {
		 URL is probably something like mailto:foo or javascript:foo
		 Return what little we know.
	} */
	v = {
		"protocol": protocol,
		"search":   search,
		"hash":     hash,
		"host":     host,
		"hostname": hostname,
		"port":     port,
		"pathname": pathname,
		"href":     href
	};
	// if (console && console.log) console.log(v);
	return v;
}
function getGAProfile(href) {
	// Takes an href string or location object and returns the
	// first profile string that matches.
	// if (console && console.log) console.log("Getting profile for location %s", href)
	if (typeof href == "string") href = getLinkLocation(href);
	// HACK: Loop because some profile keys contain path parts,
	//       so they're not just hostnames.
	for (profile in profiles) {
		if (profile == "naz.edu") continue;
		if ((href.hostname + href.pathname).indexOf(profile) >= 0) {
			// console.log("profile %s matched against address %s", profile, href.hostname + href.pathname);
			return profile;
		}
	}
	return "";
}
function trackFuturePageview() {
	var loc = getLinkLocation(this.href);
	var profile = getGAProfile(loc);
	var default_tracker = _gat._getTracker(profiles[profile]);
	var overall_tracker = _gat._getTrackerByName("overall");
	// if (console && console.log) console.log("Tracking page view for '%s' with profile '%s'", loc.pathname, profile);
	default_tracker._trackPageview(loc.pathname);
	overall_tracker._trackPageview(loc.pathname);
}
function trackError(err) {
	// Track a specific http status code by adding it to the end of the URL as hash
	var loc = getLinkLocation(window.location.href);
	var profile = getGAProfile(loc);
	var _gaq = _gaq || [];
	var err_path = '/error/' + err + loc.pathname;
	// if (console && console.log) console.log("Tracking error page view for '%s' with profile '%s'", loc.pathname + "#" + err, profile);
	_gaq.push(
		['overall._trackPageview', err_path],
		[        '_trackPageview', err_path]
	);
}

function trackNotHTML() {
	// Add tracking to hyperlinks to pages that can't use Javascript,
	// such as PDFs.
	var anchors = document.getElementsByTagName('a');
	// if (console && console.log) console.log("anchors found: %d", anchors.length);
	linkloop: for (var i = 0; i < anchors.length; i++) {
		var a = anchors[i];
		if (!a.href) continue;
		var loc = getLinkLocation(a.href);
		// Is there a profile for this location?
		var profile = getGAProfile(loc);
		if (!profile) continue;
		// HACK: There's really no great way to generically tell if a
		//       web server is going to return a Javascriptable
		//       content type or not, so we're just taking a swing at
		//       things here. If the pathname has what looks like an
		//       extension, and the extension looks like it's not a
		//       HTML type of thing, manually track it.
		// NOTE: In Plone a URL we want to match might also be
		//       http://foo.org/biz/awesome.pdf/at_download/file
		var pathLast = loc.pathname.split("/")[loc.pathname.split("/").length - 1];
		var ext = ""; if (pathLast.indexOf(".") >= 0) ext = pathLast.split(".")[pathLast.split(".").length - 1];
		if (/\/at_download\/file\/?$/.test(loc.pathname) || (ext && !/(s?html?|aspx?|cfm|php)\/?$/.test(ext))) {
			// Manually track these pageviews.
			// NOTE: It doesn't matter if your GA code is asynchronous
			// or not, this has to fire right away or not at all, because
			// (presumably) clicking on a link means the current page is
			// going away.
			//if (console && console.log) console.log("Adding manual page tracking for '%s' with profile '%s'", loc.pathname, profile);
			if (a.addEventListener) {
				a.addEventListener('click', trackFuturePageview, false);
			} else if (a.attachEvent) {
				a.attachEvent('onclick', trackFuturePageview);
			}
		}
	};
};
// Get the profile for the current site.
var curProfile = getGAProfile(window.location);
if (curProfile) {
	// if (console && console.log) console.log("Loading Google Analytics for '%s' and '%s'.", ".naz.edu", curProfile);
	
	_gaq.push(
		['overall._setAccount',    'UA-4159588-19'         ],
		[        '_setAccount',    profiles[curProfile]    ],
		['overall._setDomainName', '.naz.edu'              ],
		[        '_setDomainName', curProfile.split("/")[0]],
		['overall._trackPageview'                          ],
		[        '_trackPageview'                          ],
		['overall._trackPageLoadTime'                      ],
		[        '_trackPageLoadTime'                      ]
	);

	(function() {
		var ga = document.createElement('script');
		ga.type = 'text/javascript';
		ga.async = true;
		if (document.location.protocol == 'https:') {
			ga.src = 'https://ssl.google-analytics.com/ga.js';
		} else {
			ga.src = 'http://www.google-analytics.com/ga.js';
		}
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(ga, s);
	})();

	// if (console && console.log) console.log("Google Analytics loaded");
	if (window.addEventListener) {
		window.addEventListener("load", function() {_gaq.push(trackNotHTML);}, false);
	} else if (window.attachEvent) {
		window.attachEvent("onload", function() {_gaq.push(trackNotHTML);});
	}
} else {
	// if (console && console.log) console.log("Hostname '%s' is not recognized as a Google Analytics profile. Loading skipped.", profile_name_part);
}
