/**
 * Methods used to aid in the tracking and interaction with third-party social sites
 * @author Ian Kennington Walter
 * @since 9/7/2011
 */

// Tracks user clicks on the Google Plus One button. This is necessary because our site-level tracking is name-spaced with www. (unlike SCP)
function trackGooglePlusOne(target) {
	if (target.state == "on") {
		_gaq.push(['global._trackSocial', 'Google', '+1', target.href]);
		_gaq.push(['www._trackSocial', 'Google', '+1', target.href]);
	} else if (target.state == "off") {
		_gaq.push(['global._trackSocial', 'Google', '-1', target.href]);
		_gaq.push(['www._trackSocial', 'Google', '-1', target.href]);
	}
}

// Tracks user clicks on the Facebook Share button.
function trackFbShare(targetUrl) {
	_gaq.push(['global._trackSocial', 'facebook', 'send', targetUrl]);
	_gaq.push(['www._trackSocial', 'facebook', 'send', targetUrl]);
}

// Tracks user clicks on the Twitter Share button.
function trackTweet(targetUrl) {
	_gaq.push(['global._trackSocial', 'twitter', 'tweet', targetUrl]);
	_gaq.push(['www._trackSocial', 'twitter', 'tweet', targetUrl]);
}

/**
 * Builds a tweet and triggers the pop up window
 * @param String canonicalUrl The URL-encoded canonical URL, used by twitter to count tweets
 * @param String refUrl The URL-encoded URL with tracking parameters attached (will be shortened)
 * @param String tweetText The text that will be tweeted
 * @param String related The URL-encoded name of a related twitter account that you can suggest the user follow after they tweet
 */
function buildTweet(twitterAccount, canonicalUrl, refUrl, tweetText, related) {
	var encodedCanonicalUrl = encodeURIComponent(canonicalUrl);
	var encodedRefUrl = getBitlyUrl(refUrl);
	var encodedTweetText = encodeURIComponent(tweetText);
	var encodedRelated = encodeURIComponent(related);
	// If the tweet text hasn't been specified then just use the page title
	if (encodedTweetText == '') {
		encodedTweetText = encodeURIComponent(document.title);
	}
	var twitterUrl = "http://twitter.com/share?via="+twitterAccount+"&url="+encodedRefUrl+"&text="+encodedTweetText+"&counturl="+encodedCanonicalUrl+"&related="+encodedRelated;
	var twitterShareWindow = window.open(twitterUrl,'newWindow','height=340,width=500,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=yes');
	trackTweet('<?php echo $canonicalUrl; ?>');
}

/**
 * Returns the generated Bit.ly short URL given a long URL. Using local PHP to make the request to avoid JSONP.
 * @requires jQuery
 * @param String longUrl The URL-encoded long URL
 * @return String bitlyUrl The generated Bit.ly short URL
 */
function getBitlyUrl(longUrl) {
	var refUrl = encodeURIComponent(longUrl);
	var requestUrl = '/global/php/social/getBitlyUrl.php?refUrl='+refUrl;
	$.ajax({
		async: false,
		url: requestUrl, 
		dataType: "json",
		success: function(response) {
			if (response.status_code == 200) {
				refUrl = encodeURIComponent(response.data.url);
			}
		}
	});
	return refUrl;
}
