/*
	This javascript automatically makes page view calls to the GA server.
	As well, it tags file downloads and external links in Google Analytics.
	You need to be using the Google Analytics New Tracking Code (ga.js) 
	for this script to work.
	To use this file, place the script reference to this file on all pages just below the
	Google Analytics code that includes GA.js.  See the accompanying example file prweb_basic_tracking.html
	
	AUTOMATIC FILE DOWNLOAD/EXTERNAL LINK TRACKING
	For automatic file download and external link tracking, a call to gaVKItagConfig must be made in the on-page code
	The code is executed by a call to startListening as in the following example code:
	startListening(window, ‘load’, function () {gaVKItagConfig(‘pdf’, false, false, false);});
	This will attach event listeners to the correct links AFTER the page has loaded, thus ensuring all
	links are tagged
	All outbound links and links to non-html files should now be automatically tracked.
	Please see the accompanying file prweb_pdf_tracking.html for an example.

	VIDEO TRACKING
	This will track interactions with YouTube videos by sending events.
	The events sent are "Started", "25% viewed", "50% viewed", "75% viewed", "100% viewed"
	The events can be triggered repeatedly.  For example, if they rewind, fast forward, replay etc
	events will be sent again once they reach the event trigger.

	To enable YouTube tracking, you must set the following variables:
	document.ytPlayerID		a unique ID for the video player
	document.ytVideoID		the YouTube video ID that should be loaded and played
	document.strVideoName		the name of the video. The event labels will be set to this value.

	Following is example code for embedding and tracking a YouTube video.
	
	<script src="http://swfobject.googlecode.com/svn/tags/rc3/swfobject/src/swfobject.js" type="text/javascript"></script>
	<!-- embed the player -->
	<div id="ytapiplayer">
	You need Flash player 8+ and JavaScript enabled to view this video.
	</div>
	<script type="text/javascript">
	// <![CDATA[
	document.strVideoName = 'PRWeb in Plain English';
	document.ytPlayerID = "myytplayer";
	document.ytVideoID = "1YB74txAaTc";

	// allowScriptAccess must be set to allow the Javascript from one 
	// domain to access the swf on the youtube domain
	var params = { allowScriptAccess: "always", bgcolor: "#cccccc" };
	// this sets the id of the object or embed tag to 'myytplayer'.
	// You then use this id to access the swf and make calls to the player's API
	var atts = { id: document.ytPlayerID };
	swfobject.embedSWF("http://www.youtube.com/v/" + document.ytVideoID + "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=ytplayer",
					"ytapiplayer", "425", "350", "8", null, null, params, atts);
	//]]>

	</script>
*/

//set to false so log messages are not recorded
var debug = false;

function logMessage(msg) {
	if (debug) {
		if (typeof console != 'undefined')
			console.log(msg);
		else
			alert(msg);
	}
}

// add body onload function to automatically track pdf downloads
startListening(window, 'load', function () {gaVKItagConfig('pdf', false, false, false);});

try {
	var websiteOriginsCookie = readCookie('websiteOrigin');
	var originalTitle = document.title;
	var cookieDomain = "";
	var gaWebPropertyID = "";
	
	if (document.location.href.indexOf('.prweb.com') != -1) {
		cookieDomain = ".prweb.com";
		gaWebPropertyID = "UA-2647064-1";
	}
	else if (document.location.href.indexOf('.prwebtest.com') != -1) {
		cookieDomain = ".prwebtest.com";
		gaWebPropertyID = "UA-2647064-1";
	}
	else if (document.location.href.indexOf('.vkistudios.net') != -1) {
		cookieDomain = ".vkistudios.net";
		gaWebPropertyID = "UA-5002093-8";
	}
	
	// if from the UK website, append the UK site to the title for GA filtering.
	// as well, set a session cookie so any activity will be tracked back to the UK site for this session.
	if (document.location.href.indexOf('uk.prweb') != -1 || websiteOriginsCookie == 'UK') {
		document.title = appendOrigin(document.title, 'UK');
		createCookie('websiteOrigin', 'UK', 0);
	}
	
	var PRWebTracker = _gat._getTracker(gaWebPropertyID);
	
	PRWebTracker._setDomainName(cookieDomain);
	
	PRWebTracker._setAllowLinker(true);
	PRWebTracker._setAllowHash(false);

	if (document.strTrackPageView) {
		PRWebTracker._trackPageview(document.strTrackPageView);
	} else {
		PRWebTracker._trackPageview();
	}
	
	document.title = originalTitle;
	
} catch (e) {}

/*
	BEGIN: Video Tracking
*/

