if (!this.AG)
  AG = {};

AG.Sharing = Class.create({
	initialize: function(options) {
		var cont = $(options.container);
		if(!cont){
			cont = $(document.createElement('div'));
			document.body.appendChild(cont);
		}
		this.cont = cont;
		this.options = options;
		if(this.options.show_hide){
			Event.observe(cont, 'mouseover', this.cancel_delay.bindAsEventListener(this));
			Event.observe(cont, 'mouseout', this.delayed_hide.bindAsEventListener(this));
		}
		this.place();
		this.hide();
		this.content();
		this.add_to_list();
		if(typeof window.onresize == 'function'){
			var f1 = this.place.bind(this);
			var f2 = window.onresize;
			window.onresize = function(){  f2(); f1(); }
		}
		else{
			window.onresize = this.place.bind(this);
		}
	},
	add_to_list: function(){
		if( !AG.Sharing.hash ) AG.Sharing.hash = { };
		if( this.options.name ) AG.Sharing.hash[this.options.name] = this;
	}, 
	show: function(){
		this.cancel_delay();
		this.cont.show();
		$(this.options.name+'_button').show();
	},
	hide: function(){
		AG.Sharing.handler_collapse(this.options.name, 0);
		this.cont.hide();
	},
	place: function(){
		var options = this.options;
		var rel_to = $(options.relative_to);
		var left = Number(options.left);
		var right = Number(options.right);
		var top = Number(options.top);
		var bottom = Number(options.bottom);
		var pos = rel_to.cumulativeOffset();
		var dim = rel_to.getDimensions();
		var x = 0;
		var y = 0;
		if(right){
			x = pos.left + dim.width - right;
		}else{
			x = pos.left + left;
		}
		if(bottom){
			y = pos.top + dim.height - bottom;
		}else{
			y = pos.top + top;
		}
		this.cont.setStyle({ position: 'absolute', left: x+'px', top: y+'px' });
	},
	get_handler: function(i){
		return 'onclick="AG.Sharing.handler_click(\''+this.options.name+'\', '+i+', event)"';
	},
	button_content: function(){
		var html = '';
		var favour = this.get_favourite();
		if(!favour.length) favour = [0,1,2,3];
		for(var i=0;i<favour.length;i++){
			var item = AG.Sharing.serv_list[favour[i]];
			var style = 'style="background-position:-2px -'+Number(item.pos+2)+'px;"';
			var id = this.options.name+'_fav_'+Number(i+1);
			html += '<a href="'+this.get_wrapper_link(favour[i])+'" '+this.get_handler(favour[i])+' class="share_'+Number(i+1)+'" id='+id+' '+item.title+' '+style+'></a>'+"\n";
		}
		return html;
	},
	content: function(){
		var html = '';
		var id = this.options.name+'_button';
		html += '<div class=share_button id='+id+' onmouseover="this.style.opacity=\'1\';" onmouseout="this.style.opacity=\'0.7\';">'+"\n";
		html += '<div class=links id="'+this.options.name+'_button_links">'+"\n";
		html += this.button_content();
		html += '</div>';
		var panel_id = this.options.name+'_panel';
		html += [
			'<div class=open><img title="Другие варианты размещения" src=\'http://i.ag.ru/ag/i/share/share_button_dd.png\' onclick="AG.Sharing.handler_expand(\''+this.options.name+'\', event)"></div>',
			'</div>',
			'<div class=share_panel id='+panel_id+' onmouseout="AG.Sharing.handler_mouseout(\''+this.options.name+'\', event)" onmouseover="AG.Sharing.handler_mouseover(\''+this.options.name+'\', event)">',
			'<div class=s style="padding:8px 0 0 7px;cursor:pointer;margin:3px 3px 6px 3px;" title="Свернуть"  onclick="AG.Sharing.handler_collapse(\''+this.options.name+'\', event)">Сохраните/разместите ссылку</div>'
		].join("\n");
		for(var i=0; i<AG.Sharing.serv_list.length;i++){
			var item = AG.Sharing.serv_list[i];
			var style = 'style="background-position:0 -'+item.pos+'px"';
			html += '<a href="'+this.get_wrapper_link(i)+'" '+this.get_handler(i)+' class=share_a '+item.title+' '+style+'>'+item.name+'</a>'+"\n";
			if(item.id == 'vkontakte'){
				html += '<div id="'+this.options.name+'_vkontakte_count"></div>'+"\n";
			}
			if(item.id == 'facebook'){
				html += '<div id="'+this.options.name+'_facebook_count"></div>'+"\n";
			}
			if(item.id == 'moimir'){
				html += '<div id="'+this.options.name+'_moimir_count"></div>'+"\n";
			}
			if(item.id == 'google'){
				html += '<div id="'+this.options.name+'_google_count"></div>'+"\n";
			}
		}
		html += '<div id="'+this.options.name+'_fb_if"></div>';
		html += '<div id="'+this.options.name+'_gg_if"></div>';
		html += '</div>';
		this.cont.update(html);
	},
	get_favourite: function(){
		var coo = getCookie('sharing_favourite');
		if(!coo) return [0,1,2,3];
		return coo.split(',');
	},
	set_favourite: function(i){
		var fav = this.get_favourite();
		for(var c=0; c<fav.length; c++){
			if(fav[c] == i) return;
		}
		if(fav.length>3) fav.shift();
		if(fav.length<4) fav.push(i);
		setCookie('sharing_favourite', fav.join(','));
		$(this.options.name+'_button_links').update(this.button_content());
	},
	get_wrapper_link: function(i){
		if(AG.Sharing.serv_list[i].id == 'bookmark'){
			return 'http://www.ag.ru';
		}
		var base_url = 'http://www.ag.ru/share';
		var obj = this.options.object;
		return base_url+'/'+obj+'/'+AG.Sharing.serv_list[i].id;
	},
	run_wrapper: function(i){
		this.set_favourite(i);
		if( AG.Sharing.serv_list[i].id == 'bookmark' ){
			alert('Закройте это сообщение и нажмите Ctrl+D, чтобы добавить страницу в Избранное (Favorites) вашего браузера.');
		}else{
			var width = Number(AG.Sharing.serv_list[i].width);
			var height = Number(AG.Sharing.serv_list[i].height);
			var v_x = 0;
			var v_y = 0;
			if(window.screenX != undefined) v_x = window.screenX;
			if(window.screenLeft != undefined) v_x = window.screenLeft;
			if(window.screenY != undefined) v_y = window.screenY;
			if(window.screenTop != undefined) v_y = window.screenTop;
			
			document_height = function(){
				return (document.body.scrollHeight > document.body.offsetHeight)?document.body.scrollHeight:document.body.offsetHeight;
			};
			document_width = function(){
				return (document.body.scrollWidth > document.body.offsetWidth)?document.body.scrollWidth:document.body.offsetWidth;
			};
			
			var v_w = document_width();
			var v_h = document_height();
			var left = v_x + v_w / 2 - width / 2;
			var top = v_y + 150;
			var defset = 'menubar=no,location=no,scrollbars=yes';
			window.open(this.get_wrapper_link(i), '', defset+',width='+width+',height='+height+',left='+left+',top='+top);
		}
	},
	update_count: function(){
		var sh = this;
		
		// facebook
		if(!sh.options._count_fb){
			var cid_fb = this.options.name+"_facebook_count";
			var obj = new ag_server();
			obj.set_code("share");
			obj.set_param("url", this.options.object);
			obj.set_param("action", "count");
			obj.set_param("social", 'facebook');
			obj.on_load(function(o){
				if(o.get('result')){
					var count = o.get('count');
					var surl = o.get('surl');
					if(surl){
						var ifr = $(document.createElement('iframe'));
						ifr.setAttribute('src', '/?act=share&code=fb_if&surl='+surl);
						ifr.setAttribute("scrolling", 'no');
						ifr.setAttribute("frameborder", '0');
						ifr.setAttribute("allowTransparency", 'true');
						var left = 144;
						if(count > 9) left = 140;
						if(count > 99) left = 135;
						ifr.setStyle({ 
							zIndex: 100600,
							top: '-191px', 
							left: left+'px', 
							position: 'relative', 
							border: 'none', 
							overflow: 'hidden', 
							width: '50px', 
							height: '23px' 
						});
						$(sh.options.name+'_fb_if').appendChild(ifr);
					}
					var div = $(cid_fb);
					if(count){
						div.update('<div class=like_count title="Им всем понравилось!">'+count+'</div>');
						div.addClassName('share_opts');
					}else{
						div.update('<div style="position:absolute;margin:-18px 0 0 183px;_margin:-18px 0 0 163px;height:16px;padding:1px 8px 0 0;width:30px;_width:50px;_overflow-x:hidden"></div>');
						div.removeClassName('share_opts');
					}
					sh.options._count_fb = 1;
				}
			});
			obj.load();
		}
		
		// vkontakte
		if(!sh.options._count_vk){
			var cid = this.options.name+"_vkontakte_count";
			var obj = new ag_server();
			obj.set_code("share");
			obj.set_param("url", this.options.object);
			obj.set_param("action", "count");
			obj.set_param("social", 'vkontakte');
			obj.on_load(function(o){
				if(o.get('result')){
					var count = o.get('count');
					var div = $(cid);
					if(count){
						div.update('<div class=like_count title="Столько ссылок на эту страницу ВКонтакте">'+count+'</div>');
						div.addClassName('share_opts');
					}else{
						div.update('<div style="position:absolute;margin:-18px 0 0 183px;_margin:-18px 0 0 163px;height:16px;padding:1px 8px 0 0;width:30px;_width:50px;_overflow-x:hidden"></div>');
						div.removeClassName('share_opts');
					}
					sh.options._count_vk = 1;
				}
			});
			obj.load();
		}
		
		// moimir
		if(!sh.options._count_mm){
			var cid_mm = this.options.name+"_moimir_count";
			var obj = new ag_server();
			obj.set_code("share");
			obj.set_param("url", this.options.object);
			obj.set_param("action", "count");
			obj.set_param("social", 'moimir');
			obj.on_load(function(o){
				if(o.get('result')){
					var count = o.get('count');
					var div = $(cid_mm);
					if(count){
						div.update('<div class=like_count title="Столько ссылок на эту страницу в Моём Мире">'+count+'</div>');
						div.addClassName('share_opts');
					}else{
						div.update('<div style="position:absolute;margin:-18px 0 0 183px;_margin:-18px 0 0 163px;height:16px;padding:1px 8px 0 0;width:30px;_width:50px;_overflow-x:hidden"></div>');
						div.removeClassName('share_opts');
					}
					sh.options._count_mm = 1;
				}
			});
			obj.load();
		}
		
		// google plus
		if(!sh.options._count_gg){
			var cid_gg = this.options.name+"_google_count";
			var obj = new ag_server();
			obj.set_code("share");
			obj.set_param("url", this.options.object);
			obj.set_param("action", "count");
			obj.set_param("social", 'google');
			obj.on_load(function(o){
				if(o.get('result')){
					var surl = o.get('surl');
					if(surl){
						var ifr = $(document.createElement('iframe'));
						ifr.setAttribute('src', '/?act=share&code=gg_if&surl='+surl);
						ifr.setAttribute("scrolling", 'no');
						ifr.setAttribute("frameborder", '0');
						ifr.setAttribute("allowTransparency", 'true');
						var left = '144px';
						ifr.setStyle({ 
							zIndex: 100600,
							top: '-58px', 
							left: left, 
							position: 'relative', 
							border: 'none', 
							overflow: 'hidden', 
							width: '60px', 
							height: '18px' 
						});
						$(sh.options.name+'_gg_if').appendChild(ifr);
					}
					var div = $(cid_gg);
					div.update('<div style="position:absolute;margin:-18px 0 0 183px;_margin:-18px 0 0 163px;height:16px;padding:1px 8px 0 0;width:30px;_width:50px;_overflow-x:hidden"></div>');
					sh.options._count_gg = 1;
				}
			});
			obj.load();
		}
	},
	cancel_delay: function(){
		if(this.hide_delay){
			$A(this.hide_delay).each(function(val){window.clearTimeout(val);});
			this.hide_delay.clear();
		}
	},
	delayed_hide: function(){
		if(!this.hide_delay) this.hide_delay = [];
		this.hide_delay.push(window.setTimeout(this.hide.bindAsEventListener(this), 100));
	}
});


