
jQuery(function($) {
	// Tooltips
	$("a[tooltip],img[tooltip]").each(function()
	{
		var md = $(this).metadata({ type: "attr", name: "tooltip" });
		$(this).Tooltip({
			showTitle: '{-}',
			bodyText: md.url ? 'Идет загрузка..{-}' : md.text ? md.text : null,
			bodyUrl: md.url ? md.url : null,
			className: md['className'] ? md['className'] : 'tooltip'
		});
	});
	// Star rating
	$("span[rating],div[rating]").srating();
	// Protect code	- защитный код
	$("div.protectcode").html('<img src="/main/randomimg/" alt="Защитный код! Зарегистрируйтесь, чтобы не вводить код" onclick="this.src=this.src;" align="absmiddle" hspace="4">');
});





//login and messages
jQuery(document).ready(function($) {


var dat = 0;
$.updMsg = function() {
 var ldat = 0;
 $.get('/back/ajax-user.asp?mod=id',
 function(ldata)
  {ldat = ldata;
   if (ldat > 0) {
     $('#login-area').load('/back/ajax-user.asp?mod=loginstring',function(){});
     $('.new-msg-t').load('/back/ajax-user.asp?mod=umsg', function(data)
      {
        if (data > 0) {
         if (data > dat ) {$('#msg-panel:visible').animate({bottom:'+=30px'},500,'swing').animate({bottom:'-=30px'},500,'swing');}
         $('#msg-panel:hidden').fadeIn('2000').animate({bottom:'10px'},'800');
                      }
       else {$('#msg-panel:visible').hide('fast');}
       dat = data;
      });
		}
   else {
   $('#login-area').load('/back/ajax-user.asp?mod=loginstring',function(){});
        }
 });
return false;
}

$.updMsg();
$.timer(300000, function() { $.updMsg();});	// Проверять на новые сообщения каждые 300 секунд или 5 минут

/*loginform*/





/*************************************************************

 Раскрывающиеся вниз  контекстное меню

*/
$('.slide>a')
	.live('click', function () {
		var offset = $(this).offset(),
			left = offset.left,
			top = offset.top + $(this).height() + 5;
      //$('.slide ul')
			$(this).next('ul')
      	.css({top: top + 'px', left: left + 'px'})
				.toggle();
		return false;
	});
$('.slide>a').html($('.slide>a').html()+' <small>&#x25bc;</small>');
/*

 /Раскрывающиеся вниз  контекстное меню

**************************************************************/



});


