function vtoggle(id, hide) {
	if (!document.getElementById) return false
	if (!hide) hide = false
	var el = document.getElementById(id)
	var vis = el.style.display
	el.style.display = (vis != 'none' || hide) ? 'none' : ''
	el = document.getElementById(id+'arr')
	el.innerHTML = (vis != 'none' || hide) ? '&nbsp;&darr;' : '&nbsp;&uarr;'
	
	return false
}

function show(url, w, h, s, n) {
	if (!n) n = 'vw'
	attr = 'width=' + w + ',height=' + h + ',location=0,menubar=0,resizable=0,scrollbars=' + s + ',status=0,titlebar=0,toolbar=0,hotkeys=0'
	if (parseInt(navigator.appVersion) >= 4) {
		x = (screen.width - w) / 2
		y = (screen.height - h) / 2
		if(x < 0) x = 0
		if(y < 0) y = 0
		attr += ',xposition=' + x + ',left=' + x + ',yposition=' + y + ',top=' + y
	}
	window.open(url, n, attr)
}
function vshow(u) { show(u, 750, 600, 1); return false; }
function rshow(u) { show(u, 400, 250, 0); return false; }

function votes_popup(vote_id, is_multy_answer, action) 
{
	var height = 215 + (40 * jQuery(".answer_" + vote_id).size());
	if(action != 'vote')
	{
		popupWindow = window.open('/vote/?id=' + vote_id, 'popupWindow', 'width=366, height=' + height + ', scrollbars=1');
		return;
	}
	
	var url = "/vote/?id=" + vote_id;
	jQuery(".answer_" + vote_id).each(function() {
	if(this.checked)
		url += "&" + jQuery(this).attr("name") + "=" + (is_multy_answer ? "1" : jQuery(this).attr("value"));
		return true;
	});
	
	popupWindow = window.open(url, 'popupWindow', 'width=366, height=' + height + ', scrollbars=1');
}

function clickTab(a, otherTab) {
	var span = a.parentNode;
	if (span.className=='active') {
		return true;
	}
	var tab = document.getElementById(otherTab+'Tab');
	span.className = 'active';
	tab.className = '';
	var table = document.getElementById(otherTab+'Table');
	table.style.display = 'none';
	if (otherTab == 'video') {
		table = document.getElementById('photoTable');
	} else {
		table = document.getElementById('videoTable');
	}
	table.style.display = 'block';
	return false;
}


Event.observe(window, 'load', function() {
	setTimeout(load_adverts,100);
} );

var advert = new Array();
load_adverts = function(){
 	if (advert.length) {
 		advert.each(function(s){s(); });
 	}
}

create_iframe = function(div_id,_src,w,h){
	var div = $(div_id);
	if (!div) return;
	var ifr = document.createElement('iframe');
	ifr.frameBorder = 'no';
	ifr.width = w;
	if (h) ifr.height = h;
	ifr.scrolling = 'no';
	ifr.src = _src.toString();
	
    setTimeout(function () { div.appendChild(ifr);  }, 0);
    //div.insert(ifr);
}

switch_tabs_realty_banner = function( name ){
//	var tab = document.getElementById( name );
//	var otherTabName;
//	if( name == "realty" ){
//		otherTabName = "health";
//	} else {
//		otherTabName = "realty";
//	}
//	document.getElementById( otherTabName ).style.display = "";
//	tab.style.display = "none";
//	document.getElementById( "type-" + otherTabName ).style.display = "";
//	document.getElementById( "type-" + name ).style.display = "none";
}

switch_tabs_realty_banner_rand = function(){
	var rand = Math.round( Math.random() * 100000000000 ) ;
	if( rand % 2 == 0 ){
		document.getElementById( "realty" ).style.display = "";
		document.getElementById( "health" ).style.display = "none";
		document.getElementById( "type-realty" ).style.display = "";
		document.getElementById( "type-health" ).style.display = "none";
	} else {
		document.getElementById( "health" ).style.display = "";
		document.getElementById( "realty" ).style.display = "none";
		document.getElementById( "type-health" ).style.display = "";
		document.getElementById( "type-realty" ).style.display = "none";
	}
}

shufle = function( array ){
	var i = array.length, j, t;
	while( i ){
	  j = Math.floor( ( i-- ) * Math.random() );
	  t = array[i];
	  array[i] = array[j];
	  array[j] = t; 
	}
	return array;
}

