//////////////////////////////////////////////////////////
// CustomAnalytics
// The custom analytics object handles automatic site
//  link tracking and tagging to capture richer
//  (anonymous) data via Google Analytics and to
//  pass media attribution credits between branded sites.
//////////////////////////////////////////////////////////

var CustomAnalytics = {

	/* ABOUT uxRegionList ****************************************************************
		This is an associative object with a jQuery-style selector for a DIV followed by
		the letter to be assigned.  the wireUXRegion() function will go through this list
		and append the variable 'ux=...' to the end of every link within a div.
		This list is ORDER-SPECIFIC.  If div A contains div B, but they should each have
		unique UX tracking, ensure that div B comes AFTER div A. 
		--------------------------------------------------------------------------------*/
		
	uxRegionList:{
		'div#header':'h',
		'div#navigation':'t',
		'div#menu':'l',
		'div#content':'m',
		'div#landing-callout':'lc',
		'div#callouts':'r',
		'div#footer':'f'
	} // End uxRegionList
	,
	gaWirePdfs: function() {
	
		//alert('wiring gaWirePdfs...');	
		// Adds GA Page Tracking to all *local* PDF links
		$("a[href$='.pdf']:not([href^='http:'])").click(function() {
			targetURI = $(this).attr("href");
			try {
				pageTracker._trackPageview(targetURI);
			} catch(error) {
				// GA Page Tracker isn't implemented correctly.
				// alert('Error adding GA tracking to local PDF. Details: ' + error);
			}
			// Either opens PDF in a new window or in same window.
			if ($(this).attr("target")=="_blank") { window.open(targetURI); }
			else { window.location=targetURI; }
			return false;
		});
		
	} // End gaWirePdfs()
	,
	wireUXRegion: function() {	
		for (var regionQuery in CustomAnalytics.uxRegionList) {
			$(regionQuery + " a:not([href^='http:'],[href^='#elig'],[href^='#eligibility'],[href^='javascript:'],[href^='/system_pages/'])").attr("href", function() { return CustomAnalytics.appendUXRegion(this, CustomAnalytics.uxRegionList[regionQuery])});
		}
	} // End wireUXRegion()
	,
	appendUXRegion: function(p, region) {
		p = new String(p.toString());

		// Make the URL a local path (this only works for local functions)
		if (p.substring(0,7) == 'http://') {
			p = p.split('/');
			p.shift(); p.shift(); p.shift();
			p = '/' + p.join('/');
		}

		var newVar = "ux="+region;
		var hash = "";
		var hashIndex = p.indexOf("#");
		if (hashIndex>=0) {
			hash = p.substr(hashIndex);
			p = p.substring(0,hashIndex-1);
		}
		if (p.match(/ux=[a-z]+/i) != null) {
			p = p.replace(/ux=[a-z]/,newVar);
		} else {
			if (p.indexOf("?")>=0) {
				p += "&";
			} else {
				p += "?";
			}
			p += newVar + hash
		}
		return p;
	} // End appendUXRegion(linkPath, pageRegion)
	,
	appendSource: function(uri) {
		var joinChar = (uri.indexOf("?")>=0) ? "&" : "?";
		var sourceVal = Storage.readCookie("source");
		if (sourceVal > 0)
			return uri + joinChar + "source=" + sourceVal;
		return uri;
	} // End appendSource()
	,
	init: function() {
		/* Add source code cookie value to all external links for media source attribution */
		$("a[href^='http']:not([href*='astrazeneca'],[href*=azprivacy])").each(function() { 
			var innerHTML = this.innerHTML;
			this.href=CustomAnalytics.appendSource(this.href);
			this.innerHTML = innerHTML;
		}).click(function() {
//			try { pageTracker._trackEvent('siteExit',this.href); }
//			catch(error){}
			return true;
		});

		CustomAnalytics.gaWirePdfs();
		CustomAnalytics.wireUXRegion();
		
	}
}

$(document).ready(function() {
    	CustomAnalytics.init();
});







//////////////////////////////////////////////////////////
// Storage
// The storage object handles cookie operations
//////////////////////////////////////////////////////////
var Storage = {

	readCookie: function(name) {
		var nameEQ = name + '=';
		var ca = document.cookie.split(';');
		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') {
				c = c.substring(1, c.length);
			}
			if (c.indexOf(nameEQ) == 0) {
				return c.substring(nameEQ.length, c.length);
			}
		}
		return null;
	} // End readCookie()
	,
	
	createCookie: function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = '; expires=' + date.toGMTString();
		}
		else {
			var expires = '';
		}
		var ck = name + '=' + value + expires + '; path=/';
		//	if (days != -1) alert('Cookie\n' + ck + '\ncreated');
		document.cookie = ck;
	} // End createCookie()
	,
	
	expireCookie: function(name) {
		if (name) {
			Storage.createCookie(name,'',-1);
		}
	} // End expireCookie()
	,
	
	cookieQsParam: function(key) {
		key = key.toLowerCase();
		var qs = window.location.search.substring(1);
		var pairs = qs.split('&');
		for (var i = 0; i < pairs.length; i++) {
			var name = pairs[i].split('=')[0];
			var val = pairs[i].split('=')[1];
			if (name.toLowerCase() == key) {
				if (Common.isNumeric(val)) {
					Storage.createCookie(key, val, null);
				}
			}
		}
	} //End cookieQsParam()

};

