
var Share =  function(options){
	var SHARE_START_BUTTON = 'share_start_button';
	var SHARE_EMBED_CONT = 'share_embed';
	var SHARE_EMBED_TEXT = 'share_embed_text';
	var SHARE_EMBED_COPY_BUTTON = 'share_embed_copy_button';
	var _elencoShare = [];
	var _copyLabel = '';
	var _addTo = [];
	var _copyButtonLabel = '';
	var _label = '';
	var _labelAlt = '';
	
	var _heightTextArea = 29;
	var _boxHeight = 32;
	var _pageName = '';
	var _marginX = 0;
	var _imgPath = '';
	var _shareBox = null;
	var _tooltipImagePath = '';
	var _countShare = 0;
	
  function stringFormat(text){
		if (arguments.length <= 1)				
			return text;
		var tokenNum = arguments.length - 2;
		for( var i = 0; i <= tokenNum; i++ )
			text = text.replace(new RegExp("\\{" + i + "\\}", "gi"), arguments[i + 1]);
		return text;
	}
	
	function $(id){
		return document.getElementById(id);
	}
	
	function getNewId() {
		return _countShare++;
	}
	
	var ShareItem = function(opt){
		this.url = opt.URL;
		this.itemTitle = opt.ITEM_TITLE;    
		var idShareEmbedCont = SHARE_EMBED_CONT + opt.CONTAINER;
		var idShareEmbedText = SHARE_EMBED_TEXT + opt.CONTAINER;
		var idShareEmbedCopyButton = SHARE_EMBED_COPY_BUTTON + opt.CONTAINER;
		var idShareStartButton = SHARE_START_BUTTON + opt.CONTAINER;	
		var id = 'share_' + getNewId();
		var embedText = '';
		var _isEmbedToBlog = false;
						
		function offset(elem) {
			var mOffsetLeft = elem.offsetLeft;
			var mOffsetParent = elem.offsetParent;
			
			while (mOffsetParent) {
				mOffsetLeft += mOffsetParent.offsetLeft;
				mOffsetParent = mOffsetParent.offsetParent;				
			}	
			
			var mOffsetTop = elem.offsetTop;
			mOffsetParent = elem.offsetParent;
			
			while (mOffsetParent) {
				mOffsetTop += mOffsetParent.offsetTop;
				mOffsetParent = mOffsetParent.offsetParent;				
			}				
			
			return {x: mOffsetLeft, y: mOffsetTop};		
		}		
		
		function show() {
			var pos = offset(document.getElementById(idShareStartButton)); 				
      _shareBox.show(pos.x - 50, pos.y - 17 - _boxHeight);
		};
		
		function createButton(conf) {
			var btn = document.createElement('a');
			btn.href = 'javascript:void(0);';
			btn.className = conf.className;
			btn.onclick = conf.onclick;
			btn.innerHTML = conf.label;
			return btn;		
		}
		
		function _init(){
  		var cont = $(opt.CONTAINER);
  		if (!cont) 
				return;
			if (opt.PRE_ACTION != null) {
				opt.PRE_ACTION();
			}
			if (opt.EMBED_TO_BLOG != null) {
				embedText = opt.EMBED_TO_BLOG;
			}
			
  		var htmlTips = ['<div class="bookmarks"><div class="list">'];
			
  		var linkPattern = '<a href="javascript:void(0);" class="{0}" onclick="shareObj.addTo(\'{1}\',\'{2}\');">{3}{4}</a>';
			
			_isEmbedToBlog = false;
  		for (var i = 0; i < _addTo.length; i++) {
  			var conf = ShareManager.configuration().get(_addTo[i].id);
  			var arrow = '';				
  			if (_addTo[i].id == "embedtoblog") {
					arrow = ' <img class="arrow" src="' + _imgPath + 'yoox80/layout/share/arrow.gif" />';
					_isEmbedToBlog = true;
				}
				htmlTips.push(stringFormat(linkPattern, conf.className, id, _addTo[i].id, _addTo[i].label, arrow));				
  		}			
						
  		htmlTips.push('</div>');
  		if (_isEmbedToBlog) {
    		htmlTips.push('<div id="', idShareEmbedCont, '" class="embed"><p>',_copyLabel,'</p><textarea id="', idShareEmbedText,'" style="height: ', _heightTextArea,'px"></textarea>',
  										'<a href="javascript:void(0);" id="',idShareEmbedCopyButton,'" class="button" onclick="shareObj.copy(\'',id,'\');">', _copyButtonLabel, '</a>',
  										'<div class="clear"></div></div>');			
			}									
  		htmlTips.push('</div>');
						
  		htmlTips = htmlTips.join('');
  		var share = document.createElement('div');
  		share.className = 'share';
			share.id = idShareStartButton;
  		share.title = _labelAlt;
			var shareBtn = createButton({className: 'start', onclick: show, label: _label});
			share.appendChild(shareBtn);
			opt.POSITION = opt.POSITION == null ? 'last' : opt.POSITION;
			if (opt.POSITION == 'first') {
				cont.insertBefore(share,cont.firstChild);
			}
			else {
  			cont.appendChild(share);
			}
      _shareBox = Tooltip.Box({body: htmlTips});				
		};

		this.getId = function(){
			return id;
		};
		
		this.addTo = function(tipoAdd) {		
			var conf = ShareManager.configuration().get(tipoAdd);
						
			if (conf.action) {
				/*if (_isEmbedToBlog) {
	  			Element.setStyle(idShareEmbedCont, {display: 'none'});
				}*/
  			conf.action(this);
			}
			pageTracker._trackEvent('Share', 'yooxer', tipoAdd);		
  	};
		
		this.copy = function() {
  		var txt = $(idShareEmbedText);
			txt.focus();
			txt.select();
			var r = txt.createTextRange();
			r.select();
  		r.execCommand('Copy');
		}		
		
		_init();
		return this;
	};
	
	function initialize(options) {
    _label = options.LABEL;
    _labelAlt = options.LABEL_ALT == null ? options.LABEL : options.LABEL_ALT;
    _copyLabel = options.COPY_LABEL;
    _copyButtonLabel = options.COPY_BUTTON_LABEL;
    _pageName = options.PAGE_NAME;
    _addTo = options.ADD_TO;
		_imgPath = options.IMG_PATH;
		_tooltipImagePath = options.TOOLTIP_IMG_PATH == null ? options.IMG_PATH : options.TOOLTIP_IMG_PATH;
		
    if (_addTo.length > 3) { /*adatta l'altezza in base al numero di link*/
  	  _heightTextArea += (_addTo.length - 3) * 20;
    }
    _boxHeight += _addTo.length * 20;
				
    if (options.MARGIN_X != null) {
	    _marginX = options.MARGIN_X;
    }
		
  	for (var i = 0; i < options.ITEMS_CONF.length; i++) {
  		var opt = options.ITEMS_CONF[i];
  		opt.POSITION = options.POSITION;
  		var si = new ShareItem(opt);
  		_elencoShare[si.getId()] = si;
  	}		
 	};
	
	this.addTo = function(id,tipoAdd) {
		_elencoShare[id].addTo(tipoAdd);
	};
	this.copy = function(id) {
		_elencoShare[id].copy();		
	};
	
	initialize(options);
	
	return this;
};

