/** 
 * @fileoverview This file is to be used for implementing Urchin on a website.
 * It is a wrapper class around the Urchin tracker class and allows you to add custom functionality
 * to Urchin tracking.
 *
 * @author Andre Wei andrewei@vkistudios.com
 */

 /* Function List
  * Privileged Function list
  * addListener
  * getBaseDomain
  * addTrans
  * addItem
  * trackTrans
  * tagCrossDomainLinks
  */
  
var UrchinCrossDomainsList = ""; // pipe-delimited list of base domains to treat as cross-domain.
var UrchinDownloadsList = "pdf"; // pipe-delimited list of extensions to track as downloads
var numBaseDomainParts = 2; // number of parts in the base domain.  ie www.example.com = 2, www.example.co.uk = 3

/* BEGIN: VKIUrchin Class */

/**
 * Construct a new VKIUrchin object.
 * @class This is the Urchin wrapper class
 * @constructor
 * @param {string} crossDomainsList Comma-separated list of base domains to treat as cross-domain
 * @param {int} numDomainParts Number of parts in the base domain
 * @returns A new VKI tracker
 */
	  
function VKIUrchin (crossDomainsList, trackDownloadsList, numDomainParts) {
	
	var loc = document.location;
	var self = this;
	
	var vkiCookie = "__utmvki";
	var tranx = new Object();
	tranx['orderID'] = '';
	tranx['affiliate'] = '';
	tranx['total'] = '';
	tranx['tax'] = '';
	tranx['shipping'] = '';
	tranx['city'] = '';
	tranx['state'] = '';
	tranx['country'] = '';
	tranx['items'] = new Array();
	
	// set the base domain
	numDomainParts = -1*numDomainParts;
	var _baseDomain = loc.hostname.split('.').slice(numDomainParts).join(".");
	
	/**
	 * Comma-separated list of base domains to treat as cross-domain
	 * @private
	 * @type string
	 */
	var _crossDomainsList = "";
	
	if (crossDomainsList != null && typeof(crossDomainsList) == "string")
		_crossDomainsList = crossDomainsList;
	
	var _trackDownloadsList = "";
	
	if (trackDownloadsList != null && typeof(trackDownloadsList) == "string")
		_trackDownloadsList = trackDownloadsList;
		
	/* BEGIN: Privileged Functions */
	
	/**
	 * Returns the base domain of the website
	 *
	 * @privileged
	 */
	this.getBaseDomain = function() {
		return _baseDomain;
	}
	
	/**
	 *  Adds event handler for specified event to an element
	 *  
	 * @privileged
	 * @param {object} element Element to add event listener to
	 * @param {string} type Event to listen for.  Do not prepend event with 'on', as the functions automatically prepends it
	 * @param {object} expression Javascript function to execute on event.  Can be either a function name or anonymous function
	 * @param {boolean} bubbling Sets whether to register the event on bubbling phase (true) or capturing phase (false).  Only applies to W3C compliant browsers.
	 * @returns	True on success, false on failure
	 * @type boolean
	 */
	this.addListener = function (element, type, expression, bubbling) {
		bubbling = bubbling || false;
		
		if (window.addEventListener) { // Standard
			element.addEventListener(type, expression, bubbling);
			return true;		
		} else if(window.attachEvent) { // IE
			element.attachEvent('on' + type, expression);
			return true;
		} else
			return false;
	}
	
	/**
	 *  Adds transaction to Urchin tracking object
	 *  
	 * @privileged
	 * @param {string} unique order ID
	 * @param {string} affiliate store
	 * @param {string} order total excluding taxes and shipping
	 * @param {string} tax amount
	 * @param {string} shipping amount
	 * @param {string} city of customer
	 * @param {string} state of customer
	 * @param {string} country of customer
	 */
	 
	this.addTrans = function (orderID, affiliate, total, tax, shipping, city, state, country) {
		tranx['orderID'] = orderID;
		tranx['affiliate'] = affiliate;
		tranx['total'] = total;
		tranx['tax'] = tax;
		tranx['shipping'] = shipping;
		tranx['city'] = city;
		tranx['state'] = state;
		tranx['country'] = country;
	}
	
	/**
	 *  Adds item to Urchin tracking object
	 *  
	 * @privileged
	 * @param {string} unique order ID
	 * @param {string} unique SKU/identifier of the product
	 * @param {string} descriptive product name
	 * @param {string} category of product
	 * @param {string} unit price of product
	 * @param {string} quantity purchased
	 */
	this.addItem = function (orderID, sku, productName, category, price, quantity) {
		var count = tranx['items'].length;
		
		tranx['items'][count] = new Object();
		tranx['items'][count]['orderID'] = orderID;
		tranx['items'][count]['sku'] = sku;
		tranx['items'][count]['productName'] = productName;
		tranx['items'][count]['category'] = category;
		tranx['items'][count]['price'] = price;
		tranx['items'][count]['quantity'] = quantity;
	}
	
	/**
	 *  Sends transaction tracking request to Urchin if the order hasn't already been sent
	 *  
	 * @privileged
	 * @param {string} unique order ID
	 */
	this.trackTrans = function (orderID) {
		try {
			if (orderID == tranx['orderID'] && this.checkSetTrans(orderID)) {
				var item = null;
				var formHTML = "<form style='display:none;' name='utmform'><textarea id='utmtrans'>\n";
				
				formHTML += 'UTM:T|' + tranx['orderID'] + '|' + tranx['affiliate'] + '|' + tranx['total'] + '|' + tranx['tax'] + '|' + tranx['shipping'] + '|' + tranx['city'] + '|' + tranx['state'] + '|' + tranx['country'] + "\n";
				for (var i = 0; i < tranx['items'].length; i++)
				{
					item = tranx['items'][i];
					formHTML += 'UTM:I|' + item['orderID'] + '|' + item['sku'] + '|' + item['productName'] + '|' + item['category'] + '|' + item['price'] + '|' + item['quantity'] + "\n";
				}
				
				formHTML += '</textarea></form>';
				document.write(formHTML);
				__utmSetTrans();
			}
		}
		catch (e) {}
	}
	
	/**
	 *  Checks if order has already been sent or not.  Sets session cookie to track orders that have been sent.
	 *  
	 * @privileged
	 * @param {string} unique order ID
	 */
	 
	this.checkSetTrans = function (orderID) {
		// Check if this transaction has been sent to Urchin before and this is a reload of the thankyou page
		var strCookieName = vkiCookie;
		var strCookieValue = 'e.' + orderID;
		var strControlCookie = this.readCookie(strCookieName) || '';
		var isNew = (strControlCookie.search(strCookieValue) == -1);
		this.createCookie(vkiCookie, strCookieValue, 1);
		return isNew;
	}
	
	this.extractUTMVars = function (str, delimiter) {
		delimiter = (typeof delimiter == 'undefined') ? '&' : delimiter;
		
		var re = RegExp("__utm[^=]+=[^" + delimiter + "]*", "gi");
		
		var matches = str.match(re);
		var ret = new Object();
		var i, utm, utmval;
		
		if (matches != null) {
			for (i = 0; i < matches.length; i++) {
				utm = matches[i].split("=");
				utmval = utm.slice(1).join("=");
				ret[utm[0]] = utmval;
			}
		}
		
		return ret;
	}
	
	/**
	 *  Creates cookie
	 *  
	 * @privileged
	 * @param {string} cookie name
	 * @param {string} cookie value
	 * @param {string} days until cookie expires
	 * @param {string} optional - domain to set the cookie for
	 */
	 
	this.createCookie = function (name, value, days, cookieDomain) {
	
		var domain = "";
		var expires = "";
		
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = " expires="+date.toGMTString() + ";";
		}
		
		if (typeof(cookieDomain) != 'undefined')
			domain = " domain=" + cookieDomain + "; ";
		
		document.cookie = name + "=" + value + ";" + expires + domain + "path=/";
	}
	
	/**
	 *  Reads cookie
	 *  
	 * @privileged
	 * @param {string} cookie name
	 * @returns	value of the cookie, or null if cookie not set
	 * @type mixed
	 */
	 
	this.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;
	}

	/**
	 *  Deletes cookie
	 *  
	 * @privileged
	 * @param {string} cookie name
	 */
	 
	this.eraseCookie = function (name, cookieDomain) {
		cookieDomain = cookieDomain || getDomainName();
		this.createCookie(name, "", -1, cookieDomain);
	}

	function tagCrossDomain(elem) {
		
		var useHash, url;
		
		if (elem.nodeName == "FORM") {
			
			useHash = (elem.action.search(/#/) > -1) ? false : true;
			
			elem.onsubmit = function(){__utmLinkPost(elem, useHash);};
		}
		else if (elem.nodeName == "A") {
			useHash = (elem.hash == "") ? true : false;
			elem.href = "javascript:__utmLinker('"+ elem.href + "', " + useHash + ");";
		}
	}
	
	/* END: Priviledged Functions */
	
	/* BEGIN: Optional Functionality */
	
	this.tagElements = function() {
		
		if (_crossDomainsList == "" && _trackDownloadsList == "")
			return;
		
		var anchors, anchor, forms, form = null;
		var i, j = 0;
		var regexp, patternDocslist = null;
		var oldHTML = '';
		var url, utmparams, utm, name, val, hidden, useHash = null;
			
		anchors = document.getElementsByTagName("a");
		forms = document.getElementsByTagName("form");
		
		/* compile regexps first to save processing time */
		var crossDomainRegexp = new RegExp("^https?://.*" + _crossDomainsList + "(/?.*)?");
		var patternDocslist = new RegExp("\\.(?:" + _trackDownloadsList + ")($|\\&|\\?|#)");
		var baseDomainRegexp = new RegExp(_baseDomain, "i");
		
		// loop through all anchor tags
		for (i = 0; i < anchors.length; i++) {
			anchor = anchors[i];
			
			// tag cross-domain links
			if (_crossDomainsList != "") {
				// if the link matches, append cookie information to link
				if (!baseDomainRegexp.test(anchor.href) && crossDomainRegexp.test(anchor.href)) {
					tagCrossDomain(anchor);
				}
			}
			
			// tag download links
			if (_trackDownloadsList != "") {
				if (patternDocslist.test(anchor.href)) {
					self.addListener(anchor, "click", _vkiurchin.trackDownload);
					
					if (anchor.target != "_blank" && anchor.onclick == null) {
						
						anchor.onclick = function (e) {
								if (!e) var e = window.event;
								
								e = (e.srcElement) ? e.srcElement : this;
								setTimeout(function(){document.location.href = e.href}, 500);
								
								return false;
							};
					}
				}
			}
		}
		
		// loop through all form tags
		if (_crossDomainsList != "") {
			for (i = 0; i < forms.length; i++) {
				form = forms[i];
				
				if (!baseDomainRegexp.test(form.action) && crossDomainRegexp.test(form.action)) {
					tagCrossDomain(form);
				}
			}
		}
	}
	
	/**
	 *  Sends page view to GA to track file downloads
	 *  
	 * @privileged
	 * @param {event} e DOM event
	 */
	 
	this.trackDownload = function (e) {
		var targ;
		if (!e) var e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;
		
		var lnk = (targ.pathname.charAt(0) == "/") ? targ.pathname : "/" + targ.pathname;
		
		if (targ.search && targ.pathname.indexOf(targ.search) == -1) lnk += targ.search;
		
		if (targ.hostname !== document.location.hostname)
			lnk = "/external/" + targ.hostname + lnk;
		else
			lnk = "/download" + lnk;
		
		try {
			urchinTracker(lnk);
		} catch (err) {}
	}
	
	/* END: Optional Functionality */
}

var _vkiurchin = new VKIUrchin(UrchinCrossDomainsList, UrchinDownloadsList, numBaseDomainParts);

/* BEGIN: initialize page tracking object */

try {
	_udn = "none";
	_uhash = "off";
	_ugifpath = "/_layouts/images/MicrositesImageAssets/__utm.gif";
	
	/* OPTIONAL */
	// if cross-domain is enabled, tag all links
	if (UrchinCrossDomainsList != "" || UrchinDownloadsList != "") {
		if (UrchinCrossDomainsList != "") {
			_ulink = 1;
			_uanchor = 1;
		}
		
		_vkiurchin.addListener(window, 'load', _vkiurchin.tagElements);
	}
	/* OPTIONAL */
	
	if (document.strUserDefined) {
		__utmSetVar(document.strUserDefined);
	}
	
	if (!document.strTrackPageView) {
		var vkiloc = document.location;
		
		if (_udl.pathname.search(/\/pages\/contactusform\.aspx/i) > -1 && _ubd.body.innerHTML.search(/Thank you for your enquiry./i) > -1) {
			document.strTrackPageView = '/pages/contactusformsubmitted' + vkiloc.search;
		}
	}
	
	if (document.strTrackPageView) {
		urchinTracker(document.strTrackPageView);
	} else {
		urchinTracker();
	}
} catch(e) {}

/* END: initialize page tracking object */