/**
* star rating plugin
*/
(function($) {
	$.fn.srating = function() {
		return this.each(function() {
			var opts = $.irating.getOpts($(this));
			if (!opts) {
				opts = $(this).metadata({type: "attr", name: "rating"});
				if (typeof opts.val == 'object') {
					opts.votes = opts.val[1];
					opts.isStatic = opts.isStatic ? opts.isStatic : opts.val[2] == 1;
					opts.val = parseFloat(String(opts.val[0]).replace(/\,/g, "."));
				}
				opts.url = opts.url ? "/main/rating/default2.asp?" + opts.url : null;
			}
			$.irating.install($(this), opts);
		});
	};
	$.irating = {
		install : function($el, opts)
		{
			var opts = $.extend({ maxVal: 5, val: 0, votes: 0, msgb: "", msga: "", isStatic: false, rmsg: false, className: null}, opts);
			if ($el.find("ul.star-rating").length == 0) {
				var zindex = 0, items = "", itemst = "</ul>";
				if (opts.msgb.length || opts.msga.length || opts.rmsg) {
					items += '<span class="rating-msg">' + (opts.isStatic ? opts.msga : opts.msgb) + '</span><span class="star-rating-inline">';
					itemst += "</span>";
				}
				items += '<ul class="star-rating ' + opts.className + '"><li class="current-rating" style="width:0%;" title=""></li>';
				for (var i = 1; i <= opts.maxVal; i++) {
					title = 'голосовать: ' + i + ' из ' + opts.maxVal;
					zindex = opts.maxVal - i + 2;
					items += '<li><a href="javascript:void(0);" r="' + i + '" title="' + title +'" style="width:0%;z-index:' + zindex + ';" hidefocus></a></li>';
				}
				if (opts.rmsg) itemst += '</span><span class="rating-rmsg"></span>';
				$el.empty().append(items + itemst);
			}
			$el.find("ul.star-rating")[0].$opts = $.extend({ $c: $el }, opts);
			$.irating.setRating($el, opts.val, opts.votes);
			$.irating.setStatic($el, opts.isStatic);
		},
		setStatic : function($el, s)
		{
			var opts = $.irating.getOpts($el);
			$el.find("a").each(function(i) {
				$(this).css("width", s ? 0 : Math.floor(100 / opts.maxVal * (i+1)) + '%');
				if (!s) $(this).bind("click", {val: (i+1)}, $.irating._handler);
			});
		},
		setRating : function($el, val, votes)
		{
			val = parseFloat(String(val).replace(/\,/g, "."));
			var rmsg = "голосов";
			var opts = $.irating.getOpts($el), $curr = $el.find("li.current-rating");


			if ($curr.length) {

				switch (votes - Math.round(votes/10)*10) {
				case 1:
					rmsg = "голос"; break;
				case 2:
					rmsg = "голоса"; break;
				case 3:
					rmsg = "голоса"; break;
				case 4:
					rmsg = "голоса"; break;
				}


				$curr.css({width: Math.floor(100 / opts.maxVal * val) + '%'}).attr("title", (Math.round(val * 100) / 100) + ' из ' + opts.maxVal + ' | ' + votes + ' ' + rmsg);
				//$el.find("span.rating-rmsg").html('  ' + (Math.round(val * 100) / 100) + ' из ' + opts.maxVal + ' | ' + votes + ' голосов');


				$el.find("span.rating-rmsg").html(' ' + votes + '&#160;' + rmsg);

				$el.find("a").each(function(i) {
					$(this).attr("title", 'голосовать: ' + (i+1) + ' из ' + opts.maxVal + ' (текущий: ' + (Math.round(val * 100) / 100) + ' из ' + opts.maxVal + ' | ' + votes + ' ' + rmsg);
				});
			}
		},
		getOpts: function($el)
		{
			var $c = $el.find("ul.star-rating");
			if ($c.length == 0) $c = $el.parents("ul.star-rating");
			return $c[0] ? $c[0].$opts : null;
		},
		_handler : function(e)
		{
			var opts = $.irating.getOpts($(this)), $curr = opts.$c.find("li.current-rating");
			$.irating.setStatic(opts.$c, true);
			var p = 0, fader = $.timer(100, function() {
				p = p > 100 ? 0 : p + 10;
				$curr.css({width: p + '%'});
			});
			$.ajax({
				url: opts.url,
				data: { "vote": e.data.val },
				success: function(content)
				{
					fader.stop();
					var $res = $(content).find("rating");
					$.irating.setRating(opts.$c, $res.attr('rating'), $res.attr('votes'));
					opts.$c.find("span.rating-msg").html(opts.msga);
					$(".usrating[uid=" + $res.attr('author') + "]").each(function() {
						$.irating.setRating($(this), $res.attr('author_rating'), $res.attr('author_votes'));
					});
				},
				error: function()
				{
					//fader.stop();
				}
			});
		}
	}
})(jQuery);
















