/*
	Depends of:
		jQuery
		jQuery Metadata
		jQuery UI
		jQuery Tools
		jQuery Tooltip
		Highslide JS

*/




/*
	В консоли используй:
	console.info(a); —  информация;
	console.warn(b); —  предупреждение;
	console.error(c); — сообщение об ошибке.
	console.log(a); — вывести в консоль значение переменной а ;
*/
// Заглушки для браузеров у которых нет консоли
if (typeof(console) == 'undefined') {
	var console = {
		log: function(message) {},
		info: function(message) {},
		warn: function(message) {},
		debug: function(message) {},
		error: function(message) {alert(message);},
		alert: function(message) {alert(message);}
	}
}


function debug(obj)	{ // Выводит все свойства объекта DOM-модели
	var str = typeof(obj);
	for (i in obj) {	str = str + ', ' + i;}
	console.error(str);
}






















/****************************

		SelectAll.js

*/


function SelectAll(form, state, check) {
  	if (arguments.length == 2)
	{ var ch_name = 'check' } else
	{ var ch_name = check };
    for (i=0; i<form.elements.length; i++) {
      if (form.elements[i].name == ch_name) {
        var item = form.elements[i];
        item.checked = state;}}};


function CheckAction(form, check_name, text) {
	for (i=0; i<form.elements.length; i++) {
		if (form.elements[i].name == check_name) {
			var item = form.elements[i];
			if (item.checked) {
				if (confirm ( text )) { return true; } else { return false; }; }}
	};
	return false;
};


//Функция выделяет все элементы объекта select в заданной форме
function selectAllOptions(iForm, iSelect, iIndex)
{
  var obj = document.forms[iForm].elements[iSelect];
  for	(var i=iIndex; i<obj.options.length; i++) {obj.options[i].selected = true;}
}

//Функция возвращает [true/false] - есть ли выделенный элемент заданного списка
function checkOptionsAndSend( iForm, iSelect)
{
  var obj = document.forms[iForm];
  var vSelected = obj.elements[iSelect].selectedIndex;
  if (vSelected > -1)
  {
    obj.submit();
  }
  return false;
}

//Функция возвращает [true/false] - есть ли выделенный элемент заданного списка
function setIMP( iForm, iAction, iRec) {
  var obj = document.forms[iForm];
  obj.elements['action'].value = iAction;
  obj.elements['check'][iRec].checked = 'on';
  obj.submit();
  return false;
}




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.elements['action'].value = sAction;
				frm.submit();
			}
		}	else {
			frm.elements['action'].value = sAction;
			frm.submit();
		}
	} else {
		alert('Выберите записи для операции');
	}
	return false;
}


function toggleOptions(option,titlebar) {
	drawer = document.getElementById(option);
	bar = document.getElementById(titlebar);

	if (drawer.style.display == 'block') {
		drawer.style.display = 'none';
		//if (bar) bar.className = 'none';
	} else {
		drawer.style.display = 'block';
		//if (bar) bar.className = 'closed';
	}
}



function zr(i) {
	var s = "";
	s += i;
	if(s.length==1) s = "0" + s;
	return s;
}


function CurrDate() {
   var d, s = "";											// Declare variables.
   d = new Date();										// Create Date object.
   s += zr(d.getDate()) + ".";				// Get day
	 s += zr(d.getMonth() + 1) + ".";		// Get month
   s += d.getFullYear() + " ";				// Get year
	 s += zr(d.getHours()) + ":";				// Get hours
	 s += zr(d.getMinutes());						// Get minutes
   return(s);													// Return date
}

function CurrDateTime() {
   var d, s = "";											// Declare variables.
   d = new Date();										// Create Date object.
   s += zr(d.getDate()) + ".";				// Get day
	 s += zr(d.getMonth() + 1) + ".";		// Get month
   s += d.getFullYear() + " ";				// Get year
	 s += zr(d.getHours()) + ":";				// Get hours
	 s += zr(d.getMinutes()) + ":";			// Get minutes
	 s += zr(d.getSeconds());     			// Get secunds
   return(s);													// Return date
}


/*

		SelectAll.js

****************************/
































jQuery(document).ready(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=\'/main/randomimg/?r=\' + Math.floor(Math.random()*10000);" align="absmiddle" hspace="4">');

	// Voting
	$(".voting").voting();

	// Dialog widgets helper plugin
	$("a[dialog],button[dialog]").dialog2({modal: true});

	// Login form
	$.updMsg();

	// Slide-plugin - раскрывающиеся вниз контекстное меню
	$('.slide>a').slide();

	// Nocache plugin
	$("a.nocache").nocache();

	// 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();});


	/* Подстветка строк в таблице при наведении */
	$('table.trhover tr').hover(function(){
		$(this).find("td").addClass('hover');
	},function(){
		$(this).find("td").removeClass('hover')}
	);


});





