insertAppendOtherApplecationsBlock = function(){
	var title = document.title;
	var link = document.location.href;
	
	if( link.indexOf("top") >=0 ){
		link = jQuery(".extra .m3 a" ).eq(2).attr( "href" );
		title = "Взгляд / " + jQuery("#right_td").find("h1").eq(0).text();
	}
	
	var textElement = jQuery(".m3");
	if(document.location.href.indexOf("photoreport") < 0 && 
	   document.location.href.indexOf("infographics") < 0 &&
	   document.location.href.indexOf("vote") < 0
		|| textElement.length == 0 ){
		textElement = jQuery(".text").eq(jQuery(".text").length - 1);
		jQuery("#append-other-applecations").find(".append-other-applecations").css( "margin", "1" );
	}
	textElement.after(jQuery("#append-other-applecations").html());
	textElement.nextAll(".nomargin:eq(0)").css("clear", "both");
	jQuery("#append-other-applecations").html( "" );
	createLinksForAppendOtherApplecations(jQuery(".append-other-applecations:eq(0)"), link, title );
}

var Url = {
		 
		// public method for url encoding
		encode : function (string) {
			return escape(this._utf8_encode(string));
		},
	 
		// public method for url decoding
		decode : function (string) {
			return this._utf8_decode(unescape(string));
		},
	 
		// private method for UTF-8 encoding
		_utf8_encode : function (string) {
			string = string.replace(/\r\n/g,"\n");
			var utftext = "";
	 
			for (var n = 0; n < string.length; n++) {
	 
				var c = string.charCodeAt(n);
	 
				if (c < 128) {
					utftext += String.fromCharCode(c);
				}
				else if((c > 127) && (c < 2048)) {
					utftext += String.fromCharCode((c >> 6) | 192);
					utftext += String.fromCharCode((c & 63) | 128);
				}
				else {
					utftext += String.fromCharCode((c >> 12) | 224);
					utftext += String.fromCharCode(((c >> 6) & 63) | 128);
					utftext += String.fromCharCode((c & 63) | 128);
				}
	 
			}
	 
			return utftext;
		},
	 
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
	 
			while ( i < utftext.length ) {
	 
				c = utftext.charCodeAt(i);
	 
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
	 
			}
	 
			return string;
		}
	 
	};
