/** 
 * @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
  * getBaseDomain
  * addTrans
  * addItem
  * trackTrans
  * tagCrossDomainLinks
  */

/* BEGIN: VKIUrchin Class */

/**
 * Construct a new VKIUrchin object.
 * @class This is the Urchin wrapper class
 * @constructor
 * @returns A new VKI tracker
 */
	  
function VKIUrchin () {

	var baseDomain = document.location.hostname;
	var debug = false;
	var subdomainsArr = Array(); // array of sites that use subdomains.  Add domains that use subdomains to this array
	
	/*
	 * Add domains that use subdomains.
	 * Each domain will be an array where the first element is the base domain
	 * and the second element is the number of dots in the base domain
	 * Examples:
	 * campusstarter.co.uk would be Array("campusstarter.co.uk", 3)
	 * campusstarter.com would be Array("campusstarter.com", 2)
	 */
	subdomainsArr[0] = Array("campusstarter.com", 2); // first element is base domain, second element is number of dots in the base domain.  For example, campusstarter.co.uk would be Array("campusstarter.co.uk", 3)
	
	// set the base domain
	if (baseDomain.search('vkistudios.net') > -1) {
		baseDomain = 'vkistudios.net'
		debug = true;
	}
	else {
		var found = false;
		
		for (var i = 0; i < subdomainsArr.length; i++) {
			if (baseDomain.search(subdomainsArr[i][0]) > -1) {
				
				found = true;
				var splitHost = baseDomain.split('.');
				baseDomain = "";
				
				for (var j = 1; j <= subdomainsArr[i][1]; j++) {
					
					baseDomain = '.' + splitHost[splitHost.length - j] + baseDomain;
				}
				
				baseDomain = baseDomain.substr(1);
			}
		}
		
		if (!found) {
			if (baseDomain.search(/^www\./) > -1)
				baseDomain = baseDomain.substr(4);
		}
	}
	
	/* BEGIN: Privileged Functions */
	
	/**
	 * Returns the base domain of the website
	 *
	 * @privileged
	 */
	this.getBaseDomain = function() {
		return baseDomain;
	}
	
	/**
	 *  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);
	}
	
	/**
	 *  Logging function
	 *  
	 * @privileged
	 * @param {string} message
	 */
	 
	this.log = function (message) {
		if (debug == false)
			return;
			
		if (typeof(console.log) == 'function')
			console.log(message);
		else
			alert(message);
	}
	
	/* END: Priviledged Functions */
	
	/* BEGIN: Optional Functionality */
	
	/**
	 *  Looks for links to sites we want to cross-domain link to
	 *  and updates the href to call utmLinker function
	 */
	 
	this.tagCrossDomainLinks = function() {
		$(".country").each(function(idx) {
			this.href = __utmGetLinker(this.href, true);
		});
	}
	
	/**
	 *  Looks for specific elements and attaches click handlers
	 *  that fire off the appropriate tracking request
	 */
	this.tagTrackingElements = function () {
		
		$(".rfi").each(
			function (idx) {
				$(this).click(function () {
					_vkiurchin.rfischools = _vkiurchin.schoolname;
					_vkiurchin.trackPage('/rfi-request');
				});
			}
		);
		
		$(".banner").each(
			function (idx) {
				$(this).click(function () {
					_vkiurchin.trackPage('/banner-click', $(this).attr('rel'));
				});
			}
		);
	}
	
	/**
	 *	This function removes all non-alphanumeric characters and replaces
	 *	spaces with underscores
	 */
	 
	this.sanitize = function (str) {
		str = str.replace(/\s/g, '_');
		str = str.replace(/('|"|#)/g, '');
		return str;
	}
	
	this.trackPage = function (page, schoolname) {
		if (!page)
			var page = this.pagename;
		
		if (!schoolname)
			var schoolname = this.schoolname;
		
		var str = page;
		str += (schoolname != '') ? '/' + schoolname : '';
		str += (this.prodtype != '') ? '/' + this.prodtype : '';
		str += (this.site != '') ? '-' + this.site : '';
		str += (this.network != '') ? '-' + this.network : '';
		str += (this.region != '') ? '-' + this.region : '';
		
		if (document.location.search != '') {
			str += document.location.search;
			var separator = '&';
		}
		else
			var separator = '?';
		
		str += (this.rfischools != '') ? separator + 'schools=' + this.rfischools : '';
		
		try {
			urchinTracker(this.sanitize(str));
		} catch (e) {this.log(e);}
	}
	/* END: Optional Functionality */
}

var _vkiurchin = new VKIUrchin();

_vkiurchin.pagename = (document.location.pathname == '/') ? '/index.cfm' : document.location.pathname;
_vkiurchin.site = document.location.hostname;

if (_vkiurchin.site.search(/^www\./) > -1)
	_vkiurchin.site = _vkiurchin.site.substr(4);

_vkiurchin.network = '';
_vkiurchin.region = '';
_vkiurchin.schoolname = '';
_vkiurchin.prodtype = '';
_vkiurchin.rfischools = '';

$(document).ready(function () {
	/* BEGIN: initialize page tracking object */

try {
		
	_udn = "." + _vkiurchin.getBaseDomain();
	_uhash = "off";
	_ulink = 1;
	_uanchor = 1;
	_ugifpath = "/urchin/__utm.gif";
	
	if (document.strUserDefined) {
		__utmSetVar(document.strUserDefined);
	}
	
	_vkiurchin.trackPage();
	
	_vkiurchin.tagTrackingElements();
	_vkiurchin.tagCrossDomainLinks();
} catch(e) {}
});

/* END: initialize page tracking object */