// Copyright 2011 Google Inc. All Rights Reserved.

/**
 * @fileoverview A simple script to automatically track Facebook and Twitter
 * buttons using Google Analytics social tracking feature.
 * @author api.nickm@google.com (Nick Mihailovski)
 */


/**
 * Namespace.
 * 
 * @type {Object}.
 */
var _ga = _ga || {};


/**
 * Ensure global _gaq Google Anlaytics queue has be initialized.
 * 
 * @type {Array}
 */
var _gaq = _gaq || [];

/**
 * Helper method to track social features. This assumes all the social
 * scripts / apis are loaded synchronously. If they are loaded async,
 * you might need to add the network specific tracking call to the
 * a callback once the network's script has loaded. 
 * 
 * @param {String} pageUrl An optional URL to associate the social tracking with a particular page.
 */
_ga.trackSocial = function( pageUrl ) {
	_ga.trackFacebook( pageUrl, 'facebook');
	_ga.trackTwitter( pageUrl, 'twitter');
	_ga.trackVkontakte( pageUrl, 'vkontakte');  
};


/**
 * Tracks Facebook likes, unlikes and sends by suscribing to the Facebook
 * JSAPI event model. Note: This will not track facebook buttons using the iFrame method.
 * 
 * @param {String} pageUrl An optional URL to associate the social tracking with a particular page.
 * @param {String} trackerName An optional name for the tracker object.
 */
_ga.trackFacebook = function( pageUrl, trackerName ) {
	try 
	{
		if ( FB && FB.Event && FB.Event.subscribe ) 
		{
			FB.Event.subscribe('edge.create', function( targetUrl ) {
				_gaq.push( ['_trackSocial', trackerName, 'like', targetUrl, pageUrl] );
			});
			FB.Event.subscribe('edge.remove', function( targetUrl ) {
				_gaq.push( ['_trackSocial', trackerName, 'unlike', targetUrl, pageUrl] );
			});
			FB.Event.subscribe('message.send', function( targetUrl ) { 
				_gaq.push( ['_trackSocial', trackerName, 'send', targetUrl, pageUrl] );
			});
		}
	} catch (e) {}
};

/**
 * Track vKontakte Share button.
 * 
 * @param {String} pageUrl An optional URL to associate the social tracking with a particular page.
 * @param {String} trackerName An optional name for the tracker object.
 */
_ga.trackVkontakte = function( pageUrl, trackerName ) {
	try 
	{
		if ( VK && VK.Share && VK.Share.click ) 
		{
			var targetUrl; // Default value is undefined.
			
			var oldShareClick = VK.Share.click;
			VK.Share.click = function( index, el ) {
				_gaq.push( ['_trackSocial', trackerName, 'share', targetUrl, pageUrl] );
				
				return oldShareClick.call( VK.Share, index, el );
			};
		}
	} catch (e) {}
}

/**
 * Tracks everytime a user clicks on a tweet button from Twitter.
 * This subscribes to the Twitter JS API event mechanism to listen for
 * clicks coming from this page. Details here:
 * http://dev.twitter.com/pages/intents-events#click
 * This method should be called once the twitter API has loaded.
 * 
 * @param {String} pageUrl An optional URL to associate the social tracking with a particular page.
 * @param {String} trackerName An optional name for the tracker object.
 */
_ga.trackTwitter = function( pageUrl, trackerName ) {
	try 
	{
		if ( twttr && twttr.events && twttr.events.bind ) 
		{
			twttr.events.bind( 'tweet', function( event ) {
				if ( event ) 
				{
					var targetUrl; // Default value is undefined.
					if ( event.target && event.target.nodeName == 'IFRAME' ) 
					{
						targetUrl = _ga.extractParamFromUri( event.target.src, 'url' );
					}
					_gaq.push( ['_trackSocial', trackerName, 'tweet', targetUrl, pageUrl] );
				}
			});
		}
	} catch (e) {}
};


/**
 * Extracts a query parameter value from a URI.
 * 
 * @param {String} uri The URI from which to extract the parameter.
 * @param {String} paramName The name of the query paramater to extract.
 * 
 * @return {String} The un-encoded value of the query paramater. underfined if there is no URI parameter.
 */
_ga.extractParamFromUri = function( uri, paramName ) 
{
	if ( !uri ) 
	{
		return;
	}
	var uri = uri.split( '#' )[0];  // Remove anchor.
	var parts = uri.split( '?' );  // Check for query params.
	if ( parts.length == 1 ) 
	{
		return;
	}
	var query = decodeURI( parts[1] );

	// Find url param.
	paramName += '=';
	var params = query.split( '&' );
	for ( var i = 0, param; param = params[i]; ++i ) 
	{
		if ( param.indexOf( paramName ) === 0 ) 
		{
			return unescape( param.split('=')[1] );
		}
	}
	return;
};