createLinksForAppendOtherApplecations = function(parent, link, title, blog){
	var escapeLink = escape(link);
	var escapeTitle = Url.encode(title);
	/*var idArticle = link;//link.match( /\/(\d*)\.html/ )[1];*/
	
	if(typeof blog == "undefined")
	{
		blog = blogger;
	}
	
	parent.find(".app-popup").find("a").each( function(){
		var app = jQuery(this);
		if( app.hasClass("blogger") ){
			app.attr( "href", "http://www.blogger.com/blog_this.pyra?t&a=ADD_SERVICE_FLAG&passive=true&alinsu=0&aplinsu=0&alwf=true&hl=ru&skipvpage=true&rm=false&showra=1&fpui=2&naui=8&u=" + escapeLink + "&n=" + escapeTitle );
		} else if( app.hasClass("twitter") ){
			app.attr( "href", "http://twitter.com/home?status=" + escapeTitle + " " + escapeLink );
		} else if( app.hasClass("google") ){
			escapeTitleGoogle = Url.encode( shorter( jQuery("#right_td").find(".lead").eq(0).text(), 87 ) );
			app.attr( "href", "http://www.google.com/buzz/post?message=" + escapeTitleGoogle + "&url=" +  escapeLink);
		} else if( app.hasClass("gmail") ){
			app.attr( "href", "https://mail.google.com/mail/?view=cm&fs=1&to&ui=2&tf=1&shva=1&su=" + escapeTitle + "&body=" + escapeLink );
		} else if( app.hasClass("livejournal") ){
			if( !jQuery.browser.msie && typeof blog != "undefined"){
				var form = jQuery("<form style='display:none' accept-charset='UTF-8' action='http://www.livejournal.com/update.bml' method='POST'><input type='hidden' name='subject' value='" + title + "'/><textarea name='event'>" + new Template(blog.options.add_code_tpl).evaluate(blog.article_data) + "</textarea></form>");
				app.after(form);
				app.click(function() {
					form.submit();
					return false; 
				});
			}
			app.attr( "href", "http://www.livejournal.com/update.bml?subject=" + escapeTitle + "&event=" + escapeLink );
		} else if( app.hasClass("liveinternet") ){
			app.attr( "href", "http://www.liveinternet.ru/journal_post.php?action=n_add&cntitle=" + escapeTitle + "&cnurl=" + escapeLink );
		} else if( app.hasClass("facebook") ){
			app.attr( "href", "http://www.facebook.com/share.php?u=" + escapeLink );
		} else if( app.hasClass("myspace") ){
			app.attr( "href", "https://secure.myspace.com/index.cfm?fuseaction=login.simpleform&featureName=postToV3&dest=" + escapeLink );
		} else if( app.hasClass("mailru") ){
			app.attr( "href", "http://connect.mail.ru/share?share_url=" + escapeLink );
		}
	} );
	parent.find(".append .app.big-livejournal").each( function(){
		if( !jQuery.browser.msie && typeof blog != "undefined"){
			var form = jQuery("<form style='display:none' accept-charset='UTF-8' action='http://www.livejournal.com/update.bml' method='POST'><input type='hidden' name='subject' value='" + title + "'/><textarea name='event'>" + new Template(blog.options.add_code_tpl).evaluate(blog.article_data) + "</textarea></form>");
			jQuery(this).after(form);
			jQuery(this).click(function() {
				form.submit();
				return false;
			});
			return false;
		}
		jQuery(this).attr( "href", "http://www.livejournal.com/update.bml?subject=" + escapeTitle + "&event=" + escapeLink );
	} );
	
	parent.find(".append .app.big-twitter").each( function(){
		jQuery(this).attr( "href", "http://twitter.com/home?status=" + escapeTitle + " " + escapeLink );
		return false;
	} );
	
	parent.find(".append .app.big-vkontakte").click( function(){
		VK.Share.click(0);
		return false;
	} );
	parent.find(".append .app.big-vkontakte").hover( function(){
			jQuery(this).css( "background", "url(/images/vkontakte_color.gif) no-repeat 0 0;" );
		},	function(){
			jQuery(this).css( "background", "url(/images/vkontakte_bw.gif) no-repeat 0 0;" );
	});
	parent.find(".app.big-facebook").each( function(){
		jQuery(this).attr( "href", "http://www.facebook.com/share.php?u=" + escapeLink );
		return false;
	} );
	parent.find(".app.big-russiaru").click(function() {
		RussiaRuAPI.click();
		return false;
	});
	parent.find(".action.print").click( function(){
		location.href = link.replace("html", "print.html");
		return false;
	} );

	if(window.location.href.indexOf("/online/") < 0 && jQuery("#online").length == 0)
	{
		if(window.location.hostname.indexOf("admin") < 0)
		{
			var likeVkontakte =	jQuery('<script type="text/javascript">VK.init({apiId: "1949124", onlyWidgets: true});</script>' +
					'<div id="vk_like"></div><script type="text/javascript"> ' +
					'VK.Widgets.Like("vk_like", {width: "496", verb: "1"}, \"' + escapeLink + '\");' +
					'</script>');
		}
		var buttonLike = jQuery('<div id="facebook-like"><iframe src="http://www.facebook.com/plugins/like.php?href=' + escapeLink + '&amp;' +
				'layout=standard&amp;show_faces=false&amp;width=100%&amp;action=recommend&amp;colorscheme=light&amp;height=23" scrolling="no" ' + 
				'frameborder="0" style="border:none; overflow:hidden; width:100%; height:23px;" allowTransparency="true"></iframe></div>');
		if( jQuery("#facebook-like").length == 0 ){
			jQuery(".append-other-applecations").eq(0).before(likeVkontakte.clone());
			jQuery(".text p").eq(0).after(buttonLike.clone());
	//		if( location.href.indexOf("news") < 0 ){
	//			jQuery(".append-other-applecations").eq(0).before(buttonLike.clone().attr("class", "recommend-facebook").find("iframe").css("width", "468px").end());
	//		}
		}
	}
	var inPopup = false;
	parent.find(".append-all-app").hover( function( e ){
		inPopup = true;
		jQuery(this).parents(".append-other-applecations").find(".app-popup").show();
		return false;
	}, function(){
		inPopup = false;
	    setTimeout(function () { if (!inPopup) parent.find(".app-popup").hide(); }, 1000);
	});
	parent.find(".app-popup").hover( function( e ){
		inPopup = true;
		jQuery(this).show();
		return false;
	}, function(){
		inPopup = false;
		var app = jQuery(this);
	    setTimeout(function () { if (!inPopup) app.hide(); }, 1000);
	});
}
	
shorter = function( str, count ){
	count -= 3;
	var words = str.split( " " );
	var strShort = "";
	var i = 0;
	for( j = 0; j < words.length; j++){
		var word = words[j];
		if( strShort.length + word.length < count ){
			strShort += word;
			i++;
			
			if(i < words.length && strShort.length + words[i].length < count ){
				strShort += " ";
			} else if(i < words.length && word.match("\\W*") ){
				strShort += "...";
				break;
			} else {
				break;
			}
		}
	}
	return strShort;	
};

(function($, resize) {
	if($.browser.msie)
	{
		var documentIsLoaded, $window = $(window).one("load", function() {
			documentIsLoaded = 1;
		});

		function backToNative () {
			$.event.special[resize] = undefined;
			var events = $window.data("events"),
			eventStack = events && events[resize];
			if(eventStack)
			{
				events[resize] = undefined;
			}
			
			$window.one(resize, $.noop);
			if(eventStack)
			{
				events[resize] = eventStack;
			}
		}
	    
		$.event.special[resize] = {
			setup: function() {
				if(documentIsLoaded)
				{
					backToNative();
					return !documentIsLoaded;
				}
				var checking, prevWidth = $window.width(), prevHeight = $window.height();
	          
				(function handler() {
					if(documentIsLoaded)
					{
						window.clearInterval(checking);
						backToNative();
						return;
					}
		
					var width = $window.width(), height = $window.height();
		
					if (width != prevWidth || height != prevHeight)
					{
						prevWidth = width;
						prevHeight = height;
						$window.trigger(resize);
					}
		
					if(!checking)
					{
					    checking = window.setInterval(handler, 100);
					}
				})();
			},
			teardowm: $.noop
		};
	}
}) (jQuery, "resize");

