// Google Analytics - Custom measurement functions
// (c) Sampsa Suoninen
// 2008-02-15

/* List of usable variables with default values and descriptions:



//
/* Measurement code start - Do not change anything beyond this line! */
//

function urchinTrack(){
	// Variable default values
	this.urchinServers = '1'; // Set servers to report data to: 0 = local (urchin), 1 = remote (GA), 2 = both. Default: remote
	this.urchinImage = '/__utm.gif'; // Set local image file path, default /__utm.gif
	this.urchinLocalization = ''; // Localization content group, if set, must end with a slash, e.g. "english/". Default: no value
	this.urchinDownload = '\.pdf$|\.zip$|\.rar$|\.gz$|\.bz2$|\.exe$|\.tar$|\.7z$|\.ppt$|\.xls$'; // Download types or dynamic files defined as downloads, delimiter character: |
	this.urchinAudio = '\.mp3$|\.ogg$|\.wma$|\.3gp$'; // Audio file (podcasts etc.) types that should not be counted as downloads, delimiter character: |
	this.urchinPageName = ''; // Page name (leave empty if you don't know what you're doing)
	this.urchinPageNameToLower = 'true'; // Force lower case page & content group names. Recommended. NOTE: Added to improve data integrety. May break site overlay
	this.urchinRSS = '\/feed$'; // RSS link filetypes (can be dynamic), delimiter character: |
	this.urchinContentGroup = ''; // Content group, does not work together with engagement
	this.urchinInternalDomains = ''; // Comma separated list of domains concidered as internal links (format: '|domain.com|domain.net')
	this.urchinSearchTrack = 'false';
	this.urchinSearchMatch = 's';
	this.urchinSegmentActive = 'false'; // Enable engagement segmentation, set 'true' to enable (disables default content group segmentation)
	this.urchinSegmentType = 'simple'; // Segment types: "simple" (1 level) or "full" (multilevel)
	this.urchinSegment1Name = 'Engagement Index Light'; // Name of segment one (as shown in GA)
	this.urchinSegment1TimeLimit = '60' // Minimum value for segment one (in seconds)
	this.urchinSegment1PageLimit = '3' // Minimum value for segment one (in pages)
	this.urchinSegment2Name = 'Engagement Index Medium'; // Name of segment two (as shown in GA)
	this.urchinSegment2TimeLimit = '180' // Minimum value for segment two (in seconds), all values larger than this are part of segment two
	this.urchinSegment2PageLimit = '5' // Minimum value for segment two (in pages), all values larger than this are part of segment two
	this.urchinSegment3Name = 'Engagement Index Heavy'; // Name of segment three (as shown in GA)
	this.urchinSegment3TimeLimit = '300' // Minimum value for segment three (in seconds), all values larger than this are part of segment three
	this.urchinSegment3PageLimit = '10' // Minimum value for segment three (in pages), all values larger than this are part of segment three
	this.urchinSegmentSitePath = '/'; // Path on site where to apply, default '/' for the whole site
	this.urchinSegmentLifeTime = '630720000000'; // Segment lifetime in milliseconds
	this.urchinCampaignEnable = 'true';
	this.urchinCampaignModify = 'false'; // Set this value 1 if campaign tracking variables need to be reset to the values below
	// Define variable names for campaign URL query string 
	// These three variables are used only if urchinCampaign is set to 'true'
	this.urchinCampaignAnchor='false';
	this.urchinCampaignName='camp';
	this.urchinCampaignSource='adver';
	this.urchinCampaignMedium='type';
	this.urchinCampaignTerm='kwd';
	this.urchinCampaignVersion='version'; 
	this.urchinCampaignID='cid';
	
	var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	var hackTrack = _gat._getTracker("UA-58419-1");
	hackTrack._initData(); // New GA data initalization
	
	// For combination use with Urchin
	switch(this.urchinServers)
	{
		case "0":
			hackTrack._setLocalGifPath(this.urchinImage);
			hackTrack._setLocalServerMode();
			break;
		case "2":
			hackTrack._setLocalGifPath(this.urchinImage);
			hackTrack._setLocalRemoteServerMode();
			break;
		default:
			hackTrack._setRemoteServerMode();
	}
	
	/* Google Analytics event tracking initialization, TBD */
	//var hackEvent = hackTrack._createEventTracker("Forms");
	
	// This functionality should be dispended
	
	hackTrack._setCampaignTrack(this.urchinCampaignEnable);
	if(this.urchinCampaignModify == "true")
	{
		hackTrack._setAllowAnchor(this.urchinEnableAnchor);
		hackTrack._setCampNameKey(this.urchinCampaignName);
		hackTrack._setCampSourceKey(this.urchinCampaignSource);
		hackTrack._setCampMediumKey(this.urchinCampaignMedium);
		hackTrack._setCampTermKey(this.urchinCampaignTerm);
		hackTrack._setCampContentKey(this.urchinCampaignVersion);
		hackTrack._setCampIdKey(this.urchinCampaignID);
	}
	
		var tmpDomain = document.domain.split(".");
		if(document.domain.search(".co.") == -1) {
			tmpDomain = tmpDomain.slice(-2);
		} else {
			tmpDomain = tmpDomain.slice(-3);
		}
		this.urchinDomain = tmpDomain.join(".");
	
		// Main function, sends Google Analytics "page view" hit.
	this.urchinRun = function(){
		if(this.urchinContentGroup && (this.urchinContentGroup != '') && (this.urchinSegmentActive != 'false')) {
			if(this.urchinPageNameToLower == "true")
			{
				this.urchinContentGroup = this.urchinContentGroup.toLowerCase();
			}
			hackTrack._setVar(this.urchinContentGroup);
		} 
		
		if(this.urchinSearchTrack == "true" && urchinGetURLParameter(this.urchinSearchMatch)) {
			searchResults = escape(urchinGetURLParameter(this.urchinSearchMatch));
			this.urchinPageName = "/search/" + searchResults;
		} else if(this.urchinPageName&&this.urchinPageName != "") {
			if(this.urchinPageNameToLower == "true")
			{
				this.urchinPageName = this.urchinPageName;
			} 
		} else {
			if(this.urchinPageNameToLower == "true")
			{
				this.urchinPageName = location.pathname + location.search; 
			} 
		}
		hackTrack._trackPageview(this.urchinPageName.toLowerCase());
	}
	
	// This function enables tracking of anchor (a) HTML elements. Includes:
	// - Download links
	// - Exit links
	// - Mail links
	// - RSS links
	// For development, add more functions.
	this.urchinLinks = function(){
		var a = document.getElementsByTagName('a');
		var domain = /^(http|https):\/\/([a-z-.0-9]+)[\/]{0,1}/i.exec(window.location);
		var isDownload = new RegExp("("+this.urchinDownload+")", "i");
		var isAudio = new RegExp("("+this.urchinAudio+")", "i");
		var isInternalLink = new RegExp("("+this.urchinDomain+this.urchinInternalDomains+")", "i");
		var isRSS = new RegExp("("+this.urchinRSS+")", "i");
		for(var i = 0; i < a.length; i++){
			var currentBind = a[i].getAttribute("onclick");
			var actionBind = 'click'; // What event to bind to (do not define "onclick"? Default "click"
			var actionIdent = '/'; // Content group to be used? Default '/'
			// Until a better solution presents itself, change "this.href" to "this.alt", "this.title" or "this.innerHTML" depending on what you want to be the link name
			// Wargning DO NOT USE innerHTML unless you are 110% sure there are no image etc. links with HTML as the link text. Will ruin your day.
			
			if(a[i].protocol != "javascript:") {
				if(a[i].protocol == "mailto:") {
					this.runTracker('email', a[i], a[i].href, actionBind, actionIdent, currentBind, false);
				} else if(this.urchinRSS && isRSS.test(a[i].href)) {
					this.runTracker('rss', a[i], a[i].href, actionBind, actionIdent, currentBind, false);
				} else if(this.urchinDownload && isDownload.test(a[i].href)){
					this.runTracker('downloads', a[i], a[i].href, actionBind, actionIdent, currentBind, false);
				} else if(this.urchinAudio && isAudio.test(a[i].href)){
					this.runTracker('listen', a[i], a[i].href, actionBind, actionIdent, currentBind, false);
				} else if(!isInternalLink.test(a[i].href)) {
					this.runTracker('exit', a[i], a[i].href, actionBind, actionIdent, currentBind, false);
				}
			}
		}
	}
	
	this.runTracker = function(pageType, pageItem, pageName, pageBind, pageIdent, currentBind, pageCondition) {
		switch (pageType)
		{
			case "email":
				urchinEventBind(pageItem, pageBind, function(){ hackTrack._trackPageview('/email'+pageIdent+pageName.substring(7)) + ((currentBind != null) ? ";"+currentBind : ""); }, pageCondition);
				break;
			case "rss":
				urchinEventBind(pageItem, pageBind, function(){ hackTrack._trackPageview('/rss'+pageIdent+pageName.replace(/^(http|https):\/\/([a-z-.0-9]+)\//i, '')) + ((currentBind != null) ? ";"+currentBind : ""); }, pageCondition);
				break;
			case "downloads":
				urchinEventBind(pageItem, pageBind, function(){ hackTrack._trackPageview('/download'+pageIdent+pageName.replace(/^(http|https):\/\/([a-z-.0-9]+)\//i, '')) + ((currentBind != null) ? ";"+currentBind : ""); }, pageCondition);
				break;
			case "listen":
				urchinEventBind(pageItem, pageBind, function(){ hackTrack._trackPageview('/listen'+pageIdent+pageName.replace(/^(http|https):\/\/([a-z-.0-9]+)\//i, '')) + ((currentBind != null) ? ";"+currentBind : ""); }, pageCondition);
				break;
			case "exit":
				urchinEventBind(pageItem, pageBind, function(){ hackTrack._trackPageview('/offsite'+pageIdent+pageName.replace(/^http:\/\/|https:\/\//i, '')) + ((currentBind != null) ? ";"+currentBind : ""); }, pageCondition);
				break;
	}	
}
}
// Helper functions

function urchinEventBind(obj, evt, newhandler, captures)
{
	if (obj.attachEvent)
		obj.attachEvent('on' + evt, newhandler);
	else if (obj.addEventListener)
		obj.addEventListener(evt, newhandler, captures);
	else
	{
		var oldhandler;
		if (oldhandler = obj['on' + evt])
			obj['on' + evt] = function() { oldhandler(); newhandler(); }
		else obj['on' + evt] = newhandler;
	}
}

function urchinSetCookie(cookieName, cookieValue, cookieExpireDays, urchinDomain, urchinSitePath)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+cookieExpireDays)
	document.cookie=cookieName+ "=" +escape(cookieValue)+
	((cookieExpireDays==null) ? "" : ";expires="+exdate.toGMTString())+
	(( urchinDomain==null) ? "; domain=" + urchinDomain : "" ) +
	(( urchinSitePath==null) ? "; path=" + urchinSitePath : "/" );
}

function urchinGetCookie(name) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ((!start) &&(name!=document.cookie.substring(0, name.length))){
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf( ";", len );
	if (end == -1) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function urchinGetURLParameter(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

// End of helper functions

