/* Event handlers */
var gigyaAnalytics = {
	// Generic event that logs to analytics API.
	trackEvent: function(category, action, label, value)
	{
		//console.log("Event tracked: " + category + ", " + action + ", " + label + ", " + value);

		if(typeof _gaq != "undefined")
		{
			_gaq.push(['_trackEvent', category, action, label, value]);
		}
	},
	
	// Generic visit-level variable.
	trackIsSSOUser: function(isSSOUser)
	{
		//console.log("'Is SSO User' set to: " + isSSOUser);
		
		if(typeof _gaq != "undefined")
		{
			_gaq.push(['_setCustomVar', 1, "Is SSO User", (isSSOUser ? "yes" : "no"), 1]);
		}
	},
	
	// Triggered when the authentication window is opened to login.
	onLoginAttempted: function(e)
	{
		if(e.provider)
		{
			var provider = e.provider.ucwords();
			gigyaAnalytics.trackEvent("Gigya SSO", provider + " Login Attempted", document.title);
		}
	},
	// Triggered when a login successfully completes.
	onLoginCompleted: function(e)
	{
		if(e.provider)
		{
			var provider = e.provider.ucwords();
			gigyaAnalytics.trackEvent("Gigya SSO", provider + " Login Completed", document.title);
			
			if(provider != "Site")
			{
				gigyaAnalytics.trackIsSSOUser(true);
			}
			else
			{
				gigyaAnalytics.trackIsSSOUser(false);
			}
		}
	},
	
	// Triggered when the authentication window is opened to add a connection.
	onConnectionAttempted: function(e)
	{
		if(e.provider)
		{
			var provider = e.provider.ucwords();
			gigyaAnalytics.trackEvent("Gigya SSO", provider + " Connection Attempted", document.title);
		}
	},
	// Triggered when a new connection is added.
	onConnectionCompleted: function(e)
	{
		if(e.provider)
		{
			var provider = e.provider.ucwords();
			gigyaAnalytics.trackEvent("Gigya SSO", provider + " Connection Completed", document.title);
		}
	},
	// Triggered when a connection is removed.
	onDisconnect: function(e)
	{
		if(e.provider)
		{
			var provider = e.provider.ucwords();
			gigyaAnalytics.trackEvent("Gigya SSO", provider + " Disconnect", document.title);
		}
	},
	
	// Triggered on logout.
	onLogout: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya SSO", "Logout", document.title);
	},
	
	// Triggered when the Share UI oeens in a lightbox.
	onShareUILightboxOpened: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Share UI", "Lightbox Opened", document.title);
	},
	// Triggered when a share from the Share UI is published.
	onShareUIPublished: function(e)
	{
		if(e.providers)
		{
			var providers = e.providers.split(",");
			for(i = 0; i < providers.length; i++)
			{
				var provider = providers[i].ucwords();
				gigyaAnalytics.trackEvent("Gigya Share UI", provider + " Share Published", document.title);
			}
		}
	},
	
	// Triggered when a reaction button is clicked (but not when it is un-clicked).
	onReactionClicked: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Reactions", e.reaction.text + " Clicked", document.title);
	},
	// Triggered when a share is published via reactions.
	onReactionPublished: function(e)
	{
		if(e.providers)
		{
			var providers = e.providers.split(",");
			for(i = 0; i < providers.length; i++)
			{
				var provider = providers[i].ucwords();
				gigyaAnalytics.trackEvent("Gigya Reactions", provider + " Share Published", document.title);
			}
		}
	},
	
	// Triggered when a comment is published.
	onCommentPublished: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Commenting", "Published", document.title);
		if(e.providers)
		{
			var providers = e.providers.split(",");
			for(i = 0; i < providers.length; i++)
			{
				var provider = providers[i].ucwords();
				gigyaAnalytics.trackEvent("Gigya Commenting", provider + " Share Published", document.title);
			}
		}
	},
	
	// Triggered when a review is published.
	onReviewPublished: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Ratings & Reviews", "Published", document.title);
		if(e.providers)
		{
			var providers = e.providers.split(",");
			for(i = 0; i < providers.length; i++)
			{
				var provider = providers[i].ucwords();
				gigyaAnalytics.trackEvent("Gigya Ratings & Reviews", provider + " Share Published", document.title);
			}
		}
	},
	
	// Triggered when Facebook Like is clicked.
	onFacebookLikeClicked: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Share Bar", "Facebook Like Clicked", document.title);
	},
	
	// Triggered when Google +1 is clicked.
	onGooglePlusOneClicked: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Share Bar", "Google +1 Clicked", document.title);
	},
	
	// Triggered when Twitter Tweet is clicked.
	onTwitterTweetClicked: function(e)
	{
		gigyaAnalytics.trackEvent("Gigya Share Bar", "Tweet Shared", document.title);
	},
	
	// Triggered when a bookmark window is launched.
	onBookmarkWindowLaunched: function(e)
	{
		var provider = e.provider.ucwords();
		gigyaAnalytics.trackEvent("Gigya Share Bar", provider + " Bookmark Shared", document.title);
	}
};

/** Bind events to the handlers defined above. */

// Bind events that are available via the API.
gigya.services.socialize.addEventHandlers({
	listenerType: "component"
}, {
	listenerDescription: "Listener for Gigya analytics plugin",
	onLogout: gigyaAnalytics.onLogout,
	onLogin: gigyaAnalytics.onLoginCompleted,
	onConnect: gigyaAnalytics.onConnectionCompleted,
	onDisconnect: gigyaAnalytics.onDisconnect
});