var shareObj = null;
/* intialize shareObj with json object */
var ShareManager = function() {
  var Config = function(){
  	var _elenco = [];
		var winPopup = null;
		
		function action(o,conf) {
      var U = o.url;
      var T = o.itemTitle + ' - The New Yooxer';
      var url = conf.getUrl(U,T);
			if (winPopup != null) {
				try {
					winPopup.close();
				}catch(e){}
			}                      				
      winPopup = window.open(url, 'sharer', 'resizable=1,toolbar=0,status=0,width=' + conf.width + ',height=' + conf.height + ',scrollbars=' + conf.scrollbars);
      winPopup.focus(); 		
		}
		
		function generateAction(param){
			var conf = {};
			conf.getUrl = param.getUrl;
			conf.width = param.width == null ? 640 : param.width;
			conf.height = param.height == null ? 480 : param.height;
			conf.scrollbars = param.scrollbars == null ? 1 : param.scrollbars;
			conf.tp = param.tp;									
			return function(o) {action(o,conf);};
		}		
		
  	return {
  		add: function(key,param){
				if (param.win) {
					param.action = generateAction(param.win)
				}
  			_elenco[""+key] = param;
  		},
  		get: function(key){
  			return _elenco[""+key];		
  		}
  	}
  };
	var conf = new Config();
	var _itemsConf = [];
	
	function addItem(itemConf) {
		_itemsConf[_itemsConf.length] = itemConf;	
	}
	
	return {
		addItem: function(itemConf){
			addItem(itemConf);
		},
		configuration: function(){
			return conf;
		},
  	process: function(){
  		if (typeof(jsinit_share)=='undefined') {
  			return;	
			}
			if (jsinit_share.ITEM) {
				addItem(jsinit_share.ITEM);
			}
			jsinit_share.ITEMS_CONF = _itemsConf;
  		shareObj = new Share(jsinit_share);
  	}
	}
}();