if (document.strVideoName) {
	var ytplayer = false;
	
	YouTubeStates = {
		unstarted : -1,
		ended : 0,
		playing : 1,
		paused : 2,
		buffering : 3,
		cued : 5
	}
		
	function Video (videoName) {
		this.videoName = videoName;
		this.duration = 0;
		this.markerTimes = {};
		this.markerEventSent = {};
		this.previousMarkerTime = 0;
		
		this.getVideoName = function () {
			return this.videoName;
		}
		
		this.getDuration = function () {
			return this.duration;
		}
		
		this.getMarkerTime = function (marker) {
			return this.markerTimes[marker];
		}
		
		this.setDuration = function (duration) {
			// YouTube includes the "Replay" overlay animation as part of video duration, but sends the ended state exactly at the end of the video	
			// thus, we will get the "ended" state change notification before the current time equals the duration of the video. 
			// to fix this issue, we'll round the duration down
			
			this.duration = Math.floor(duration);
			this.markerTimes = {};
			this.markerTimes['25'] = this.duration * 0.25;
			this.markerTimes['50'] = this.duration * 0.5;
			this.markerTimes['75'] = this.duration * 0.75;
			
			this.markerEventSent['started'] = false;
			this.markerEventSent['25'] = false;
			this.markerEventSent['50'] = false;
			this.markerEventSent['75'] = false;
			this.markerEventSent['finished'] = false;
		}
		
		this.setCurrentTime = function (currentTime) {
			
			/*
			  * if the current video time is within 1 second of the marker, send the event and mark all previous markers as sent.
			  * this prevents any other markers from being sent if the person skips backwards/forwards in the video and only records
			  * the events that truly occurred.
			  */
			
			if (getPlayerState() == YouTubeStates.ended) {
				if (Math.abs(currentTime - this.duration) <= 1 && !this.markerEventSent['finished']) {
					this.trackEvent('100% viewed');
					this.markerEventSent['finished'] = true;
					this.markerEventSent['started'] = false;
					this.markerEventSent['25'] = false;
					this.markerEventSent['50'] = false;
					this.markerEventSent['75'] = false;
				}
			}
			else {
				if (Math.abs(currentTime - this.markerTimes['75']) <= 1 && !this.markerEventSent['75']) {
					this.trackEvent('75% viewed');
					this.markerEventSent['25'] = true;
					this.markerEventSent['50'] = true;
					this.markerEventSent['75'] = true;
				}
				else if (Math.abs(currentTime - this.markerTimes['50']) <= 1 && !this.markerEventSent['50']) {
					this.trackEvent('50% viewed');
					this.markerEventSent['25'] = true;
					this.markerEventSent['50'] = true;
				}
				else if (Math.abs(currentTime - this.markerTimes['25']) <= 1 && !this.markerEventSent['25']) {
					this.trackEvent('25% viewed');
					this.markerEventSent['25'] = true;
				}
				else if (Math.abs(currentTime) <= 1 && !this.markerEventSent['started']) {
					this.trackEvent('Started');
					this.markerEventSent['started'] = true;
					this.markerEventSent['25'] = false;
					this.markerEventSent['50'] = false;
					this.markerEventSent['75'] = false;
					this.markerEventSent['finished'] = false;
				}
			}
			
			// check if visitor rewound video.  If they did, allow future time events to be resent
			if (currentTime < this.previousMarkerTime) {
				if (currentTime < this.markerTimes['25'])
					this.markerEventSent['25'] = false;
					
				if (currentTime < this.markerTimes['50'])
					this.markerEventSent['50'] = false;
					
				if (currentTime < this.markerTimes['75'])
					this.markerEventSent['75'] = false;
				
				this.markerEventSent['finished'] = false;
			}
			
			this.previousMarkerTime = currentTime;
		}
		
		this.trackEvent = function (action) {
			if (typeof PRWebTracker != 'undefined') {
				PRWebTracker._trackEvent('Videos', action, this.videoName);
				logMessage(action);
			}
		}
	}
	
	function onYouTubePlayerReady(playerId) {
		  ytplayer = document.getElementById(document.ytPlayerID);
		  ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
		  ytplayer.addEventListener("onError", "onPlayerError");
		  setInterval(updateytplayerInfo, 250);
	}

	function onytplayerStateChange(newState) {
		switch (newState) {
			case YouTubeStates.unstarted:
				break;
			
			case YouTubeStates.ended:
				break;
				
			case YouTubeStates.playing:
				break;
				
			case YouTubeStates.paused:
				break;
				
			case YouTubeStates.buffering:
				break;
			
			case YouTubeStates.cued:
				break;
			
			default:
				break;
		}
	}

	function updateytplayerInfo() {
		if (typeof video != 'undefined') {
			if (video.getDuration() <= 0) {
				if (getDuration() > 0)
					video.setDuration(getDuration());
			}
			else {
				video.setCurrentTime(getCurrentTime());
			}
			
		}
	}

	function getPlayerState() {
		if (ytplayer) {
			return ytplayer.getPlayerState();
		}
	}

	function getCurrentTime() {
		if (ytplayer) {
			return ytplayer.getCurrentTime();
		}
	}

	function getDuration() {
		if (ytplayer) {
			return ytplayer.getDuration();
		}
	}

	var video = new Video(document.strVideoName);
}

