/*
 * Easy Retweet Button
 * http://ejohn.org/blog/retweet/
 *   by John Resig (ejohn.org)
 *
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */

(function(){

window.RetweetJS = {
	// Your Bit.ly Username
	bitly_user: "startphilly",

	// Your Bit.ly API Key
	// Found here: http://bit.ly/account
	bitly_key: "R_582fff86cc8ddb5e329f5fb663173984",

	// Tweet Prefix text
	// "RT @jeresig " would result in: "RT @jeresig Link Title http://bit.ly/asdf"
	prefix: "RT @startphilly "

};

//////////////// No Need to Configure Below Here ////////////////

var loadCount = 1;

// Asynchronously load the Bit.ly JavaScript API
// If it hasn't been loaded already
if ( typeof BitlyClient === "undefined" ) {
	var head = document.getElementsByTagName("head")[0] ||
		document.documentElement;
	var script = document.createElement("script");
	script.src = "http://bit.ly/javascript-api.js?version=latest&login=" +
		RetweetJS.bitly_user + "&apiKey=" + RetweetJS.bitly_key;
	script.charSet = "utf-8";
	head.appendChild( script );

	var check = setInterval(function(){
		if ( typeof BitlyCB !== "undefined" ) {
			clearInterval( check );
			head.removeChild( script );
			loaded();
		}
	}, 10);

	loadCount = 0;
}

if ( document.addEventListener ) {
	document.addEventListener("DOMContentLoaded", loaded, false);

} else if ( window.attachEvent ) {
	window.attachEvent("onload", loaded);
}

function loaded(){
	// Need to wait for doc ready and js ready
	if ( ++loadCount < 2 ) {
		return;
	}

	var elems = [], urlElem = {}, hashURL = {};

	BitlyCB.shortenResponse = function(data) {
		for ( var url in data.results ) {
			var hash = data.results[url].userHash;
			hashURL[hash] = url;

      url = url.replace(/\?.*$/, '');
			var elems = urlElem[ url ];

			$.each(elems, function() {
        $(this).children('div.share_buttons').children('a').each( function () {
				  $(this).attr('href', $(this).attr('href') + hash);
        });
			});

		}
	};

  share_title = function (service) {
    switch (service.toLowerCase()) {
      case 'twitter': return 'retweet';
      case 'digg': return 'digg it';
      case 'delicious': return 'bookmark on delicious';
      case 'reddit': return 'reddit this';
      case 'pingfm': return 'Ping this!';
      case 'email': return 'email this';
      default: null;
    }
  };

  share_url = function (service, origText, origExcerpt) {
    switch (service.toLowerCase()) {
      case 'linkedin': return "http://www.linkedin.com/shareArticle?mini=true&source=Start%20Philly&title=" +
                                encodeURIComponent(origText) + "&summary=" + encodeURIComponent(origExcerpt) + 
                                "&url=" + encodeURIComponent("http://bit.ly/");
      case 'twitter': return "http://twitter.com/home?status=" +
                                encodeURIComponent(RetweetJS.prefix + origText + " http://bit.ly/");
      case 'facebook': return "http://www.facebook.com/share.php?t=" + 
                                encodeURIComponent(origText) + "&u=" + encodeURIComponent("http://bit.ly/");
      case 'stumbleupon': return "http://www.stumbleupon.com/submit?title=" + 
                                encodeURIComponent(origText) + "&url=" + encodeURIComponent("http://bit.ly/");
      case 'digg': return "http://digg.com/submit?phase=2&title=" + 
                                encodeURIComponent(origText) +
                                "&bodytext=" + encodeURIComponent(origExcerpt) +
                                "&url=" + encodeURIComponent("http://bit.ly/");
      case 'delicious': return "http://delicious.com/post?title=" +
                                encodeURIComponent(origText) + 
                                "&notes=" + encodeURIComponent(origExcerpt) +
                                "&url=" + encodeURIComponent("http://bit.ly/");
      case 'pingfm': return "http://ping.fm/ref/?title=" + 
                                encodeURIComponent(origText) + 
                                "&body=" + encodeURIComponent(origExcerpt) +
                                "&link=" + encodeURIComponent("http://bit.ly/");
      case 'reddit': return "http://reddit.com/submit?title=" + 
                                encodeURIComponent(origText) + "&url=" + encodeURIComponent("http://bit.ly/");
      case 'tumblr': return "http://www.tumblr.com/share?v=3&t=" + 
                                encodeURIComponent(origText) + 
                                "&s=" + encodeURIComponent(origExcerpt) +
                                "&u=" + encodeURIComponent("http://bit.ly/");
      case 'email': return "mailto:?subject=Start Philly%3A%20" + 
                                encodeURIComponent(origText) + 
                                "&body=" + encodeURIComponent(origExcerpt) +
                                "%0D%0D" + encodeURIComponent("http://bit.ly/");
      default: null;
    }
  };
  var services = ['LinkedIn', 'twitter', 'facebook', 'StumbleUpon', 'digg',
                  'delicious', 'PingFM', 'Tumblr', 'email'];
  services.reverse();
  
  $(".shares > div > a.share").each( function() {
    var share = this;

    var origText    = share.textContent || share.innerText;
    var origExcerpt = share.title;
    var href     = share.href;
      
    var container = $(share).parent();
    $(share).remove();

    $.each(services, function() {
      var a = document.createElement('A');
      $(a).attr('title', (share_title(this) || "Share on " + this));
  
      var img = document.createElement('IMG');
      img.src = "/wp-content/themes/start-philly/img/share/" + this.toLowerCase() + ".png";

      $(a).append(img);
      
      var url = share_url(this, origText, origExcerpt);
      $(a).attr('href', url);

      $(container).prepend(a);
    });
    href = href.replace(/beta\./, '');
    if ( urlElem[ href ] ) {
      urlElem[ href ].push( $(container).parent() );
    } else {
      urlElem[ href ] = [ $(container).parent() ];
      BitlyClient.shorten(href+"?utm_source=share&utm_medium=button", 'BitlyCB.shortenResponse');
    }
	});

}

})();