(function($) {
	/**
	* ajax comments paging plugin
	*/
	$.fn.cpaging = function(settings)
	{
		settings = $.extend({ $container: $(this) }, settings);
		$(settings.navContainer, this).find("a").each(function()
		{
			var re = new RegExp(settings.navParamName + "=(.*)[\&|\#|$]", "i");
			var pageNo = String(this.href).match(re);
			pageNo = (pageNo && typeof(pageNo) == 'object' && pageNo.length > 1) ? pageNo[1] : 1;

			$(this).attr("pageno", pageNo).click(function()
			{
				settings.$container.html('<br><div style="background-color:#EEF4FF;width:100%;"><table align="center" celspacing="10" cellpadding="5"><tr><td><img src="/jscript/images/loading2.gif"></td><td>Идет загрузка ' + $(this).attr("pageno") + '-ой страницы..</td></tr></table></div><br>');
				$.ajax({
					url: settings.pageUrl + "&" + settings.navParamName + "=" + $(this).attr("pageno"),
					success: function(content)
					{
						var $div = $('<div/>').append(String(content).replace(/<script(.|\s)*?\/script>/gi, ""));
						settings.$container.empty().html($div.find(settings.dest).html());
						$.globalEvalHtml(content); // выполнение скриптов в подгруженном контенте
					},
					error: function() { }
				});
				return false;
			});
		});
	};

	/**
	* jQuery global eval scripts from html
	*/
	$.globalEvalHtml = function(content)
	{
		var re = new RegExp('<script[^>]*>([\\S\\s]*?)<\/script>', 'img');
		var re2 = new RegExp('<script[^>]*>([\\S\\s]*?)<\/script>', 'im');
		var tags = String(content).match(re);
		$.each(tags || [], function() {
			$.globalEval((this.match(re2) || ['', ''])[1]);
		});
		return content;
	}

	/**
	* jQuery Timer plugin v0.1
	*/
	 $.timer = function (interval, callback)
	 {
		var interval = interval || 100;

		if (!callback)
			return false;

		_timer = function (interval, callback) {
			this.stop = function () {
				clearInterval(self.id);
			};

			this.internalCallback = function () {
				callback(self);
			};

			this.reset = function (val) {
				if (self.id)
					clearInterval(self.id);
				var val = val || 100;
				this.id = setInterval(this.internalCallback, val);
			};

			this.interval = interval;
			this.id = setInterval(this.internalCallback, this.interval);
			var self = this;
		};

		return new _timer(interval, callback);
	 };




 /**
 *
 * multiply photos upload plugin
 *
 */
	$.fn.mupload = function(opts) {
		var $container = $(this);

		var settings = $.extend({
			max: 20,
			isEdit: parseInt($container.find("input[name=id]").val()) > 0,
			frame: $('<iframe id="muploadframe" name="muploadframe" style="visibility:hidden;height:1px;"/>')
			}, opts);

		var upCount = 0, curSize = 0;

		$container[0].target = settings.frame.attr("name");

		$container.submit(function() {
			$container.find("input:submit,a.photo-item-add,a.photo-item-del").css("visibility", "hidden");
			$container.trigger("submitPhoto");
			return false;
		});

		$container.bind("submitPhoto", function(e) {
			settings.frame.appendTo("body");

			var $item = $container.find("div.photo-item:eq(" + upCount + ") .photo-item-inner").css("position", "relative");
			window.scrollTo(0, $item.offset()['top'] - 10);

			// disable all elements
			$container.find("div.photo-item").each(function() {
				$(this).find("textarea,input").attr("disabled", true);
			});
			//enable current
			$item.find("textarea,input").removeAttr("disabled");

			var msgLoading = settings.isEdit ? "Сохранение.." : "Загрузка фото (" + (upCount+1) + " из " + curSize  + ")..";
			var $d1 = $('<div style="position:absolute;z-index:999;top:0px;left:0px;width:100%;background-color:#fff;"/>')
				.css({ opacity: 0.7, height: $item[0].offsetHeight }).prependTo($item);
			var $d2 = $('<table width="100%" style="position:absolute;z-index:1000;top:0px;left:0px;"><tr><td align="center" width="100%" style="font-weight:bold;color:red;"><img align="absmiddle" src="/jscript/images/loading-img.gif">&nbsp;&nbsp;' + msgLoading + '</td></tr></table>')
				.css({ height: $item[0].offsetHeight }).prependTo($item);

			settings.frame.load(function() {
				settings.frame.ready(function() {
					if (!settings.isEdit) { // если это не редактирование
						if (++upCount <= curSize) {
							var idoc = null;
							if (settings.frame[0].contentDocument) idoc = settings.frame[0].contentDocument;
							else if (settings.frame[0].contentWindow) idoc = settings.frame[0].contentWindow.document;
							else idoc = settings.frame[0].document;

							var $item = $container.find("div.photo-item:eq(" + (upCount-1) + ") .photo-item-inner").html(idoc.body.innerHTML);
							$d1.remove(); $d2.remove();
							settings.frame.remove();

							if (upCount < curSize) $container.trigger("submitPhoto"); // запуск загрузки следующей фотки
						}
					}
					else location.href = location.href + "&hash=" + Math.random(); // необходимо обновиться страницу с сервера
				});
			});



			$container[0].submit(); // запуск загрузки первой фотки


		});

		$container.bind("recalculate", function() {
			$(this).find("span.photo-item-num").each(function(i) {
				$(this).html(i + 1);
				curSize = i + 1;
			});
		});

		$container.find("div.photo-item:first")
			.find("a.photo-item-add").click(function() {

				if ($container.find("div.photo-item").length >= settings.max)	{
					alert("Нельзя одновременно закачать более " + settings.max + " фотографий!");
					return false;
				}

				if ($.browser.msie && $.browser.version > 6) {
					alert("К сожалению в Internet Explorer версии 7 и 8 не работает множественная загрузка фото. Используйте другие браузеры, такие как FireFox, Opera, Google Chrome или более ранние версии IE.");
					return false;
				}
				var $item = $(this).parents(".photo-item"); // элемент, где нажали на +
				var $first = $(".photo-item:first"); // первый элемент, который и будем клонировать
				var $newitem = $first.clone(true).insertAfter($(".photo-item:last")); // новый элемент
				$newitem.find("textarea").val($item.find("textarea").val()) // копировать наименование
				window.scrollTo(0, $newitem.offset()['top'] - 10); // скролл к новому элементу

				if ($.browser.msie) {
					$newitem.find("input:file")
						.val("")
						.click();// в IE работает click!
				} else	{
					$newitem.find("input:file")
						.val("")
						.focus();
				 }

				$container.trigger("recalculate");
			})
			.attr("title", "Добавить форму для закачки еще одного фото")
			.end()
			.find("a.photo-item-del").click(function() {
				if ($container.find("div.photo-item").length == 1) return false;
				var $item = $(this).parents("div.photo-item:first");
				$item.remove();
				$container.trigger("recalculate");
			})
			.attr("title", "Удалить форму");



		$container.trigger("recalculate");
		$container.find("input:submit").removeAttr("disabled");
	}



	/**
	* block element plugin
	*/
	$.fn.extend({
		block: function(opts) {
			return this.each(function() {
				if (this.$blockOpts) $(this).unblock();
				opts = $.extend({ msg: "загрузка..", opacity: 0.5, opacityColor: '#fff' }, opts);
				var d1 = $('<div style="position:absolute;z-index:999;top:0px;left:0px;width:100%;background-color:' + opts.opacityColor + ';"/>')
					.css({ opacity: opts.opacity, height: this.offsetHeight }).prependTo($(this).css("position", "relative"));
				var d2 = $('<table width="100%" style="position:absolute;z-index:1000;top:0px;left:0px;"><tr><td align="center" width="100%"">' + opts.msg + '</td></tr></table>')
					.css({ height: this.offsetHeight }).prependTo($(this));
				var d3 = $(this).find("select").css("visibility", "hidden");
				this.$blockOpts = $.extend({ divs: [d1,d2,d3] }, opts);
			});
		},
		unblock: function() {
			return this.each(function() {
				if (this.$blockOpts) {
					if (this.$blockOpts.divs[2]) this.$blockOpts.divs[2].css("visibility", "visible");
					if (this.$blockOpts.divs[1]) this.$blockOpts.divs[1].remove();
					if (this.$blockOpts.divs[0]) this.$blockOpts.divs[0].remove();
					this.$blockOpts = null;
				}
			});
		}
	});
})(jQuery);