if (window.addEventListener) {
	window.addEventListener('load', ShareManager.process, false); 
}
else {
	window.attachEvent("onload", ShareManager.process);
}


ShareManager.configuration().add('myspace', {className: 'myspace', 
														win: {getUrl: function(U,T){
                                      var L = 3;                      	
                                      return 'http://www.myspace.com/index.cfm?fuseaction=postto&t=' + encodeURIComponent(T) + '&u=' + encodeURIComponent(U.replace(/\?/,'/').replace(/&|=/gi,'/')) + '&l=' + L;
      															}, width: 800, tp: '16904'                     
  	                         			}
														 });
ShareManager.configuration().add('facebook', {className: 'facebook', 
														win: {getUrl: function(U,T){
																			return 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(U) + '&t='+encodeURIComponent(T);
      															}, scrollbars: 0, tp: '16905'                    
  	                         			}  
														 });
ShareManager.configuration().add('twitter', {className: 'twitter', 
														win: {getUrl: function(U,T){
																			U += (U.indexOf('?') > 0 ? '&' : '?');
																			return 'http://twitter.com/home?status=' + encodeURIComponent(U + 't\n' + T);
      															}, width: 800, tp: '16906'                      
  	                         			}
														 });
ShareManager.configuration().add('digg', {className: 'digg', 
														win: {getUrl: function(U,T){
																			return 'http://digg.com/submit?url=' + encodeURIComponent(U) + '&title=' + encodeURIComponent(T) + '&topic=TOPIC';
      															}, width: 950                      
  	                         			}    
														 });
ShareManager.configuration().add('live', {className: 'live', 
														win: {getUrl: function(U,T){
																			return 'https://skydrive.live.com/sharefavorite.aspx%2f.SharedFavorites??&mkt=en-us&url=' + encodeURIComponent(U) + '&title=' + encodeURIComponent(T) + '&top=1';
      															}                    
  	                         			}
														 });
ShareManager.configuration().add('friendfeed', {className: 'friendfeed', 
														win: {getUrl: function(U,T){
																			return 'http://friendfeed.com/?url=' + encodeURIComponent(U) + '&title=' + encodeURIComponent(T);
      															}, width: 950, tp: '16907'                    
  	                         			}
														 });
ShareManager.configuration().add('delicious', {className: 'delicious', 
														win: {getUrl: function(U,T){
																			return 'http://delicious.com/save?url=' + encodeURIComponent(U) + '&title=' + encodeURIComponent(T) + '&notes=&tags=&v=4&noui=&share=yes&jump=close';
      															}, width: 850, tp: '16908'                    
  	                         			}
														 });
ShareManager.configuration().add('google', {className: 'google', 
														win: {getUrl: function(U,T){
																			return 'http://www.google.com/bookmarks/mark?op=add&nui=1&service=bookmarks&bkmk=' + encodeURIComponent(U)+'&title='+encodeURIComponent(T);
      															}, width: 700                     
  	                         			}
														 });
ShareManager.configuration().add('embedtoblog', {className:'embedtoblog'});
