current.tracking = {};
current.tracking.Track = Class.create({
	initialize : function (trackingCode, trackingBucket)
	{
		this.setTrackingCode(trackingCode);
		this.setTrackingBucket(trackingBucket);
		Event.observe(window, 'abort', this.__onAbort.bindAsEventListener(this));
		Event.observe(window, 'dom:loaded', this.__onDomReady.bindAsEventListener(this));
		Event.observe(window, 'load', this.__onPageLoad.bindAsEventListener(this));
		document.observe('click', this.__onDomClick.bindAsEventListener(this));
	},
	setTrackingBucket : function (bucket)
	{
		this._bucket = bucket;
	},
	getTrackingBucket : function ()
	{
		return this._bucket;
	},
	setTrackingCode : function (code)
	{
		this._trackingCode = code;
	},
	getTrackingCode : function ()
	{
		return this._trackingCode;
	},
	setHomepageTest : function (value)
	{
		this.setProperty(current.tracking.Conversion.HOMEPAGE_AD_TEST, value);
	},
	_resetTracking : function ()
	{
		this.setTrackingCode(s_gi(this.getTrackingBucket()));
	},
	_resetProperties : function ()
	{
		var props = current.tracking.Properties;
		var _user = current.User.getInstance();
		
		this.setProperty(props.PAGE_NAME, null);
		this.setProperty(props.CONTENT_TITLE, null);
		this.setProperty(props.CONTENT_ID, null);
		this.setProperty(props.CONTENT_TYPE, null);
		this.setProperty(props.PRODUCER_ID, null);
		this.setProperty(props.CLICK_POSITION, null);
		this.setProperty(props.USER_MEMBER, null);
		this.setProperty(props.PREVIOUS_PAGE, null);
		this.setProperty(props.PREVIOUS_PAGE_NAME, null);
		this.setProperty(props.HIERARCHY, null);
		this.setProperty(props.FRANCHISE, null);
		this.setProperty(props.GROUP_NAMES, null);
		this.setProperty(props.PARENT_GROUP_NAME, null);
		this.setProperty(props.CLASSIFIER_PARENT_GROUP_NAME, null);
		this.getTrackingCode().linkTrackVars = 'None';
		this.getTrackingCode().linkTrackEvents = 'None';
	},
	setProperty : function (name, value)
	{
		var s = this.getTrackingCode();
		s[name] = value;
		var convert = current.tracking.Conversion[name];
		if (convert != null)
		{
			s[convert] = value;
		}
		if (value != null && value != '')
		{
			s.linkTrackVars = (s.linkTrackVars && s.linkTrackVars != 'None') ? s.linkTrackVars.concat(',' + name) : name;
			if (convert != null)
			{
				s.linkTrackVars = (s.linkTrackVars && s.linkTrackVars != 'None') ? s.linkTrackVars.concat(',' + convert) : convert;
			}
		}
	},
	setSection : function (section)
	{
		this.getTrackingCode().channel = section;
		this.setProperty(current.tracking.Properties.SITE_SECTION, section);
	},
	_setEvent : function (event)
	{
		this.getTrackingCode().events = event;
	},
	_setAds : function (arr)
	{
		var t = typeof arr;
		var a = ';';
		if (t == 'number' || t == 'string')
		{
			a += arr;
		}
		else 
		{
			a += arr.join(',;');
		}
		this.setProperty(current.tracking.Properties.ADS, a);
	},
	_addEvent : function (event)
	{
		var e = this.getTrackingCode().events;
		if (e == null || e == '')
		{
			this.getTrackingCode().events = event;
		}
		else
		{
			this.getTrackingCode().events = e.concat(',' + event);	
		}
	},
	_setPreviousPageName : function ()
	{
		setSessionCookie(current.Cookies.PREVIOUS_PAGE_NAME, current.site.Page.getInstance().getPageName());
	},
	doPageTracking : function ()
	{
		var i = this.getTrackingCode().t();
		if (i)
		{
			document.write(i);
		}
		this._setPreviousPageName();
	},
	doTracking : function ()
	{
		var s = this.getTrackingCode();
		s.linkTrackVars = (s.linkTrackVars && s.linkTrackVars != 'None') ? s.linkTrackVars.concat(',' + 'events') : 'events';
		s.linkTrackEvents = s.events;
		var i = s.tl(s, 'o', 'bundle:jsEvents');
		if (i)
		{
			document.write(i);
		}
		//this._setPreviousPageName();
	},
	_fetchUserProperties : function ()
	{	
		var _user = current.User.getInstance();
		var props = current.tracking.Properties;
		this.setProperty(props.USER_COUNTRY, _user.getCountry());
		this.setProperty(props.USER_ID, _user.getId());
		this.setProperty(props.USER_MEMBER, _user.isLoggedIn());
		
		var loginPath = this.getLoginPath();
		if (_user.isLoggedIn() && loginPath != null)
		{
			this.setProperty(current.tracking.Conversion.USER_MEMBER, loginPath);
			deleteCookie(current.Cookies.USER_MEMBER);
		}
	},
	_fetchPageProperties : function ()
	{
		var _page = current.site.Page.getInstance();
		var props = current.tracking.Properties;
		
		this.setProperty(props.PAGE_NAME, _page.getPageName());
		this.setProperty(props.CONTENT_TITLE, _page.getContentTitle());
		this.setProperty(props.CONTENT_ID, _page.getId());
		this.setProperty(props.CONTENT_TYPE, _page.getType());
		this.setProperty(props.PRODUCER_ID, _page.getOwnerId());
		this.setProperty(props.FRANCHISE, _page.getFranchise().gsub(',','|'));
		this.setProperty(props.PREVIOUS_PAGE_NAME, getCookieValue(current.Cookies.PREVIOUS_PAGE_NAME));
		deleteCookie(current.Cookies.PREVIOUS_PAGE_NAME);
		this.setProperty(props.CLICK_POSITION, getCookieValue(current.Cookies.CLICK_MAP));		
		this.setProperty(props.HIERARCHY, _page.getPageName().replace(/:/g, ','));
		this.setSection(_page.getSection());
		this._addEvent(current.tracking.Events.PAGE_VIEW);
	},
	_fetchSearchProperties : function ()
	{
		var searchTerm = current.utils.Url.getParam(current.tracking.Constants.SEARCH_QUERY_PARAM);	
		if (searchTerm != null)
		{
			this.setProperty(current.tracking.Properties.SEARCH_TERM, searchTerm.toLowerCase());
			this.setProperty(current.tracking.Properties.SEARCH_COUNT, current.site.Page.getInstance().getSearchResultCount());
			
			var s = this.getTrackingCode();
			s.eVar1=s.prop1;
			var t_search=s.getValOnce(s.eVar1,'ev1',0);
			if(t_search)
			{
				s.events = s.apl(s.events,'event1',',',2);
			}	
		}
	},
	_fetchItemProperties : function ()
	{
		var _page = current.site.Page.getInstance();
		if (_page.getPageName() == 'item')
		{
			var _iPage = current.content.items.ItemPage.getInstance();
			var props = current.tracking.Properties;
			
			this.setProperty(props.GROUP_NAMES, _iPage.getGroupSlugs().gsub(',','|'));
			this.setProperty(props.PARENT_GROUP_NAME, _iPage.getParentGroupSlug());
			this.setProperty(props.CLASSIFIER_PARENT_GROUP_NAME, _iPage.getClassifierGroupSlug());
		}
	},
	_fetchGroupProperties : function ()
	{
		var _page = current.site.Page.getInstance();
		if (_page.getPageName() == 'group')
		{
			var _gPage = current.content.groups.GroupPage.getInstance();
			var props = current.tracking.Properties;
			
			this.setProperty(props.CLASSIFIER_PARENT_GROUP_NAME, _gPage.getClassifierGroupSlug());
		}
	},
	_fetchEvents : function ()
	{
		if (this.isRegisteredSuccess())
		{
			this._setEvent(current.tracking.Events.REGISTRATION);
			deleteCookie(current.Cookies.REGISTRATION);
		}
	},
	getLoginPath : function ()
	{
		return getCookieValue(current.Cookies.USER_MEMBER);
	},
	isRegisteredSuccess : function ()
	{
		return (getCookieValue(current.Cookies.REGISTRATION) != null);
	},
	isContentCreated : function ()
	{
		return (getCookieValue(current.tracking.Events.CONTENT_ADD) != null);
	},
	__onAbort : function ()
	{
		document.currentTrackingAbortTime = new Date().getTime();
	},
	__onDomReady : function ()
	{
		document.currentTrackingDomReadyTime = new Date().getTime();
	},
	__onPageLoad : function ()
	{
		document.currentTrackingPageLoadTime = new Date().getTime();
		this.doInternalTracking(current.tracking.internal.EventTypeMap.JS_END, false);
	},
	__onDomClick : function (event)
	{
		var rel = event.element().name;
		if (rel == null || rel == '' || rel.indexOf('clickmap') == -1)
		{
			return;
		}
		setSessionCookie(current.Cookies.CLICK_MAP, rel.evalJSON().clickmap);
	},
	execPageTrack : function()
	{
		this._fetchUserProperties();
		this._fetchPageProperties();
		this._fetchSearchProperties();
		this._fetchItemProperties();
		this._fetchGroupProperties();
		this._fetchEvents();
		this.doPageTracking();
		this.doInternalTracking(current.tracking.internal.EventTypeMap.PAGE_LOADED, true);
	},
	doInternalTracking : function (eventType, retCount)
	{
		var p = current.site.Page.getInstance();
		var i = current.tracking.internal;
		var t = i.PageTypeMap.get(p.getPageName());
		if (t == null)
		{
			t = i.PageTypeMap.get('default');
		}
		i.Track.doViewTrack(p, t, eventType, retCount);
	},
	onShare : function ()
	{
		this._resetTracking();
		this._fetchUserProperties();
		this._setEvent(current.tracking.Events.CONTENT_SHARE);
		this.doTracking();
	},
	onContentCreate : function (context, contentType)
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		var contentCreateType  = (context == Clipper2.CONTEXT_COMMENT) ? current.tracking.Properties.CONTENT_COMMENT_CREATE_TYPE : current.tracking.Properties.CONTENT_CREATE_TYPE;
		this.setProperty(contentCreateType, contentType);
		this._setEvent(current.tracking.Events.CONTENT_ADD);
		this.doTracking();
	},
	onCommentSubmitted : function (contentType)
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this.setProperty(current.tracking.Properties.CONTENT_COMMENT_CREATE_TYPE, contentType);
		this._setEvent(current.tracking.Events.COMMENT_SUBMITTED);
		this.doTracking();
	},
	onVote : function ()
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this.setProperty(current.tracking.Properties.VOTE_CONTEXT, current.site.Page.getInstance().getPageName());
		this._setEvent(current.tracking.Events.CONTENT_VOTE);
		this.doTracking();
	},
	onEmbedShare : function ()	
	{
		this._resetTracking();
		this._fetchUserProperties();
		this._setEvent(current.tracking.Events.EMBED_FOCUS);
		this.doTracking();
	},
	onGroupCreate : function ()
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this._setEvent(current.tracking.Events.GROUP_CREATE);
		this.doTracking();
	},
	onGroupJoin : function (groupSlug)
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this.setProperty(current.tracking.Properties.JOIN_CONTEXT, groupSlug);
		this._setEvent(current.tracking.Events.GROUP_JOIN);
		this.doTracking();
	},
	onMessageSend : function ()
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this._setEvent(current.tracking.Events.MESSAGE_SENT);
		this.doTracking();
	},
	onHomepageOptOut : function ()
	{
		this._resetTracking();
		this._fetchUserProperties();
		this._resetProperties();
		this._setEvent(current.tracking.Events.AB_OPT_OUT);
		this.doTracking();
	},
	onBladeOpen : function (contentId, contentTitle, sponsorId)
	{
		var p = current.tracking.Properties
		
		this._resetTracking();
		this._resetProperties();
		
		this._fetchUserProperties();
		this.setProperty(p.CONTENT_TITLE, contentTitle);
		this.setProperty(p.CONTENT_ID, contentId);
		this.setProperty(p.HIERARCHY, 'twoscreen,blade');
		this.setProperty(p.PREVIOUS_PAGE_NAME, getCookieValue(current.Cookies.PREVIOUS_PAGE_NAME));
		deleteCookie(current.Cookies.PREVIOUS_PAGE_NAME);
		
		this._setEvent(current.tracking.Events.BLADE_OPEN);
		if (sponsorId != null )
		{
			this._setAds([sponsorId]);
			this._addEvent(current.tracking.Events.AD_IMPRESSION);
		}
		
		this.setSection('twoscreen');
		this.doTracking();
	},
	onBladeSponsorClick : function (sponsorId)
	{
		this.onAdClick({}, sponsorId);
	},
	onAdClick : function (event, sponsorId)
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this._setEvent(current.tracking.Events.AD_CLICK);
		this._setAds([sponsorId]);
		this.setProperty(current.tracking.Conversion.AD_CLICK, sponsorId);
		this.doTracking();
	},
	onAdImpression : function (sponsorId)
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		var _page = current.site.Page.getInstance();
		this.setProperty(current.tracking.Properties.HIERARCHY, _page.getPageName().replace(/:/g, ','));
		this.setSection(_page.getSection());
		this._setEvent(current.tracking.Events.AD_IMPRESSION);
		this._setAds([sponsorId]);
		this.doTracking();
	},
	onViewpointOpen : function (contentId, contentTitle)
	{ // NO LONGER TRACKED
	},
	onViewpointsTopicChange : function (topicName)
	{ // NO LONGER TRACKED
	},
	onThreadedCommentsExpand : function ()
	{
		this._resetTracking();
		this._resetProperties();
		this._fetchUserProperties();
		this.setProperty(current.tracking.Properties.CONTENT_ID, current.site.Page.getInstance().getId());
		this._setEvent(current.tracking.Events.THREADED_COMMENTS_EXPAND);
		this.doTracking();
	}
});
current.tracking.Track.getInstance = function() {
	if (!document.__currentTracking__)
	{
		document.__currentTracking__ = new current.tracking.Track(s, document.currentTrackingBucket);
	}
	return document.__currentTracking__;
};
current.tracking.Properties = 
{
	PAGE_NAME : 'pageName',
	ADS : 'products',
	SEARCH_TERM : 'prop1',
	SEARCH_COUNT : 'prop2',
	CONTENT_TITLE : 'prop3',
	CONTENT_ID : 'prop4',
	CONTENT_TYPE : 'prop5',
	SITE_SECTION : 'prop7',
	USER_COUNTRY : 'prop10',
	PRODUCER_ID : 'prop14',
	USER_ID : 'prop15',
	CLICK_POSITION : 'prop17',
	HIERARCHY : 'hier1',
	PREVIOUS_PAGE_NAME : 'prop24',
	USER_MEMBER : 'prop25',
	CONTENT_CREATE_TYPE : 'prop26',
	CONTENT_COMMENT_CREATE_TYPE : 'prop27',
	VOTE_CONTEXT : 'prop28',
	FRANCHISE : 'prop29',
	GROUP_NAMES: 'prop30',
	PARENT_GROUP_NAME : 'prop31',
	CLASSIFIER_PARENT_GROUP_NAME : 'prop34',
	JOIN_CONTEXT: 'prop35'
};
current.tracking.Constants = 
{
	SEARCH_QUERY_PARAM : 'q'
}
current.tracking.Events = 
{
	SEARCH : 'event1',
	PAGE_VIEW : 'event2',
	REGISTRATION : 'event3',
	AD_IMPRESSION : 'event4',
	AD_CLICK : 'event5',
	AB_OPT_OUT : 'event7',
	COMMENT_SUBMITTED : 'event8',
	EMBED_FOCUS : 'event10',
	INVITE_SEND : 'event11',
	INVITE_SIGNUP : 'event12',
	CONTENT_ADD : 'event13',
	CONTENT_SHARE : 'event14',
	CONTENT_VOTE : 'event15',
	// event16-19 used by the Flash player during play
	// to track start, percentage complete, and total duration of video
	MESSAGE_SENT : 'event20',
	// event21 used by the Flash player on start
	THREADED_COMMENTS_EXPAND : 'event22',
	BLADE_OPEN : 'event23',
	GROUP_CREATE : 'event24',
	GROUP_JOIN : 'event25'
};
current.tracking.Conversion =
{
	AD_CLICK : 'eVar15',
	USER_CONTENT_TITLE : 'eVar20',
	USER_MEMBER : 'eVar25',
	HOMEPAGE_AD_TEST : 'eVar10'
};
current.tracking.internal = {};
current.tracking.internal.Track =
{
	_getInlineTime : function ()
	{
		if (document.currentTrackingClientStartTime && document.currentTrackingClientEndTime)
		{
			return (document.currentTrackingClientEndTime - document.currentTrackingClientStartTime);
		}
		return '';
	},
	_getAbortTime : function ()
	{
		if (document.currentTrackingClientStartTime && document.currentTrackingAbortTime)
		{
			return (document.currentTrackingAbortTime - document.currentTrackingClientStartTime);
		}
		return '';
	},
	_getDomReadyTime : function ()
	{
		if (document.currentTrackingClientStartTime && document.currentTrackingDomReadyTime)
		{
			return (document.currentTrackingDomReadyTime - document.currentTrackingClientStartTime);
		}
		return '';
	},
	_getPageLoadTime : function ()
	{
		if (document.currentTrackingClientStartTime && document.currentTrackingPageLoadTime)
		{
			return (document.currentTrackingPageLoadTime - document.currentTrackingClientStartTime);
		}
		return '';
	},
	_getRequestTime : function ()
	{
		if (document.currentTrackingRequestTime)
		{
			return document.currentTrackingRequestTime;
		}
		return '';
	},
	_getSearchTrackArgs : function (p)
	{
		var searchTrack = '&keyword='+p.getSearchQuery()+'&key1='+p.getSearchResultCount();
		var userFilter = p.getSearchUserFilter();
		var groupFilter = p.getSearchGroupFilter();
		if (!userFilter.empty())
		{
			searchTrack = searchTrack + '&key2='+ userFilter;
		}
		if (!groupFilter.empty())
		{
			searchTrack = searchTrack + '&key3='+groupFilter;
		}
		return searchTrack;
	},
	_getItemTrackArgs : function (p, eventType)
	{
		var m = current.tracking.internal.EventTypeMap;
		var type = p.getType();
		var itemTrack = '&key1='+type;
		// duplicates logic in _assetDisplayLarge.php to determine whether this 
		// uses our video player.  if so, return video plays instead of page views.
		if (eventType == m.PAGE_LOADED)
		{
			// bug 21969 - for now, just do this for pod and we'll investigate others once asset type changes
			if (type == 'pod') // (type == 'webcam' || type == 'pod' || type == 'vc2' || type == 'videoegg' || type == 'upload')
			{
				itemTrack += '&retEventTypes='+encodeURIComponent(m.ONSITE_PLAYER_START+','+m.OFFSITE_PLAYER_START);
			}
		}
		return itemTrack;
	},
	doViewTrack : function (p, objType, eventType, retCount)
	{
		var id = p.getId();
		var node = $('viewDisplay');
		var args = '';
		if (document.referrer && document.referrer != "")
		{
			args += '&referer=' + encodeURIComponent(document.referrer);
		}
		var clickPosition = getCookieValue(current.Cookies.CLICK_MAP);
		deleteCookie(current.Cookies.CLICK_MAP);
		if (clickPosition)
		{
			args += '&refererName=' + clickPosition;
		}
		args += '&requestTime=' + this._getRequestTime();
		args += '&inlineTime=' + this._getInlineTime();
		args += '&abortTime=' + this._getAbortTime();
		args += '&domReadyTime=' + this._getDomReadyTime();
		args += '&clientTime=' + this._getPageLoadTime();
		if (objType == 1)
		{
			args += this._getItemTrackArgs(p, eventType);
		}
		else if (objType == 8)
		{
			args += this._getSearchTrackArgs(p);
		}
		var handler = null;
		if (retCount && node)
		{
			handler = current.tracking.internal.Track.__onViewUpdate;
		}
		else
		{
			args += '&img=1';
		}
		new Ajax.Request(current.Constants.getInstance().getTrackingAppPath()
			+ '?objectType=' + objType 
			+ '&objectId=' + id 
			+ '&eventType=' + eventType 
			+ '&url=' + encodeURIComponent(current.site.Page.getInstance().getUrl())
			+ "&sessionId=" + current.User.getInstance().getSessionId() 
			+ args,
		{
			method : 'get',
			onSuccess : handler
		});
	},
	__onViewUpdate : function (data)
	{
		var node = $('viewDisplay');
		if (node)
		{
			var vCount = data.responseText;
			node.setOpacity(0);
			node.update(current.utils.Strings.addCommas(vCount)+' '+current.locale.Bundle.get('views'));
			node.setStyle({visibility: 'visible'});
			new Effect.Opacity(node, {to: 1, duration: 0.5});
		}
	}
};
current.tracking.internal.EventTypeMap =
{
	HTML_START : 50,
	JS_START : 51,
	PAGE_LOADED : 1,
	JS_END : 52,
	ONSITE_PLAYER_LOAD : 31,
	ONSITE_PLAYER_START : 3,
	ONSITE_PLAYER_ADS : 32,
	OFFSITE_PLAYER_LOAD : 21,
	OFFSITE_PLAYER_START : 2,
	OFFSITE_PLAYER_ADS : 22
};
current.tracking.internal.PageTypeMap = $H(
{
	'default' : 0,
	'item' : 1,
	'people:profile' : 2,
	'group' : 10,
	'tag' : 11,
	'toolbar' : 12,
	'homepage' : 4,
	'homepage:uploads:popular' : 5,
	'homepage:uploads:newest' : 5,
	'homepage:ads:popular' : 6,
	'homepage:ads:newest' : 6,
	'homepage:tvs:popular' : 7,
	'homepage:tvs:newest' : 7,
	'search' : 8
});