var Cookies = {
	set: function(cookieName, cookieContent, cookieExpireTime){
		if (cookieExpireTime>0){
			var expDate=new Date();
			expDate.setTime(expDate.getTime()+cookieExpireTime*1000*60*60);
			var expires=expDate.toGMTString();
			document.cookie=cookieName+"="+escape(cookieContent)+"; path="+escape('/')+"; expires="+expires
		}else{
			document.cookie=cookieName+"="+escape(cookieContent)+"; path="+escape('/')+"";
		}
	},
	get: function(cookieName){
		var ourCookie=document.cookie;
		if (!ourCookie || ourCookie=="")return "";
		ourCookie=ourCookie.split(";");
		var i=0;
		var Cookie;
		while (i<ourCookie.length){
			Cookie=ourCookie[i].split("=")[0];
			if (Cookie.charAt(0)==" ") Cookie=Cookie.substring(1);
			if (Cookie==cookieName) return unescape(ourCookie[i].split("=")[1]);
			i++;
		}
		return "";
	},
	erase: function(cookieName){
		var cookie = Cookies.get(cookieName) || true;
		Cookies.set(cookieName, '', -1);
		return cookie;
	},
	accept: function(){
		if (typeof navigator.cookieEnabled == 'boolean') return navigator.cookieEnabled;
		Cookies.set('_test', '1');
		return (Cookies.erase('_test') = '1');
	}
}

