// JavaScript Document

window.onload = (function(){
  $('div.buttons')
    .append('<button data-href="http://www.google.com/buzz/post?url={$url}&message={$message}&imageurl={$image}" data-dimension="700x450">\
	  <img src="images/sociale/google.gif"> Buzz\
	</button><button data-href="http://profile.live.com/badge?url={$url}&title={$message}&screenshot={$image}" data-dimension="900x500">\
	  <img src="images/sociale/msn.gif" /> Messenger\
	</button><button data-href="http://twitter.com/share?url={$url}&text={$message}" data-dimension="550x300">\
	  <img src="images/sociale/twitter.gif" /> Twitter\
	</button><button data-href="http://www.facebook.com/sharer.php?u={$url}&t={$message}" data-dimension="550x300">\
	  <img src="images/sociale/facebook.gif" /> Facebook\
	</button>')
    .find('button')
    .click(function(){
	  var a = {
		url 	: window.location.href.replace(/[\(\)]/g,''),
		message	: document.title,
		image	: $('meta[name=image_src]').attr('content'),
		lang	: (window.navigator.browserLanguage||window.navigator.language)
	  };
	  var w=800,h=500,m;
	  if( $(this).attr('data-dimension') && ( m = $(this).attr('data-dimension').match(/[0-9]+/ig) ) ){
		w = m[0];
		h = m[1];
	  }
	  var l = (screen.width/2)-(w/2), t = (screen.height/2)-(h/2);
	  window.open( $(this).attr('data-href').replace(/([^\?\&\=]+)=\{\$(.*?)\}/ig, function(m,p1,p2){
	    if((p2 in a)&&!a[p2])
	    	return '';
		return p1+'='+((p2 in a)?encodeURIComponent(a[p2]):m);
	  }), 'buzz', 'width='+w+'px,height='+h+'px,left='+l+'px,top='+t+'px,resizeable,scrollbars,location=1');
  });
  var url = window.location.href.replace(/[\(\)]/g,'');

  // We can get the number of Buzz's from Google
  $.getJSON('http://www.google.com/buzz/api/buzzThis/buzzCounter?url='+encodeURIComponent(url)+'&callback=?', function(o){
  	$('div.buttons button[data-href*=google]').append(o[url]);
  });

  // And the number of FaceBooks
  $.getJSON('http://api.ak.facebook.com/restserver.php?v=1.0&method=links.getStats&urls=%5B%22'+ encodeURIComponent(url) +'%22%5D&format=json&callback=?', function(json){
  	$('div.buttons button[data-href*=facebook]').append(json[0].total_count);
  });

  // And the number of tweets
  // HAD Trouble with the twitter caching locally and failing to return the number of tweets.
  $.getJSON('http://urls.api.twitter.com/1/urls/count.json?url='+encodeURIComponent(url)+'&noncache='+Math.random()+'&callback=?', function(json){
  	$('div.buttons button[data-href*=twitter]').append(json.count);
  });

});