jQuery(function($) {
/*blog-code*/
$(".tog").click(function()
 {
 $(".b-codes textarea").text($("#cc2").html());
 var targ = "#" + $(this).attr('targ');
 $(targ + "p").addClass("togframe");
 $(targ).toggle('fast',function(){
   if ($(targ + ":visible").length <= 0) {$(targ + "p").removeClass("togframe")}
                                        });
 return false;
 });
$(".f-tab").click(function()
 {
  $(this).parent("div.tabbs").children(".f-tab").removeClass('f-act');
  $(this).addClass('f-act');
  $(this).parent().parent("div.tabbed").children(".tabbcontent").children(".cc").css('display','none');
  var targ = "#" + $(this).attr('targ');
  if (targ == '#tt2')
   {
   $("#tt2").load('/main/topic_cloud_ajax.asp');
   }
  $(targ).css('display','block');
  return false;
 });
 $(".b-codes textarea").bind('click mouseenter', function() {$(this).focus().select();});






	// чтобы было видно имя файла в полях ввода типа file
	//$(".file").bind("blur", function(e) {setCursorPosition(this, this.value.length-1, this.value.length-1);});
	//$(".file").bind("change", function(e) {this.focus(); this.value=this.value;alert(this.value);});
	//$(".file").bind("change", function(e) {$(this).setCursorPosition(this.value.length);});
	//$(".file").bind("blur", function(e) {$(this).setCursorPosition(this.value.length);});

});


function setCursorPosition(oInput, oStart, oEnd) {
	if (oInput.setSelectionRange) {
		oInput.setSelectionRange(oStart,oEnd);
	} else if (oInput.createTextRange) {
		range = oInput.createTextRange();
		range.collapse(true);
		range.moveEnd('character', oEnd);
		range.moveStart('character',oStart);
		range.select();
	}
}





// Открытие окна с центрированием, работает в FF
function WindowOpen(url, title, w, h) {
	if (String(url).length == 0) return false; // нечего открывать
	if(h == 0) h = Math.floor(screen.height * 0.95);
	var left = (screen.width/2)-(w/2);
	var top = (screen.height/2)-(h/2);
	if(top < 0) top = 0;
	if(left < 0) left = 0;
	title = String(title);
	title = title.replace(/\s/gi,"_"); // Calling window.open with spaces in the window name will error is IE but works fine in Firefox
	var win = window.open(url, title, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=n, width=" + w + ", height=" + h + ", top=" + top + ", left=" + left);
	if (win) {
    win.focus();
	} else {
    alert('Отключите блокировщик всплывающик окон в настройках браузера\nPlease turn off pop-up window blocker in browser options');
	}
	return win;
}







function act(frm, sAction, sConfirm)
{
	var j=0;

	if (frm.elements.check.checked){j++;}
	for (var i=0; i<frm.elements.check.length; i++)
	{
		if (frm.elements.check[i].checked) {j++;}
	}

	if (j>0){
		if (sConfirm!=''){
			sConfirm=sConfirm.replace('%d',j);
			if (confirm(sConfirm)){
				frm.action.value=sAction;
				frm.submit();
			}
		}
		else{
			frm.action.value=sAction;
			frm.submit();
		}

	}
	else{
		alert('Ошибка! Выберите записи для операции!');
	}

	return false;
}