var VZ = {
	urlVars: null,
	
	init: function() {
		VZ.initWidgets();
		VZ.initVote();
		VZ.initPhoto();
		VZ.initPhotoThumbs();
		VZ.initJCarousel(jQuery(".spec-project-photos"));
		VZ.initJCarousel(jQuery(".taggroup-menu"), true);
		VZ.initJCarousel(jQuery(".main-menu"), true);
		//VZ.initSocialNetworkPanel();
		VZ.initOnline();
		
		jQuery("#top .sys_app img").hover(function() {
			jQuery(this).attr("src", jQuery(this).attr("src").replace('_bw',''));
		}, function() {
			jQuery(this).attr("src", jQuery(this).attr("src").replace('.','_bw.'));
		});
		
		jQuery(".sys_bigimage").hover(function() {
			jQuery(this).attr("src", jQuery(this).attr("src").replace('b.jpg','.jpg'));
		}, function() {
			jQuery(this).attr("src", jQuery(this).attr("src").replace('.jpg','b.jpg'));
		});
	},
	getUrlVars: function() {
		if(!VZ.urlVars)
		{
			var vars = [], hash;
			var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
			for(var i = 0; i < hashes.length; i++)
			{
			  hash = hashes[i].split('=');
			  vars.push(hash[0]);
			  vars[hash[0]] = hash[1];
			}
			VZ.urlVars = vars;
		}
		return VZ.urlVars;
	},  
	getUrlVar: function(name) {
		return VZ.getUrlVars()[name];
	},
	initJCarousel: function(form, isMenu) {
		//alert("++++++++++++++=" + jQuery(form).attr("class"));
		if(form.length > 0 && (!jQuery.browser.msie || (jQuery.browser.version != 6 && jQuery.browser.version != 7)))
		{
			var li = jQuery(".sys_thumbs li").last();
			var thumbs = form.find(".sys_thumbs");
			var li = thumbs.find("li").last();
			if(!li.length) return;
			
			var timer = null;
			var resizeThumbs = function() {
				if(timer != null)
				{
					window.clearInterval(timer);
				}
				var buttons = form.find(".jcarousel-buttons");
				var buttonsW = 0;
				if(buttons.length > 0)
				{
					buttonsW = parseInt(buttons.css("width"));
				}
				var width = parseInt(li.css("width"));
				var mright = parseInt(li.css("margin-right"));
				if(mright != mright)
				{
					mright = 0;
				}
				width += mright;
				var widthWindow = isMenu ? jQuery(window).width() - 260 : form.width();
				//alert(form.width() + " " + buttonsW + " " + width);
				var mod = (widthWindow - buttonsW) % width;
				width = (widthWindow - buttonsW) - mod - mright;
				//alert(widthWindow + " " + (form.width() - buttonsW) + " " + mod + " " + mright);
				//thumbs.css({width: "800px"}).show();
				//alert(width);
				thumbs.css({width: width}).show();
			};
			resizeThumbs();
			
			setTimeout( function() {
				form.find("ul").jcarousel({scroll: 1, buttons: form.find(".jcarousel-buttons")});
			}, 2000);
			
			jQuery(window).resize(function() {
				timer = setInterval(resizeThumbs, 100);
			});
			jQuery("iframe").load(function() {
				timer = setInterval(resizeThumbs, 1000);
			});
		}
	},
	initNewsComments: function(options) {
		options.page_size = options.page_size || 3;
		new easyXDM.Socket({
			remote: options.commentsUrl + "?api_key=" + options.apiKey + "&ps=" + options.page_size + "&source=news_" 
				+ options.id + "&path=" + encodeURIComponent(options.link) + "&css=" + options.css + "&recommend=/images/vz/vz_recommend.gif",
			container: document.getElementById(options.container),
			props: {style: {width: options.width}},
			onMessage: function(message, origin) {
				var height = parseInt(message);
				if(height > 0)
				{
					var iframe = this.container.getElementsByTagName("iframe")[0];
					iframe.scrolling = 'no';
					iframe.frameborder = 'no';
					iframe.style.height = height + "px";
					iframe.style.width = options.width;
				}
				else
				{
					var post = jQuery.evalJSON(message);
					VZ.newsCommentsCallback(post.count, post.page_id, post.time, post.sign, options.id);
				}
			}
		});
	},
	initOnline: function() {
		var online = jQuery("#online");
		
		if(online.length > 0)
		{
			jQuery("#online .append-other-applecations").each(function(){
				var blog = new Blogger();
				blog.initArticle({
					date: jQuery(this).find("input[name=sysDate]").val(),
					pic_url: jQuery(this).find("input[name=sysPicUrl]").val(),
					pic_display: jQuery(this).find("input[name=sysPicUrl]").length > 0 ? "block" : "none",
					title: jQuery(this).find("input[name=sysTitle]").val(),
					lead: jQuery(this).find("input[name=sysLead]").val(),
					url: jQuery(this).find(".sysUrl").attr("href")
				});
				createLinksForAppendOtherApplecations(jQuery(this), jQuery(this).find(".sysUrl").attr("href"), jQuery(this).find("input[name=sysTitle]").val(), blog);
			});
			
			var fillTemplate = function(item) {
				var template = jQuery(".sysOnlineTemplate").clone();
				template.find(".sysTitle").html(item.title);
				template.find(".sysDate").text(item.date);
				template.find(".sysText").html(item.text);
				template.find("input[name=mtime]").val(item.mtime);
				if(item.image)
				{
					template.find(".sysImg img").attr("src", item.image);
				}
				else
				{
					template.find(".sysImg").remove();
				}			
				template.removeClass("sysOnlineTemplate");
				
				var share = template.find(".append-other-applecations");
				var blog = new Blogger();
				blog.initArticle({
					date: item.date,
					pic_url: item.image,
					pic_display: item.image ? "block" : "none",
					title: item.title,
					lead: "",
					url: item.url
				});
				createLinksForAppendOtherApplecations(share, item.url, item.title, blog);
				
				template.find(".sys_bigimage").hover(function() {
					jQuery(this).attr("src", jQuery(this).attr("src").replace('b.jpg','.jpg'));
				}, function() {
					jQuery(this).attr("src", jQuery(this).attr("src").replace('.jpg','b.jpg'));
				});
				
				return template;
			}
			
			var extractHTML = function(xml, tag) {
				var result;
				jQuery(xml).find(tag).each(function(i, el) {
					if(el.textContent)
					{
						result = el.textContent;
					}
					else
					{
						result = el.firstChild.nodeValue;
					}
				});
				return result;
			}
			
			var color = 226;
			msgblink = function() {
				if(color == 236) color -= 10;
				else color += 10;
				online.find(".sysMsg").css("background", "rgb(" + color + ", " + color + ", " + color + ")");
				setTimeout(msgblink, 1000);
			};
			online.find(".sysMsg").click(function(){
				location.reload();
				return false;
			});
			
			var id = online.find("input[name=online_id]").val();
			var last = online.find(".sysPosts input[name=mtime]:first").val();
			var update = function() {
				VZ._post("/onlinedata/" + id + "/" + last + ".xml?mode=before", {}, function(resp) {
					var posts = jQuery(resp).find("post");
					var time = posts.eq(0).attr("date");
					var newPosts = posts.length;
//					jQuery(resp).find("post").each(function(i, el){
//						var date = jQuery(el).attr("date");
//						if(date > last)
//						{
//							newPosts += 1;
//							return true;
//						}
//						else if(date == last)
//						{
//							return true;
//						}
//						
//						return false;
//					});
					
					if(newPosts > 0)
					{
						online.find(".sysMsg").css("display", "block").html(newPosts + VZ.printPluralForm(newPosts, " новое сообщение", " новых сообщения", " новых сообщений"));
						if(online.find(".sysMsg").css("display") == "none")
						{
							setTimeout(msgblink, 1000);
						}
					}
				}, "GET");
				setTimeout(update, 60 * 1000);
			};
			
			if(online.find(".sysMsg").length > 0)
				setTimeout(update, 60 * 1000);
			
			online.find(".sysMore").click(function() {
				var from = online.find(".sysPosts input[name=mtime]:last").val();
				VZ._post("/onlinedata/" + id + "/" + from + ".xml", {}, function(resp) {
					var countNew = 0;
					jQuery(resp).find("post").each(function(i, el){
						var item = {};
						var post = jQuery(el);
						item.title = extractHTML(post, "title");
						item.date = post.find("date").text();
						item.mtime = post.attr("date");
						item.image = post.find("img").text();
						item.id = post.find("id").text();
						item.url = post.find("url").text();
						item.text = extractHTML(post, "text");
						var template = fillTemplate(item);
						online.find(".sysPosts").append(template);
						template.show();
						
						if(post.find("has_comments").text() == "true")
						{
							template.append("<div class='xdm-container' id='xdm-container-" + item.id + "'></div>");
							
							VZ.initNewsComments(
								{
									commentsUrl: online.find("input[name=commentsUrl]").val(), 
									apiKey: online.find("input[name=apiKey]").val(), 
									container: "xdm-container-" + item.id, 
									id: item.id, 
									link: item.url,
									page_size: 3,
									css: "http://www.vz.ru/css/online-comments.css",
									width: "80%"
								}
							);
						}
						countNew++;
					});
					
					var count = online.find(".sysMore span").text();
					count -= countNew;
					if(count <= 0)
						online.find(".sysMore").hide();
					else
						online.find(".sysMore").html("Далее <span>" + count + "</span> " + VZ.printPluralForm(count, "сообщение", "сообщения", "сообщений"));
				}, "GET");
				
				return false;
			});
			
			
			online.find(".sysBefore").click(function() {
				var from = online.find(".sysPosts input[name=mtime]:first").val();
				VZ._post("/onlinedata/" + id + "/" + from + ".xml?mode=before", {}, function(resp) {
					var countNew = 0;
					jQuery(resp).find("post").each(function(i, el){
						var item = {};
						var post = jQuery(el);
						item.title = extractHTML(post, "title");
						item.date = post.find("date").text();
						item.mtime = post.attr("date");
						item.image = post.find("img").text();
						item.id = post.find("id").text();
						item.url = post.find("url").text();
						item.text = extractHTML(post, "text");
						var template = fillTemplate(item);
						online.find(".sysPosts").prepend(template);
						template.show();
						
						if(post.find("has_comments").text() == "true")
						{
							template.append("<div class='xdm-container' id='xdm-container-" + item.id + "'></div>");
							
							VZ.initNewsComments(
								{
									commentsUrl: online.find("input[name=commentsUrl]").val(), 
									apiKey: online.find("input[name=apiKey]").val(), 
									container: "xdm-container-" + item.id, 
									id: item.id, 
									link: item.url,
									page_size: 3,
									css: "http://www.vz.ru/css/online-comments.css",
									width: "80%"
								}
							);
						}
						countNew++;
					});
					
					var count = online.find(".sysBefore span").text();
					count -= countNew;
					if(count <= 0)
						online.find(".sysBefore").hide();
					else
						online.find(".sysBefore").html("Предыдущие <span>" + count + "</span> " + VZ.printPluralForm(count, "сообщение", "сообщения", "сообщений"));
				}, "GET");
				
				return false;
			});
		}
	},
	initPhotoThumbs: function() {
		var thumbs = jQuery(".sys_thumbs");
		if(thumbs.length > 0)
		{
			thumbs.find("img.sys_thumb").hover(function() {
				jQuery(this).attr("src", jQuery(this).attr("src").replace('_150b.jpg','_150.jpg'));
			}, function() {
				jQuery(this).attr("src", jQuery(this).attr("src").replace('_150.jpg','_150b.jpg'));
			});
		}
	},
	initPhoto: function() {
		jQuery(".sys_main_photos .sys_img").hover(function() {
			jQuery(this).css("background-image", jQuery(this).css("background-image").replace("b.jpg", ".jpg"))
		}, function() {
			jQuery(this).css("background-image", jQuery(this).css("background-image").replace(".jpg", "b.jpg"))
		});
		
		var form = jQuery(".sys_photoreport");
		form.find(".sys_photo, .sys_link_left, .sys_link_right").hover(function() {
			form.find(".sys_link_left").show();
			form.find(".sys_link_right").show();
		}, function() {
			form.find(".sys_link_left").hide();
			form.find(".sys_link_right").hide();
		});
	},
	initVote: function() {
		var form = jQuery("form.sys_vote_form");
		if(form.length > 0)
		{
			form.find("input.sys_vote").unbind("click").bind("click", function(){
				var button = jQuery(this);
				VZ._post("/votehandler/", button.parents("form.sys_vote_form").serialize(), function(resp){
					if(resp == "true")
					{
						document.location.href = "/vote/result/" + button.parents("form.sys_vote_form").find("input[name=id]").val() + "/?vote=true";
					}
					else
					{
						if(button.siblings(".sys_vote_error").length == 0)
						{
							button.before("<div class = 'sys_vote_error' style = 'color: #E23535; font-weight: bold;'>Извините, с вашего IP-адреса уже голосовали</div>");
						}
					}
				});
			});
		}
	},
	initVoteBlogger: function(options) {
		var code = jQuery(".sys_blogger_code");
		var button = jQuery(".sys_blogger_button");
		code.hide();
		var codeText = "<div style = 'width: 298px; border: 1px solid #CCCCCC;'><div style='padding: 4px 8px 0px 6px; overflow: hidden; height: 27px;'><a href='http://www.vz.ru/'><img height='19' width='77' border='0' style='float: left; border: medium none; vertical-align: middle;' alt='' src='http://www.vz.ru/images/vz_tiny.gif'></a><small style='float: right; font-size: 10px;'></small></div><a href='http://www.vz.ru/vote/" + options.voteId + "/'><div style='background: url(http://img.vz.ru/upimg/" + options.img + ") no-repeat scroll center top rgb(153, 153, 153); height: 120px;'></div></a><div style = 'color: #000000; font-size: 10px; padding: 5px;'>" + 
			"<div style = 'font-weight: bold; font-size: 13px;'>" + options.question + "</div>";
		
		jQuery.each(options.answers, function(){
			codeText += "<div style='background-color: #B9B9B9; width: " + this.percent + "px; height: 18px; padding: 2px 0px 0px 3px; float:left; margin: 5px 5px 0px 0px;'></div><div style='float:left; margin-top: 8px;'>" + this.answer + " | " + this.percent + "%</div><div style='clear: both'></div>";
		});
		
		codeText += "<div style='color: #656565; margin-top: 10px;'>Всего " + VZ.printPluralForm(options.count, "проголосовал ", "проголосовало ", "проголосовали ") + options.count + VZ.printPluralForm(options.count, " человек", " человека", " человек") + ".</div>" + 
			"</div></div><div style = 'background-color: #656565; width: 300px; height: 16px; color: #FFFFFF; font-size: 11px; text-align: center;'>Результаты на " + VZ.fomatDate(new Date()) + " года</div>";
		
		button.unbind("click").bind("click", function(){
			code.toggle();
			code.html("<div class='clear'></div><div class = 'hint'>Скопируйте код и вставьте в свой блог:</div><textarea readonly id='" + "bla" + "'>" + codeText + "</textarea>");
			code.find("textarea").unbind("click").bind("click", function() {
				this.select();
			});
		});
	},
	voteCommentsCallback: function(num, pageId, time, sign, id)
	{
	   	var url = "/vkcomments_count";
	    var body = "ptl-ajax=true&ptl-action=update-count";

	    var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

	    request.open("POST", url, true);
	    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    request.send(body + "&time=" + time + "&page_id=" + pageId + "&count=" + num + "&sign=" + sign + "&type=vote" + "&id=" + id);
	},
	newsCommentsCallback: function(num, pageId, time, sign, id) {
	   	var url = "/vkcomments_count";
	    var body = "ptl-ajax=true&ptl-action=update-count";

	    var request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

	    request.open("POST", url, true);
	    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	    request.send(body + "&time=" + time + "&page_id=" + pageId + "&count=" + num + "&sign=" + sign + "&id=" + id);
	},
	fomatDate: function(date) {
		var months = new Array("января", "февраля", "марта", 
			"апреля", "мая", "июня", "июля", "августа", "сентября", 
			"октября", "ноября", "декабря");
		
		return date.getDate() + " " + months[date.getMonth()] + " " + date.getFullYear();
	},
    printPluralForm: function(t, oneText, severalText, manyText) {
        var n = Math.abs(t) % 100;
        var n1 = n % 10;
        if (n > 10 && n < 20) return manyText;
        if (n1 > 1 && n1 < 5) return severalText;
        if (n1 == 1) return oneText;
        return manyText;
    },
    getCurrentPage: function() {
    	var href = decodeURIComponent(window.location.href);
		var idx = href.indexOf('#?');
		if (idx > 0) {
			return href.substring(idx+2);
		}
		idx = href.indexOf("?");
		var params = (idx > 0) ? href.substring(idx) : '';
		return window.location.pathname + params;
    },
    post: function(action, param, callback, noPtlCallback, href) {
    	if (typeof param == "object") param = jQuery.param(param);
        var p = "ptl-action=" + action + "&ptl-ajax=true&" + param;
        if (!href) {
	        href = VZ.getCurrentPage();
        }
        if (href.length == 0) {
            href = "/";
        } else {
        	var idx = href.indexOf('?');
        	if (idx > 0) {
        		var params = href.substring(idx+1).split("&");
        		href = href.substring(0, idx+1);
        		for (var i = 0; i < params.length; i++) {
        			idx = params[i].indexOf("=");
        			if (i > 0) {
        				href += "&";
        			}
        			if (idx>0) {
        				href += params[i].substring(0, idx+1) + encodeURIComponent(params[i].substring(idx+1));
        			} else {
        				href += params[i];
        			}
        		}
        	}
        }
        VZ._post(href, p, function(data) {
            if( !noPtlCallback ) {
            	ptlProcessCallback(data);
            }
            if (typeof callback == "function") callback(data);
        });
        return false;
    },
    _post: function(url, param, callback, type) {
    	if(!type)
    	{
    		type = "POST";
    	}
    	jQuery.ajax({
            type: type,
            url: url,
            data: param,
            timeout: 30000,
            success: callback,
            error: function(xhr, code){
    			//alert(code);
            }
        });
    },
    initSocialNetworkPanel: function() {
    	var panel = jQuery("#social-network-panel");
    	
    	panel.find(".close").click(function() {
			panel.animate({
		        right: '-=' + (panel.width() + 35)
		    }, 500, function() {
		    	panel.hide();
	    	});
    	});

		var count = 0;
		var cookie = Cookies.get('show-online-banner');
		if(cookie)
		{
			count = parseInt(cookie);
		}
		if(count < 5)
		{
			panel.css("right", (-panel.width() - 25) + "px");
			panel.append("<img src='http://ad.adriver.ru/cgi-bin/rle.cgi?sid=178710&bt=21&pz=0&rnd=952943609' border='0' width='1' height='1'>");
			panel.show();
			
		    setTimeout( function() {
		    	panel.animate({
			        right: '+=' + (panel.width() + 35)
			    }, 500);
		    }, 3 * 1000);
		}
		Cookies.set('show-online-banner', count + 1, 1 * 20);
		
	    setTimeout( function() {
			panel.animate({
		        right: '-=' + (panel.width() + 35)
		    }, 500, function() {
		    	panel.hide();
	    	});
	    }, 18 * 1000);
	}, 
	initWidgets: function() {
    	var widgets = ["http://apivz.russia.ru/popular_widget?api_key=uHqzR2nYRY6YxveloLeL&css=http%3A%2F%2Fapivz.russia.ru%2Fcss%2Fpopular-materials-vz.css",
    	               /*"http://apivz.russia.ru/last_comments_widget?api_key=uHqzR2nYRY6YxveloLeL&css=http%3A%2F%2Fapivz.russia.ru%2Fcss%2Flast-comments-vz.css",*/
    	               "http://apivz.russia.ru/recommend_widget?api_key=uHqzR2nYRY6YxveloLeL&css=http%3A%2F%2Fapivz.russia.ru%2Fcss%2Frecommends-vz.css"]
    	var d = new Date();
    	var widgetUrl = widgets[d.getMilliseconds() % widgets.length]
    	
		if(jQuery("#widget-xdm-container").length > 0)
		{
	    	new easyXDM.Socket({
	    	     remote: widgetUrl,
	    	     container: document.getElementById("widget-xdm-container"),
	    	     props: {style: {width: "240px"}},
	    	     onMessage: function(message, origin){
	    	        var height = parseInt(message);
	    	        if (height > 0) {
	    	              var iframe = this.container.getElementsByTagName("iframe")[0];
	    	              iframe.scrolling = 'no';
	    	              iframe.frameborder = 'no';
	    	          	iframe.style.height = height + "px";
	    	          	iframe.style.width = "240px";
	    	        } else {
	    	          var post = jQuery.evalJSON(message);
	    	          VZ.newsCommentsCallback(post.count, post.page_id, post.time, post.sign);
	    	        }
	    	     }
	    	 });
       	}
    	if(jQuery("#groups_widget").length > 0)
    	{
			var num = Math.floor(Math.random()*2);
			if(num == 1)
			{
				var code = "<iframe src='http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fvzglyad&amp;width=240&amp;colorscheme=light&amp;show_faces=true&amp;border_color&amp;stream=false&amp;header=false&amp;height=270'" +  
					" scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:240px; height:270px;' allowTransparency='true'></iframe>";
				jQuery("#groups_widget").html(code);
			}
			else if(VK)
			{
				VK.Widgets.Group("groups_widget", {mode: 0, width: "240"}, 19976640);
			}
    	}
	}
};


jQuery(document).ready( function(){
	VZ.init();
});