// Bind events by writing over core Gigya socialize methods.
var gigyaReflection = {
	/*global: {
		generateEvent: gigya.global.generateEvent
	},*/
	services: {
		socialize: {
			//_dispatchGlobalEvent: gigya.services.socialize._dispatchGlobalEvent,
			showShareUI: gigya.services.socialize.showShareUI,
			showReactionsBarUI: gigya.services.socialize.showReactionsBarUI,
			showCommentsUI: gigya.services.socialize.showCommentsUI,
			showShareBarUI: gigya.services.socialize.showShareBarUI,
			postBookmark: gigya.services.socialize.postBookmark
		}
	}
};
/*
// Tapping into generateEvent allows us to detect when the login and addConnection authentication windows are opened.
gigya.global.generateEvent = function(event, APIKey, cid, source, sourceData, params)
{
	// Track when the login window is opened.
	if(event == "login")
	{
		gigyaAnalytics.onLoginAttempted({
			cid: cid,
			source: source,
			provider: params.sn
		});
	}
	else if(event == "addConnection")
	{
		gigyaAnalytics.onConnectionAttempted({
			cid: cid,
			source: source,
			provider: params.sn
		});
	}
	
	//console.log({event: event, APIKey: APIKey, cid: cid, source: source, sourceData: sourceData, params: params});
	gigyaReflection.global.generateEvent(event, APIKey, cid, source, sourceData, params);
};
*/
// Tapping into showShareUI allows us to detect when shares complete via the shareUI and when the lightbox is opened.
gigya.services.socialize.showShareUI = function()
{
	var p = gigya.utils.object.merge([gigya._vars.globalConf, arguments]);

	var isAdvancedShare = !(p.operationMode == "simpleshare" || (p.operationMode == "autodetect" && !gigya.services.socialize.canSendRequest(p)));
	var isLightbox = (p.containerID == null);
	
	if(isAdvancedShare)
	{
		// Track send done if is advanced share.
		var onShareUIPublished = p.onSendDone;
		p.onSendDone = function(e)
		{
			if(!e.cid) e.cid = p.cid;
			gigyaAnalytics.onShareUIPublished(e);
			if(onShareUIPublished) onShareUIPublished(e);
		};
	
		if(isLightbox)
		{
			// Track open if is lightbox & advanced share.
			var onShareUILightboxOpened = p.onLoad;
			p.onLoad = function(e)
			{
				if(!e.cid) e.cid = p.cid;
				gigyaAnalytics.onShareUILightboxOpened(e);
				if(onShareUILightboxOpened) onShareUILightboxOpened(e);
			};
		}
	}
	
	gigyaReflection.services.socialize.showShareUI(p);
}

// Tapping into the showReactionsBarUI allows us to detect when reactions are clicked and published.
gigya.services.socialize.showReactionsBarUI = function()
{
	var p = gigya.utils.object.merge([gigya._vars.globalConf, arguments]);

	var onReactionClicked = p.onReactionClicked;
	p.onReactionClicked = function(e)
	{
		if(!e.cid) e.cid = p.cid;
		gigyaAnalytics.onReactionClicked(e);
		if(onReactionClicked) onReactionClicked(e);
	};
	
	var onReactionPublished = p.onSendDone;
	p.onSendDone = function(e)
	{
		if(!e.cid) e.cid = p.cid;
		gigyaAnalytics.onReactionPublished(e);
		if(onReactionPublished) onReactionPublished(e);
	};
	
	gigyaReflection.services.socialize.showReactionsBarUI(p);
};

// Tapping into the showCommentsUI allows us to detect when comments are published.
gigya.services.socialize.showCommentsUI = function()
{
	var p = gigya.utils.object.merge([gigya._vars.globalConf, arguments]);

	var onCommentPublished = p.onCommentSubmitted;
	p.onCommentSubmitted = function(e)
	{
		if(!e.cid) e.cid = p.cid;
		gigyaAnalytics.onCommentPublished(e);
		if(onCommentPublished) onCommentPublished(e);
	};
	
	gigyaReflection.services.socialize.showCommentsUI(p);
};

// Tapping into the showShareBarUI allows us to detect when simple share is launched,
// when Facebook Like is clicked, Google +1 is clicked or Twitter Tweet is clicked.
gigya.services.socialize.showShareBarUI = function(p)
{
	var p = gigya.utils.object.merge([gigya._vars.globalConf, arguments]);

	var onSendDone = p.onSendDone;
	p.onSendDone = function(e)
	{
		if(e.providers == "twitter-tweet")
		{
			gigyaAnalytics.onTwitterTweetClicked(e);
		}
		else if(e.providers == "facebook-like")
		{
			gigyaAnalytics.onFacebookLikeClicked(e);
		}
		else if(e.providers == "google-plusone")
		{
			gigyaAnalytics.onGooglePlusOneClicked(e);
		}
		if(onSendDone) onSendDone(e);
	};
	
	gigyaReflection.services.socialize.showShareBarUI(p);
};

// Tapping into postBookmark allows us to see when the postBookmark screen is launched.
gigya.services.socialize.postBookmark = function(p)
{
	var p = gigya.utils.object.merge([gigya._vars.globalConf, arguments]);
	gigyaAnalytics.onBookmarkWindowLaunched(p);
	gigyaReflection.services.socialize.postBookmark(p);
};

String.prototype.ucwords = function()
{
	return (this + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
		return $1.toUpperCase();
	});
};