AG.Sharing.serv_list = [
	{ 
		title: 'title="Разместить ссылку ВКонтакте"', 
		pos: 0, name: 'ВКонтакте', id: 'vkontakte',
		width: 530, height: 500
	},
	{ 
		title: 'title="Разместить ссылку в Facebook"', 
		pos: 20, name: 'Facebook', id: 'facebook',
		width: 700, height: 500
	},
	{ 
		title: 'title="Твиттернуть"', 
		pos: 40, name: 'Twitter', id: 'twitter',
		width: 800, height: 400
	},
	{ 
		title: 'title="Опубликовать заметку в ЖЖ"', 
		pos: 60, name: 'LiveJournal', id: 'lj',
		width: 1050, height: 700
	},
	{ 
		title: 'title="Разместить ссылку в Одноклассниках"', 
		pos: 240, name: 'Одноклассники', id: 'odnoklassniki',
		width: 800, height: 600
	},
	{ 
		title: 'title="Разместить ссылку в LiveInternet.ru"', 
		pos: 100, name: 'LiveInternet.ru', id: 'li',
		width: 800, height: 800
	},
	{ 
		title: 'title="Разместить ссылку в МойМир@Mail.ru"', 
		pos: 120, name: 'МойМир@Mail.ru', id: 'moimir',
		width: 520, height: 370
	},
	{ 
		title: 'title="Разместить ссылку в Мой Круг (Яндекс)"', 
		pos: 140, name: 'Мой Круг (Яндекс)', id: 'yaru',
		width: 800, height: 600
	},
	{ 
		title: 'title="Разместить ссылку в MySpace"', 
		pos: 160, name: 'MySpace', id: 'myspace',
		width: 500, height: 400
	},
	{ 
		title: 'title="Разместить ссылку в Закладки Google"', 
		pos: 80, name: 'Закладки Google', id: 'google',
		width: 700, height: 500
	},
	{ 
		title: 'title="Разместить ссылку в &laquo;Избранное&raquo; браузера"', 
		pos: 180, name: '&laquo;Избранное&raquo; браузера', id: 'bookmark'
	}
];