/* END: video tracking */

/*	Configuration options required:
	1.	Select which external links to listen for
	2.	If document downloads, specify which ones or accept the default list.
*/
	var isDocs = true;
	var isMailto = true;
	var	isExternal = true;
	var isVirtual = true;
	var patternDocslist = 
/\.(?:doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)($|\&|\?)/;


	// Syntax: gaVKItagConfig([true|false|string of bar-delimited extensions [, true|false [, true|false [,  true|false]]]]) ; If all false, don't bother loading script
function gaVKItagConfig(docslist, mailto, external, virtual) {
	
	isDocs = (typeof docslist == 'boolean') ? docslist : docslist > '';	// Determine isDocs 
	if (typeof docslist == 'string' && docslist > '') patternDocslist = new RegExp('\\.(?:' + docslist + ')($|\\&|\\?)'); // updated by erikvold VKI added \? in second group:
	isMailto = (mailto !== undefined) ? mailto : true;
	isExternal = (external !== undefined) ? external : true;
    isVirtual = (virtual !== undefined) ? virtual : true;

	
	gaVKItag();
}

function gaVKItag() {

	if ((isDocs || isMailto || isExternal || isVirtual) && document.getElementsByTagName) {

		// Initialize external link handlers
	        var hrefs = document.getElementsByTagName("a");
	        for (var h = 0; h < hrefs.length; h++) {

					// try {} catch{} block added by erikvold VKI
				try{
		                //protocol, host, hostname, port, pathname, search, hash
		                if (isMailto && hrefs[h].protocol == "mailto:") {
		                        startListening(hrefs[h],"click",trackMailto);
		                } else if (isDocs && hrefs[h].hostname == location.host) { //BK VKI 080820
		                        var path = hrefs[h].pathname + hrefs[h].search;
								
								var isDoc = path.match(patternDocslist);							
								
		                        if (isDoc) {
		                            startListening(hrefs[h],"click",trackExternalLinks);
									hrefs[h].onclick = function () {return false;};
		                        }
		                } else if (isExternal && hrefs[h].hostname  && hrefs[h].hostname !== location.host) {
								startListening(hrefs[h],"click",trackExternalLinks);
		                }
				}  catch(e){
					continue;
				}
	        }
	}
}

function startListening (obj,evnt,func) {
        if (obj.addEventListener) {
                obj.addEventListener(evnt,func,false);
        } else if (obj.attachEvent) {
                obj.attachEvent("on" + evnt,func);
        }
}

function trackMailto (evnt) {
        var href = evnt.srcElement ? evnt.srcElement.href : this.href;
        var mailto = "/mailto/" + href.substring(7);
		if (typeof(PRWebTracker) == "object") PRWebTracker._trackPageview(mailto); 
}

function trackExternalLinks (evnt) {
        var e = (evnt.srcElement) ? evnt.srcElement : this;
        while (e.tagName !== "A") {
                e = e.parentNode;
        }
		var lnk = (e.pathname.charAt(0) == "/") ? e.pathname : "/" + e.pathname; 
        if (e.search && e.pathname.indexOf(e.search) == -1) lnk += e.search;
		if (e.hostname !== location.host) lnk = "/external/" + e.hostname + lnk; 
		
		if (typeof(PRWebTracker) == "object") {
			// if the originating website is set, prepend to the title so it can be filtered out
			var websiteOriginsCookie = readCookie('websiteOrigin');
			var originalTitle = document.title;
			
			if (websiteOriginsCookie != null)
				document.title = appendOrigin(document.title, websiteOriginsCookie);
			
			PRWebTracker._trackPageview(lnk);
			document.title = originalTitle;
			
			fwdTo = e.href;
			
			setTimeout("window.location.href = fwdTo;", 500);
		}
}

function addTrans(orderID, affiliate, total, tax, shipping, city, state, country) {

	var websiteOriginsCookie = readCookie('websiteOrigin');
	
	// if the originating website is set, append to the orderID so it can be filtered out
	if (websiteOriginsCookie != null)
		orderID += "_" + websiteOriginsCookie;
		
	PRWebTracker._addTrans(
		orderID,
		affiliate,
		total,
		tax,
		shipping,
		city,
		state,
		country);
}

function addItem(orderID, SKU, productName, category, price, qty) {

	var websiteOriginsCookie = readCookie('websiteOrigin');
	
	// if the originating website is set, append to the orderID so it can be filtered out
	if (websiteOriginsCookie != null)
		orderID += "_" + websiteOriginsCookie;
		
	PRWebTracker._addItem(
		orderID,
		SKU,
		productName,
		category,
		price,
		qty);
}

function trackTrans() {
	PRWebTracker._trackTrans();
}

function createCookie(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 = "";
	document.cookie = name+"="+value+expires+"; domain=" + cookieDomain + "; path=/";
}

function readCookie(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;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function appendOrigin(str, orig) {
	// append the originating site to the string
	return '[-' + orig + '-] ' + str;
}