/*
* jQuery Facebook plugin
* @author: Massimiliano Balestrieri
* @version: 2.0.0
*/
(function($) {

var Flags = {
  facebook: false,
  fbAsyncInit : false
};

var Fb = function(el,o){
	var that = el, _lang = 'it', _w = 70;
  
  if ($(that).data("fb")) {
    //console.log("già inizializzato");
    return;
  } else {
    $(that).data("fb", true);
  }
  
  var _o = {
    url : location.href,
  	SDK : '/' + '/connect.facebook.net/{lang}/all.js',
		url : location.href,
		app_id: '175749822474528',//TODO
		callback : function(href, widget){

		},
    like: {
      layout: 'box_count',
      showfaces: false,
      width: false
      //,
      //verb : 'like',
      //font : null,
      //colorscheme: null
    }
  };
  
  var _facebook = function() {
	  //singleton sul caricamento dello script - elemento obbligatorio #fb-root. anche twitter si potrebbe caricare solo alla presenza di un elemento
	  //bug su ie da ip locali : https://github.com/facebook/connect-js/issuesearch?state=open&q=ie8#issue/106
	  if (!Flags.facebook) {
		   Flags.facebook = true;
		   window.fbAsyncInit = function() {
				FB.init({appId: _o.SDK.app_id, status: true, cookie: true,	xfbml: true});
				//reset width - FB BUG
				FB.Event.subscribe('edge.remove', function(href, widget) {
			    setTimeout(function(){
			    	$(widget.dom).find("iframe").css("width", _w + "px");
			    },500);
			  });
			  FB.Event.subscribe('edge.create', function(href, widget) {
			    _o.callback(href, widget);
			  });
				Flags.fbAsyncInit = true;
			};
			
			(function() {
				$('html').attr('xmlns:fb','http://www.facebook.com/2008/fbml');
				$('body').prepend('<div id="fb-root" />');
				var e = document.createElement('script');
				e.async = true;
				e.src = document.location.protocol + _o.SDK.replace('{lang}', _o.uiculture);//location.protocol +
				document.getElementById('fb-root').appendChild(e);
			}());
		}
		if(Flags.fbAsyncInit){
			FB.XFBML.parse(that);
		}
		
	}
	, _getCultureInfo = function() {
	   return _lang.toLowerCase() + '_' + _lang.toUpperCase();
	};
	 //main
  $.extend(true, _o, o || {});
  _o.uiculture = _getCultureInfo();
  that.innerHTML = '<fb:like href="'+_o.url+'" layout="'+ _o.like.layout +'" show_faces="'+ _o.like.showfaces +'" width="'+ _w +'"/>';
  _facebook();
};

$.fn.fb = function(o) {
  return this.each(function(n) {
    new Fb(this, o);
  });
};

$(document).ready( function() {
	$('.fb-like').each(function(){
		$(this).fb({url : 'http://' + location.host + '/prodotto.php?id=' + this.id.replace("fb-","")});
	});
});

})(jQuery);