(function($) {




	/****************************

			Resize big plugin - resize big images and objects
			Sample:

				jQuery(document).ready(function($){$(".blog-content").resizebig({maxWidth: 540});});

	*/

	$.fn.resizebig = function(opts) {

		var options = {maxWidth: 540};
		$.extend(options, opts);

		var $container = $(this);
		// resize big images
		$container.find("img").each(
			function() {
				if(!(/\/images\/comment\//i.test(this.src)) && !(/\/images\/smile\//i.test(this.src))) {
					if(parseInt(this.width,10) > options.maxWidth) {
						this.width = options.maxWidth;
					} else {
						if (parseInt(this.width,10) == 0) {
							$(this).load(function() {
								$(this).unbind("load");
								if(parseInt(this.width,10) > options.maxWidth) this.width = options.maxWidth;
							});
						}
					}
				}
			}
		);

		// resize big objects
		$container.find('embed[src*="youtube.com"]').each(
			function() {
				if (parseInt($(this).attr('width'),10) > options.maxWidth) {
					sizeRatio = $(this).attr('width') / $(this).attr('height');
					newWidth = options.maxWidth;
					newHeight = Math.round(newWidth / sizeRatio);
					$(this)
						.attr('width', newWidth)
						.attr('height', newHeight)
						.parent()
						.attr('width', newWidth)
						.attr('height', newHeight);
				}
			}
		);
	}







	/****************************

			Nocache plugin - add param with random value to avoid cache in browser
			Sample:

				$(document).ready(function() {$("a.nocache").nocache({param: 'rnd', value: Math.floor(Math.random()*10000)});});

	*/
	$.fn.nocache = function(opts) {
		var options = {param: 'r', value: Math.floor(Math.random()*10000)};
		$.extend(options, opts);

		var removeURLParameter = function (url, parameter) {
			var urlparts= url.split('?');
			if (urlparts.length>=2) {
					var urlBase=urlparts.shift(); //get first part, and remove from array
					var queryString=urlparts.join("?"); //join it back up

					var prefix = encodeURIComponent(parameter)+'=';
					var pars = queryString.split(/[&;]/g);
					for (var i= pars.length; i-->0;)               //reverse iteration as may be destructive
							if (pars[i].lastIndexOf(prefix, 0)!==-1)   //idiom for string.startsWith
									pars.splice(i, 1);
					url = urlBase+'?'+pars.join('&');
			}
			return url;
		}

		return this.each(function(){
			var currHref = $(this).attr("href");

			// avoid link with href like href="Javascript:YourFunction();"
			if(!currHref.match(/^javascript:/ig)) {
				currHref = removeURLParameter(currHref, 'r');
        if (currHref.charAt(currHref.length - 1) === '?') //Very unlikely
					$(this).attr("href",currHref + options.param + "=" + options.value);
        else if (currHref.indexOf('?') > 0)
					$(this).attr("href",currHref + '&' + options.param + "=" + options.value);
        else
					$(this).attr("href",currHref + '?' + options.param + "=" + options.value);
			}
		});
	}






	/****************************

			Addtocopy plugin enhance by mail.ru
				http://tops.net.ua/jquery_addtocopy/
				http://habrahabr.ru/blogs/jquery/101763/
			Sample:
				$('body').addtocopy({msg: '<br>Подробнее: <a href="'+window.location.href+'">'+window.location.href+'</a>', minlen:35});

	*/
	$.fn.addtocopy = function(usercopytxt) {
		var options = {msg: '<br><br>Подробнее: <a href="'+window.location.href+'" target="_blank">'+window.location.href+'</a><br>', minlen: 25};
		$.extend(options, usercopytxt);
		return this.each(function(){
			//$(this).mousedown(function(){$("span.dirty-clipboard").remove();});
			$(this).mouseup(function(){
				var t,D,w,y;
				$("span.dirty-clipboard").remove();
				if(window.getSelection){
					t=window.getSelection();
					w=t.toString();
					if(!w||w.length<options.minlen) return;
					D=t.getRangeAt(0);
					w=D.cloneRange();
					w.collapse(false);
					y=$('<span class="dirty-clipboard">'+options.msg+'</span>').css("position","absolute")[0];
					w.insertNode(y);
					D.setEndAfter(y);
					t.removeAllRanges();
					t.addRange(D);
				}
				else if(t=document.selection){
					D=t.createRange();
					w=D.text;
					if(!w||w.length<options.minlen) return;
					w=D.duplicate();
					w.collapse(false);
					w.pasteHTML('<span class="dirty-clipboard" style="position: absolute;">'+options.msg+"</span>");
					D.setEndPoint("EndToEnd",w);
					D.select();
				}
				$("span.dirty-clipboard").css({overflow:"hidden",width:"1px",height:"1px"});
			});
		});
	}


	// Возвращает выделенный текст
	function getSel(){
		var w=window,d=document,gS='getSelection';
		return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
	}

	function getSelPrevNext() {
		var range, prev='', next='', selection='';
		if (window.getSelection) {
			selection = window.getSelection();
			if(selection.getRangeAt) {
				range = selection.getRangeAt(0);

				if (window.opera)
					prev = selection.getRangeAt(0);
				else
					prev=document.createRange();

				prev.setStartBefore(range.startContainer);
				prev.setEnd(range.startContainer,range.startOffset);
				prev = prev.toString();

				if (prev.length>20)
					prev = prev.substring(Math.max(prev.length-30,0),prev.length).replace(/^\S{1,10}\s+/,"");

				if (window.opera)
					next = selection.getRangeAt(0);
				else
					next = document.createRange();

				next.setStart(range.endContainer, range.endOffset);
				next.setEndAfter(range.endContainer);
				next = next.toString();
				if (next.length > 50)
					next = next.toString().substring(0,30).replace(/\s+\S{1,10}$/,"");
			}
		} else if (document.selection.createRange) {
			selection = document.selection.createRange();
			selection.expand("word");
			prev = document.selection.createRange();
			prev.moveStart("character",-20);
			prev.setEndPoint('EndToStart',selection);
			prev.expand("word");
			prev = prev.text;

			next = document.selection.createRange();
			next.moveEnd("character", 20);
			next.setEndPoint('StartToEnd',selection);
			next.expand("word");
			next = next.text;
			selection = selection.text;
		}
		return ('' + prev + '[' + selection + ']' + next).replace(/(^\s+|\s+$)/g,'');

	}


	/****************************
			Send mistake plugin
			Сообщение об ошибке или опечатке в тексте

			Sample:
				$.sendmistake();
	*/
	$.sendmistake = function(opts) {
		var options = $.extend({
			title: "Сообщение об ошибке или опечатке в тексте",
			href: "/main/sendmistake.asp",
			width: 430,
			height: 240,
			modal: true,
			resizable: false,
			open: function() {$(".ui-dialog").css("box-shadow","#888888 15px 15px 15px");}, // shadow
			//beforeClose: function() {$(this).remove();}
			close: function() {$(this).dialog('destroy').remove();}
		}, opts);
		// Register keypress events on the whole document
		$(document).keypress(function(event) {
			if (event.ctrlKey && (event.keyCode == 13 || event.keyCode == 10)) {
				//$('body').attr('sendmistake', getSel());
				if (getSel().length > 0) {
					$('body').attr('sendmistake', getSelPrevNext()); // передача текста выделения через атрибут боди родителя
					$('<div style="display: hidden; overflow: hidden;" title="' + options.title + '"><iframe frameborder="0" src="' + options.href + '" style="border-width:0; margin:0;padding:0;width:100%;height:100%;"></iframe></div>').dialog(options);
				}
			}
		});
	}






	/****************************

		Copy warning plugin

		Sample:
			$.copywarning();

	*/
	$.copywarning = function(opts) {
		$.extend($.easing,{
			easeOutBounce: function (x, t, b, c, d) {
				if ((t/=d) < (1/2.75)) {
					return c*(7.5625*t*t) + b;
				} else if (t < (2/2.75)) {
					return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
				} else if (t < (2.5/2.75)) {
					return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
				} else {
					return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
				}
			}
		});

		opts = $.extend({
			msg: '<h1>Внимание!</h1><p>При копировании или цитировании, обязательно указывайте гиперссылку</p>',
			Timeout: 5000, // 5 seconds
			AnimateDuration: 500,
			margin: '30px', //
			place: 3, // Place of warning panel, number of screen corner 1,2,3,4
			id: 'copy-panel'
			}, opts);

		$('body').bind('copy',function() {
			if ($('#' + opts.id).length == 0) {
				var $container = $('<div id="' + opts.id + '">' + opts.msg + '</div>').appendTo('body');
				var prop = {
					containerWidth: parseInt($container.outerWidth(), 10) + 'px',
					containerHeight: parseInt($container.outerHeight(), 10) + 'px'
				};

				var css = {'display': 'block'};

				if(opts.place === 'topleft' || opts.place === 1) {
					prop['AnimationProperty'] = 'top';
					css[prop.AnimationProperty] = '-' + prop.containerHeight;
					css['left'] = opts.margin;
				}

				if(opts.place === 'topright' || opts.place === 2) {
					prop['AnimationProperty'] = 'top';
					css[prop.AnimationProperty] = '-' + prop.containerHeight;
					css['right'] = opts.margin;
				}

				if(opts.place === 'bottomright' || opts.place === 3) {
					prop['AnimationProperty'] = 'bottom';
					css[prop.AnimationProperty] = '-' + prop.containerHeight;
					css['right'] = opts.margin;
				}

				if(opts.place === 'bottomleft' || opts.place === 4) {
					prop['AnimationProperty'] = 'bottom';
					css[prop.AnimationProperty] = '-' + prop.containerHeight;
					css['left'] = opts.margin;
				}

				$container.css(css);
				var AnimateCSSMap = {};
				AnimateCSSMap[prop.AnimationProperty] = opts.margin;

				$container.animate(AnimateCSSMap, opts.AnimateDuration, 'easeOutBounce' , function() {
						setTimeout(function(){
							AnimateCSSMap[prop.AnimationProperty] = "-" + prop.containerHeight;
							$container.animate(AnimateCSSMap, opts.AnimateDuration, function () {
									$container.remove();
									opts.place = (opts.place) % 4 + 1;
								})
						}, opts.Timeout);
				});
			}
		});
	}





	/****************************

		Login form plugin

		Sample:
			$.updMsg({intTimeout: 1, intTimeoutErrorStep: 1});

	*/
	$.updMsg = function(opts) {

		if ($('#login-area').length > 0) {

			opts = $.extend({
				url: '/back/ajax-user.asp?mod=login-area',
				intTimeout: 180, // 3 минуты
				intTimeoutErrorStep: 120 // 2 минуты
				}, opts);

			function update() {
				$.ajax({
					url: opts.url,
					data: ({timeout: opts.intTimeout}),
					cache: false,
					dataType: 'html',
					success: function(data)	{
						var ar = data.split('\n');
						var	uid  = isNaN(ar[0]) ? 0 : parseInt(ar[0], 10),
								msgs = isNaN(ar[1]) ? 0 : parseInt(ar[1], 10);

						opts.intTimeout  = isNaN(ar[2]) ? opts.intTimeout : parseInt(ar[2], 10);

						$('#login-area')
							.html(ar[4])
							.find('.logined-user .slide>a')
							.slide();
						// Панель информирования о новых сообщениях
						if (msgs > 0) {
							if ($('#msg-panel').length == 0) {
								$('body').append('<div id="msg-panel"><a class="ico-havenewmail black" href="' + ar[3] + '/back/umsg.asp?mod=msgs&fid=inbox&r=' + Math.floor(100000*Math.random()) + '">Входящие сообщения</a>: <b><span class="new-msg-t">0</span> новых</b></div>');
							}
							$('.new-msg-t').html(msgs);
							$('#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').remove();
						}
						setTimeout(function(){update();}, opts.intTimeout * 1000);
						//console.debug(opts.intTimeout);
					},
					error: function() {
						opts.intTimeout += opts.intTimeoutErrorStep;
						setTimeout(function(){update();}, opts.intTimeout * 1000);
						//console.debug(opts.intTimeout);
					}
				});
				return false;
			}

			update();

			return false;

		}
	}
	// /Login form












	/****************************

		Slide-plugin - раскрывающиеся вниз контекстное меню

		Sample:
			jQuery(document).ready(function($){$(".slide>a").slide();});

	*/
	$.fn.slide = function(opts) {
			return this.each(function(opts) {
				var $container = $(this);
				$container.append('&nbsp;<small>&#x25bc;</small>');
				var $slide = $container.next('ul');
				// ul must exists
				if ($slide.length > 0) {

					function show() {
						if ($slide.css("display")=='none') {
							var offset = $container.offset(),
								left = offset.left,
								top = offset.top + $container.height() + 5;
								$("ul.slide-show").removeClass("slide-show").hide();
								$slide
									.css({top: top + 'px', left: left + 'px'})
									.toggle()
									.addClass("slide-show");
						}
					}

					function hide() {
						if($slide.css("display")!='none')	$slide.hide();
					}

					$container.bind("click mouseover", function () {
						if($slide.css("display")=='none')	show();
						return false;
					});

					$container.bind("mouseover", function () {show();});

					$('body').click(function () {hide();});
				}

			});
		}

	/*

	/ Slide-plugin - раскрывающиеся вниз контекстное меню

	**************************************************************/







	/****************************

			Dialog helper plugin for jQuery UI dialog Widgets
			Sample:
				<a href="" dialog="">Диалог</a>
				<button dialog="href:'/adm/forum/moders.asp', width: 800, height: 700">Добавить модератора</button>
				$(document).ready(function() {
					$("a[dialog],button[dialog]").dialog2({modal: true}); // Dialog helper plugin
				});

	*/
	$.fn.dialog2 = function(opts) {

		var options = $.extend({
			resizable: false,
			width: 350,
			height: 350,
			modal: true,
			ajax: false,
			autoResize: false, // необходимо отладить!
			closeOnEscape: true,
			open: function() {
				$(".ui-dialog").css("box-shadow","#888888 15px 15px 15px"); // shadow
				if(options.autoResize) {
					var $frame = $(this).find("iframe");
					$frame.bind('load', function() {
						$(this).dialog('option', 'width', $frame.contents().width() + 20);
						$(this).dialog('option', 'height', $frame.contents().height() + 60);
					});
				}
			},
			close: function() {$(this).dialog('destroy').remove();}
		}, opts);

		return this.each(function(){
			var $container = $(this),
				$dialog = null,
				o,
				topWindow;

			$container.click(function() {
				o = $.extend({
					title: $container.attr("title")?$container.attr("title"):$container.text(),
					href: $container.attr("href")
				}, options);
				o = $.extend(o, $container.metadata({type: 'attr', name: 'dialog'}));
				topWindow = window.top!=window.self && window.top.jQuery.fn.dialog?window.top:window.self;
				//topWindow.jQuery("#dialog2").remove();
				if (o.ajax) {
					topWindow.jQuery('<div id="dialog2" style="display: hidden; overflow: hidden;" title="' + o.title + '"></div>').dialog(o).load(o.href);
				} else {
					topWindow.jQuery('<div id="dialog2" style="display: hidden; overflow: hidden;" title="' + o.title + '"><iframe frameborder=”0" src="' + o.href + '" style="border-width:0;margin:0;padding:0;width:100%;height:100%;"></iframe></div>').dialog(o);
				}

				return false;
			});

		});
	}

	/*

	/ Dialog helper plugin for jQuery UI dialog widgets

	**************************************************************/








	/****************************

		Scroll2-plugin for move block during the window scroll
		Ragged scroll

		Sample:
			jQuery(document).ready(function($){$("#yndexdirect").scroll2();});

	*/
	$.fn.scroll2 = function(opts) {

		// return original object to support chaining
		return this.each(function(opts) {
			var $container = $(this);
			var $parent = $(this).parent();
			$container.css("position","relative");
			var top = $container.offset().top;
			var left = $container.offset().left;
			var width = $container.width();
			$container.css({width: width});
			var position = "relative";
			//var isNoPositionFixed = (navigator.platform.indexOf("iPad") != -1 || navigator.platform.indexOf("iPod") != -1 || navigator.platform.indexOf("iPhone") != -1);
			//returns true if user is using one of the following mobile browsers
			var isNoPositionFixed = navigator.userAgent.match(/iPad|iPhone|iPod/i)

			function scroll() {
//				console.info('pageYOffset:' + window.pageYOffset + ' innerHeight:' + window.innerHeight + ' $(window).scrollTop():' + $(window).scrollTop());
				var scrollTop = $(window).scrollTop();


				if (scrollTop > top && position == "fixed" && isNoPositionFixed) {
					$container.css({top: scrollTop - top});
				} else if (scrollTop > top && position == "relative") {
					top = $container.offset().top;
					left = $container.offset().left;
					width = $container.width();
					if (isNoPositionFixed) {
						$container.css({position: "relative", top: scrollTop - top});
					} else {
						$container.css({position: "fixed", top: 0, left: left, width: width});
					}
					position = "fixed";
				} else if (scrollTop <= top && position == "fixed") {
					$container.css({position: "relative", top: 0, left: 0, width: "auto"});
					top = $container.offset().top;
					left = $container.offset().left;
					width = $container.width();
					position = "relative";
				}
			};

			scroll();

			$(window).bind("scroll resize", scroll);

		});
	};






	/****************************

		VOTING-plugin
		AJAX подгрузка формы голосования и результатов

		Sample:
			jQuery(document).ready(function($){$(".voting").voting();});

	*/
	$.fn.voting = function() {
		// return original object to support chaining
		return this.each(function() {
			if(this.length == 0){return{};} // без этой строки ошибка в плагине metadata
			var $container = $(this);
			var opts = $container.metadata({type: 'attr', name: 'voting'});
			opts = $.extend({
				url: '/back/ajax-voting.asp',
				qs: ''
				}, opts);
			opts.qs = opts.id ? '?id=' +  opts.id : '';
			opts.qs += opts.ruser ? '&ruser=' +  opts.ruser : '';

			//console.info(opts.id);
			//console.info(opts.qs);

			$container.load(opts.url + opts.qs, function() {
				containerLoad();
			});

			//
			function containerLoad() {
				$container.find('form').submit(function() {
					var $frm = $(this);
					//console.info($frm.find(":input:checked").length);

					if ($frm.find(":input:checked").length > 0)	{
						$frm.find("#voteButton").attr("disabled", "disabled").attr("value", "Подождите...");

						opts.qs = opts.qs=='' ? '?' + $frm.serialize() : opts.qs + '&' + $frm.serialize();
						//console.info(opts.url + opts.qs);

						$container.load(opts.url + opts.qs,
							function() {
								//console.info("Голос принят");
								containerLoad(); // рекурсивный вызов, чтобы подцепить событие к вновь подгруженному HTML
							});

					}
					else
					{
						alert('Пожалуйста, выберите вариант ответа');
					}
					return false;
				});
			}
		});
	};













	/****************************

		star rating plugin


	*/

	$.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/?" + opts.url : null;
			}
			$.irating.install($(this), opts);
		});
	};
	$.irating = {
		install : function($el, settings)	{
			var opts = $.extend({ maxVal: 5, val: 0, votes: 0, msgb: "", msga: "", isStatic: false, rmsg: false, className: null}, settings);
			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();
				}
			});
		}
	};






	/**
	* ajax comments paging plugin
	*/

	$.fn.cpaging = function(settings)	{
		settings = $.extend({ $container: $(this) }, settings);


		// Загрузить страницу с комментариями
		function loadpage(pageno) {
			settings.$container.html('<div class="comment-loading"><span>Загрузка ' + pageno + '-ой страницы комментариев</span></div>');
			$.ajax({
					url: settings.pageUrl + "&" + settings.navParamName + "=" + pageno,
					success: function(content) {
						var $div = $('<div/>').append(String(content).replace(/<script(.|\s)*?\/script>/gi, ""));
						//settings.$container.empty().html($div.find(settings.dest).html());	// в страницу вставляю без скриптов
						settings.$container.empty().html(String(content).replace(/<script(.|\s)*?\/script>/gi, ""));	// в страницу вставляю без скриптов
						$.globalEvalHtml(content);																					// но все равно выполняю их
					},
					cache: false,
					error: function() {
						//console.debug("Error in ajax comments paging plugin");
					}
				});
			return false;
		}

		$(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()	{
				loadpage($(this).attr("pageno"));
				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);
	 };




 /********************************************************************************************
 *
 * OLD 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", "disabled");
			});
			//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(".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);
















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

	WindowOpen("wwww", "SendMistake", 450, 260, {scrollbars: 'no', resizable: 'no'});

*/
function WindowOpen(url, title, w, h, opt) {
	var options = {toolbar: 'no', location: 'no', directories: 'no', status: 'no', menubar: 'no', scrollbars: 'yes', resizable: 'yes', copyhistory: 'no'};
	jQuery.extend(options, opt);
	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=" + options.toolbar + ", location=" + options.location + ", directories=" + options.directories + ", status=" + options.status + ", menubar=" + options.menubar + ", scrollbars=" + options.scrollbars + ", resizable=" + options.resizable + ", copyhistory=" + options.copyhistory + ", 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.elements['action'].value = sAction;
				frm.submit();
			}
		}	else {
			frm.elements['action'].value = sAction;
			frm.submit();
		}
	} else {
		alert('Выберите записи для операции');
	}
	return false;
}




/* BG cache */

try{ if (typeof(document.execCommand && !window.XMLHttpRequest)!="undefined") document.execCommand("BackgroundImageCache", false, true) }
catch(er) { }

/* / BG cache */