AG.Sharing.handler_click = function(name, i, e){
	var sh = AG.Sharing.hash[name];
	if(!sh) return;
	var panel_id = sh.options.name+'_panel';
	var id = sh.options.name+'_button';
	$(panel_id).setStyle({display: 'none'});
	sh.show();
	sh.run_wrapper(i);
	clearTimeout(sh.timeout);
	if (e.preventDefault)
		e.preventDefault();
	else
		e.returnValue= false;
	return false;
};

AG.Sharing.handler_expand = function(name, e){
	var sh = AG.Sharing.hash[name];
	if(!sh) return;
	var panel_id = sh.options.name+'_panel';
	var id = sh.options.name+'_button';
	$(panel_id).setStyle({ display: 'block' }); 
	$(id).setStyle({ visibility: 'hidden' });
	sh.update_count();
}

AG.Sharing.handler_collapse = function(name, e){
	if(!AG.Sharing.hash) return;
	var sh = AG.Sharing.hash[name];
	if(!sh) return;
	var panel_id = sh.options.name+'_panel';
	var id = sh.options.name+'_button';
	$(panel_id).setStyle({ display: 'none' }); 
	$(id).setStyle({ visibility: 'visible' });
	clearTimeout(sh.timeout);
}

AG.Sharing.handler_mouseout = function(name, e){
	var sh = AG.Sharing.hash[name];
	if(!sh) return;
	var panel_id = sh.options.name+'_panel';
	var id = sh.options.name+'_button';
	sh.timeout = setTimeout('AG.Sharing.handler_collapse("'+name+'", 0)', 1000);
}

AG.Sharing.handler_mouseover = function(name, e){
	var sh = AG.Sharing.hash[name];
	if(!sh) return;
	var panel_id = sh.options.name+'_panel';
	var id = sh.options.name+'_button';
	clearTimeout(sh.timeout);
}

AG.Sharing.show_hide_behavior = function(name, relative_to, container, object, right, top){
	if(!right) right = 105;
	if(!top) top = 2;
	document.observe("dom:loaded", function() { 
		var share = new AG.Sharing({ 
			"name": name, 
			"relative_to": relative_to, 
			"container": container, 
			"right": right, 
			"top": top, 
			"object": object,
			"show_hide": 1
		});
		Event.observe(relative_to, 'mouseover', function(event){ 
			share.place();
			share.show(); 
		});
		Event.observe(relative_to, 'mouseout', function(event){ 
			share.delayed_hide()
		}); 
	});
}

AG.Sharing.news_handle = function(id){
	AG.Sharing.show_hide_behavior('share_'+id, 'news_'+id, 'news_'+id+'_container', 'news/'+id);
};

AG.Sharing.ffic_handle = function(id){
	AG.Sharing.show_hide_behavior('share_'+id, 'ffic_foto_'+id, 'ffic_share_'+id, 'fight_for_iclubby/'+id, 106, 19);
};
