﻿function BookmarkLink(sUrl, sTitle, a) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(sTitle, sUrl, "");
	} else if (window.external)
	{ // IE Favorite
		window.external.AddFavorite(sUrl, sTitle);
	} else if (window.opera && window.print) { // Opera Hotlist
		a.href = sUrl;
		a.rel = "sidebar";
		a.title = sUrl + ',' + sTitle;
		return true;
	}
}
function checkBookmarkLink(idStr) {
	if (!(window.sidebar || (window.external && document.all) || (window.opera && window.print)))
		document.getElementById(idStr).style.display = 'none';
}

function HomePage(objSrc)
{
	var homepage = "http://www.buhonline.ru";
	if (objSrc.style.behavior)
	{ // MSIE
		objSrc.setHomePage(homepage);
	} else if (netscape && netscape.security && netscape.security.PrivilegeManager && navigator.preference)
	{ // Mozilla/FireFox
		netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
		navigator.preference("browser.startup.homepage", homepage);
	}
}
function checkHomePage(idStr)
{
	if (!(document.getElementById(idStr).style.behavior))
	{
		try { netscape; } catch (e) { document.getElementById(idStr).style.display = 'none'; return 0; }
		if (netscape && netscape.security && netscape.security.PrivilegeManager && navigator.preference)
		{
			try
			{
				netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesWrite");
			} catch (e) { document.getElementById(idStr).style.display = 'none'; }
		} else
		{
			document.getElementById(idStr).style.display = 'none';
		}
	}
}

function AccountShowForm() {
    $.blockUI({ message: $('#enterBlock'), css: { top: '100px', left: '50%', margin: '0 -190px 0'} });
}

function KEShowForm(region, urlRegions, urlKEEntryPoints)
{
	LoadRegions(urlRegions, 'keRegionSelect', function() { BuildRegionSelect(locationRegions, 'keRegionSelect', region, 2) });
	GetKEEntryPints('linkContainer', region, urlKEEntryPoints);
	$.blockUI({ message: $('#keEnter'), css: { top: '37px', right: '30%', left: '35%'} });
	return false;
}


function PublicationApplyRating(rating, ratingContainerId)
{
	var ratingStars = $("#" + ratingContainerId + " img");
	var ratingContainer;
	if (ratingStars.length == 0) 
	{
		ratingContainer = $("#" + ratingContainerId);
		ratingContainer[0].innerHTML = "";
	}
	for (var i = 1; i <= 5; i++) 
	{
		var fileName = i <= rating ? "rating-green.gif" : "rating-gray.gif";
		if (ratingStars.length > 0) 
			ratingStars[i - 1].src = "/theme/images/" + fileName;
		 else 
			ratingContainer.append("&nbsp;<img src='/theme/images/" + fileName + "' alt=''/>");
	}
}

function PublicationVoteAsync(rateButtonsContainerId, ratingContainerId, url)
{
	VoteAsync(rateButtonsContainerId, ratingContainerId, url, PublicationApplyRating);
}

function ContestVoteAsync(rateButtonsContainerId, ratingContainerId, url)
{
	VoteAsync(rateButtonsContainerId, ratingContainerId, url, function(rating, ratingContainerId)
	{
		$("#" + ratingContainerId)[0].innerHTML = "Спасибо, ваш голос учтен.<br />Сейчас у этой работы  уже&nbsp;<b>" + rating + "</b>&nbsp;голос" + VoteGetOfWordAlertNumberEnding(rating, "", "а", "ов") + "!";
	});
}

function VoteAsync(rateButtonsContainerId, ratingContainerId, url, ApplyRating)
{
	$("#" + rateButtonsContainerId).hide();
	$.post(url, '', function(data)
	{
		try
		{
			var rating = new Number(data);
			ApplyRating(rating, ratingContainerId);
		} catch (e) { }
	});
}

function VoteGetOfWordAlertNumberEnding(number, ending1, endingGT1LV5, endingGT5Or0)
{
	if (number > 5 && number <= 20)
		return endingGT5Or0;
	var text = new String(number);
	var lastDigit = new Number(text.substr(text.length - 1, 1));
	if (lastDigit == 1)
		return ending1;
	if (lastDigit > 1 && lastDigit < 5)
		return endingGT1LV5;
	return endingGT5Or0;
}

function GetCities(citySelectId, regionId, url, selectedCityId)
{
	var citySelect = $("#" + citySelectId);
	var c = citySelect.parent();
	BlockElement(c);
	$("#" + citySelectId + " > option").remove();
	var centerId = GetRegionCenterId(regionId);
	$.post(url + '/' + regionId, '', function(data)
	{
		try
		{
			var cities = eval(data);
			var selectedCityIndex = GetCityIndex(cities, selectedCityId);
			if (selectedCityIndex < 0)
			{
				if (centerId) // Если есть город по умолчанию
					selectedCityIndex = GetCityIndex(cities, centerId);
				else
					selectedCityIndex = 0;
			}
			for (var i = 0; i < cities.length; i++)
				citySelect.append("<option value=" + cities[i].id + ">" + cities[i].value + "</option>")
			citySelect.get(0).scrollTop = 0;
			if (selectedCityIndex >= 0)
				citySelect.get(0).options[selectedCityIndex].selected = true;
		} catch (e) { }
		c.unblock();
	});
}

function GetCityIndex(cities, cityId)
{
	for (var i = 0; i < cities.length; i++)
	{
		if (cities[i].id == cityId)
			return i;
	}
	return -1;
}

function GetRegionCenterId(regionId)
{
	for (var i = 0; i < locationRegions.length; i++)
	{
		if (locationRegions[i].id == regionId)
			return locationRegions[i].centerId;
	}
	return null;
}

function GetKEEntryPints(linkContainerId, regionId, url)
{
	var linkContainer = $("#" + linkContainerId);
	BlockElement(linkContainer);
	$("#" + linkContainerId + " > li").remove();
	$.post(url + '/' + regionId, '', function(data)
	{
		try
		{
			var keEntryPoints = eval(data);
			for (var i = 0; i < keEntryPoints.length; i++)
				linkContainer.append("<li><a href='" + keEntryPoints[i].href + "' target='_blank' onclick='$.unblockUI();'>" + keEntryPoints[i].value + "</a>&rarr;</li>");
		} catch (e) { }
		linkContainer.unblock();
	});
}

var locationRegions = [];

function BlockElement(elementQJ)
{
	elementQJ.block({ message: "<img src='/theme/images/ajax-loader.gif' />",
		centerX: true,
		centerY: true,
		fadeOut: 0,
		fadeIn: 0,
		css: { width: '100%', textAlign: 'center' },
		overlayCSS: { backgroundColor: '#fff', opacity: '1' }
	});
}

function LoadRegions(url, regionSelectId, callback)
{
	if (locationRegions.length > 0)
	{
		callback()
	} else
	{
		//BlockElement($("#" + regionSelectId).parent());
		$.post(url, '', function(data)
		{
			try
			{
				locationRegions = eval(data);
				callback();
				$("#" + regionSelectId).parent().unblock();
			} catch (e) { }
		});
	}
}
function BuildRegionSelect(locationRegions, regionSelectId, selectedRegionId, showIn)
{
	var options = $("#" + regionSelectId + " > option"); //.remove();
	if (options.length > 0)
	{
		options.removeAttr("selected");
		$("#" + regionSelectId + " > option[value='" + selectedRegionId + "']").attr("selected", "selected");
		return;
	}

	var regionSelect = $("#" + regionSelectId);

	for (var i = 0; i < locationRegions.length; i++)
	{
		if (locationRegions[i].showIn == 0 || locationRegions[i].showIn == showIn)
		{
			var selectedStr = locationRegions[i].id == selectedRegionId ? " selected='selected' " : "";
			regionSelect.append("<option value=" + locationRegions[i].id + selectedStr + ">" + locationRegions[i].value + "</option>");
		}
	}
}

function AccountCheckUserExistsAsyncApply(data)
{
	if ($("#UsernameValidateionMessage")[0])
	{
		$("#UsernameValidateionMessage")[0].style.display = "none";
	}
	if (data.error)
	{
		$("#AccountUserExists")[0].innerHTML = "<b>&nbsp;</b>" + (data.message ? data.message : "Такое имя уже есть на сайте");
		$("#AccountUserExists")[0].className = "AccountUserExistsError";
	} else
	{
		$("#AccountUserExists")[0].innerHTML = "<b>&nbsp;</b>Свободно";
		$("#AccountUserExists")[0].className = "AccountUserExistsOk";
	}
}
AccountCheckUserNameReq = function()
{
	$.ajax({
		url: _AccountCheckUserNameReq,
		dataType: 'json',
		type: "POST",
		contentType: "application/json; charset=utf-8",
		success: function(data)
		{
			try
			{
				AccountCheckUserExistsAsyncApply(data);
			} catch (e) { }
		}
	});
};
AccountCheckUserNamePause = function()
{
	value = _UserNameInput.value;
	if (!value || value.length < 2)
	{
		$("#AccountUserExists")[0].innerHTML = '';
		try { clearTimeout(suggestTimer); } catch (e) { ; }
		return false;
	}
    value = escapeExt(value);
	_AccountCheckUserNameReq = _UserNameCheckUrl + value;
	try { clearTimeout(suggestTimer); } catch (e) { ; }
	suggestTimer = setTimeout(AccountCheckUserNameReq, 600);
};
AccountCheckUserName = function(getStr, obj)
{
	_UserNameInput = obj;
	_UserNameCheckUrl = getStr;
	obj.onblur = function()
	{
		if (this.value.length < 1)
		{
			$("#AccountUserExists")[0].innerHTML = "";
			$("#AccountUserExists")[0].className = "";
		} else if (this.value.length < 2)
		{
			$("#AccountUserExists")[0].innerHTML = "<b>&nbsp;</b>Минимальная длина имени &mdash; 2 символа.";
			$("#AccountUserExists")[0].className = "AccountUserExistsError";
		}
	};
	setTimeout(AccountCheckUserNamePause, 1);
};

/* оставить покачто для отладки */
debug = function(el) {
	var wnd = window.open('', 'debug', ',width=300,height=800,scrollbars, resizable');
	var s = '';
	s += '<table border="1" cellspacing="0" style="width:300px;float:left;">';
	for (j in el) {
		try { s += '<tr><td>' + j + '</td><td>' + el[j] + '</td></tr>'; } catch (e) { s += '<tr><td>' + j + '</td><td><b>PermittionDenied</b></td></tr>'; }
	}
	s += '<table>';
	wnd.document.write(s);
	wnd.document.body.onkeyup = wnd.onkeyup = function(Event) {
		var evt = wnd.event ? wnd.event : Event;
		if (evt.keyCode == 27) wnd.close();
	};
}

function coptyToClipBoard(id)
{
	$("#" + id).get(0).createTextRange().execCommand("Copy");
}

/* for png images in IE6 */
function loadIePng()
{
	if (document.all && navigator.appVersion.match(/MSIE 6/))
	{
		img = event.srcElement;
		if (img.tagName.toLowerCase() != 'img') return;
		img.onload = null;
		img.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + img.src + ', sizingMethod="scale")';
		img.width = img.clientWidth;
		img.height = img.clientHeight;
		img.src = '/theme/images/pix.gif';
	}
}

function FormAutoResizeTextArea(id) {
	var $textarea;
	var $wrap;
	function init() {
		$textarea = $('#' + id);
		$wrap = $('<div>');
		$textarea.after($wrap);
		$wrap.append($textarea.remove());
		$textarea.css({ overflowY: 'hidden' });
		$textarea.bind('focus.affect', affect);
	}

	function affect() {
		var paddings = parseInt($textarea.css('padding-top'), 10) + parseInt($textarea.css('padding-bottom'), 10);
		var lineHeight = getLineHeight();

		var minHeight = getAreaHeight();
		var prevHeight = minHeight;
		

		function getAreaHeight() {
			var textarea = $textarea.get(0);
			var height = Math.max(textarea.scrollHeight, textarea.clientHeight);
			return height + lineHeight - paddings;
		}

		function getLineHeight() {
			var height = $textarea.height() - paddings;
			var value = $textarea.css({ height: 0 }).val();
			var testHeight;
			$textarea.val(' ');
			testHeight = $textarea.get(0).scrollHeight;
			$textarea.css({ height: height - paddings }).val(value);
			return testHeight;
		}

		function setAreaHeight(height) {
			$wrap.css({ height: height + paddings });
			$textarea.css({ height: height });
		}

		function resizeArea() {
			var height;
			$textarea.css({ height: 0 });
			height = getAreaHeight();
			if (height < minHeight) {
				setAreaHeight(minHeight);
				return;
			}
			if (height != prevHeight) {
				setAreaHeight(height);
			} else {
				setAreaHeight(prevHeight);
			}
			prevHeight = height;
		}
		$textarea.bind('keyup blur focus cut paste', function() { setTimeout(resizeArea, 0); });
		resizeArea();
		$textarea.unbind('focus.affect');
	}
	$(init);
}

function commentsQuote(name, message)
{
	$('#addCommentClosedBlock').hide(); $('#addCommentOpenedBlock').show();
	q = '[quote=' + name + ']' + message + '[/quote]';
	t = document.getElementById('commentMessage');
	t.value += q;
	t.focus();
	t.onfocus();
};

function switchTerm(blockId)
{
	block = $("#" + blockId)
	if (block.get(0).className == 'termText')
	{
		block.get(0).className = 'termText termOpen';
		block.show();
	} else
	{
		block.get(0).className = 'termText';
		block.hide();
	}
}

//copypast to /theme/informers/js/main.js
function slowSwitch()
{
	if (arguments.length == 3)
	{
		b = arguments[0];
		d = arguments[1];
		a = arguments[2];
		if (a == 'min')
		{
			a = -1; p = 100;
		}
		if (a == 'max')
		{
			a = 1; p = 0;
			b.style.display = '';
		}
		if (!b.e)
		{
			b.parentNode.replaceChild(b.e = document.createElement('div'), b);
			b.e.appendChild(b.r = document.createElement('div'));
			b.r.appendChild(b);
			b.e.style.position = 'relative';
			b.e.style.overflow = 'hidden';
			b.e.style.zoom = 1;
			b.w = b.e.clientWidth;
			b.h = b.e.clientHeight;
			b.r.style.position = 'absolute';
			b.r.style.width = '100%';
		}
		i = 1;
	}

	if (d == 'height')
	{
		b.e.style.height = b.h * (p + a * i * 10) / 100 + 'px';
	}
	if (d == 'width')
	{
		b.e.style.height = b.h;
		b.e.style.width = b.w * (p + a * i * 10) / 100 + 'px';
		b.r.style.width = b.w + 'px';
	}
	if (i == 10)
	{
		if (d == 'width') { b.e.style.height = '0'; }
		if (a == 1) { b.e.parentNode.replaceChild(b, b.e); b.e = false; }
		return;
	}
	i++;
	setTimeout(slowSwitch, 5);
}

function switchBlock(blockId, buttonId, cookieName)
{
	block = $("#" + blockId).get(0);
	button = $("#" + buttonId).get(0);
	if (button.className == 'switch-btn btn-open')
	{
		button.className = 'switch-btn btn-close';
		slowSwitch(block, 'height', 'max');
		$.cookie(cookieName, 1, { expires: 365, path: '/' });
	} else
	{
		button.className = 'switch-btn btn-open';
		slowSwitch(block, 'height', 'min');
		$.cookie(cookieName, 0, { expires: 365, path: '/' });
	}
}

/* Отслеживание событий */

function RegisterPageEvent(eventName) {
    $(function () {
        window._gaq = window._gaq || [];
        window._gaq.push(['_trackPageview', eventName]);

        var yandexCounter = window['yaCounter' + window.yandexCounterID];
        if (typeof (yandexCounter) != "undefined")
            yandexCounter.reachGoal(eventName);
        else {
            window.pageEvents = window.pageEvents || [];
            window.pageEvents.push(eventName);
        }
    });
}

function CheckPageEventsQueue(yandexCounterID) {
    $(function () {
        window.yandexCounterID = yandexCounterID;
        var yandexCounter = window['yaCounter' + yandexCounterID];

        window.pageEvents = window.pageEvents || [];
        var pageEvents = window.pageEvents;

        if (typeof (yandexCounter) != "undefined" && typeof (pageEvents) != "undefined")
            for (var i = 0; i < pageEvents.length; i++)
                yandexCounter.reachGoal(pageEvents[i]);
    });
}

/* Отслеживание событий */

function switchBlockWithEvent(blockId, buttonId, cookieName, eventName) {
    var button = $("#" + buttonId).get(0);
    var eventSuffix = button.className == 'switch-btn btn-open' ? '_open' : '_close';

    switchBlock(blockId, buttonId, cookieName);

    RegisterPageEvent(eventName + eventSuffix);

    return false;
}

function InitBlockState(blockId, buttonId, cookieName)
{
	if ($.cookie(cookieName) && $.cookie(cookieName) == 0)
	{
		block = $("#" + blockId).get(0);
		button = $("#" + buttonId).get(0);
		button.className = 'switch-btn btn-open';
		block.style.display = 'none';
	}
}

function FormInsertItem(sourceIdStr, insertBeforeObj, afterAction, start)
{
	var l = document.getElementById(sourceIdStr);
	insertBeforeObj = typeof (insertBeforeObj) == 'string' ? document.getElementById(insertBeforeObj) : insertBeforeObj;
	//f = document.getElementById(formIdStr);
	var n = l.cloneNode(true);
	n.removeAttribute('id');
	insertBeforeObj.parentNode.insertBefore(n, insertBeforeObj);
	if (!insertBeforeObj.i)
	    insertBeforeObj.i = (start != undefined ? start : 1);
    n.innerHTML = n.innerHTML.replace(/\:index\:/ig, insertBeforeObj.i);
	if (typeof (afterAction) == 'function')
	    afterAction(insertBeforeObj.i);
	insertBeforeObj.i++;
}
function FormDeleteItem(deleteObj)
{
	deleteObj.parentNode.removeChild(deleteObj);
}

// create suggest
function createSuggest(opts) {
	var ie = document.all && (!window.opera);
	var emptyMessage = typeof (opts.msg) != 'undefined' ? opts.msg : 'По вашему запросу ничего не найдено';
	var inp = document.getElementById(opts.input);
	inp.oldvalue = inp.value;
	if (!inp) return false;
	inp.suggestEnabled = true;
	inp.url = opts.url;
	inp.hiddenValue = document.getElementById(opts.hidden);
	inp.key = document.getElementById(opts.key);
	inp.txt = document.getElementById(opts.title);
	inp.comment = document.getElementById(opts.comment);
	inp.callback = opts.callback;
	inp.callbackParams = opts.callbackParams;
	inp.create = function () {
	    var suggest = document.createElement('div');
	    if (inp.nextSibling)
	        inp.parentNode.insertBefore(suggest, inp.nextSibling);
	    else
	        inp.parentNode.appendChild(suggest);
	    suggest.className = "suggest";

	    inp.w = window.opera ? document.createElement("iframe") : document.createElement("div");
	    suggest.insertBefore(inp.w, suggest.firstChild);
	    inp.w.style.cssText = "width:1px;height:1px;position:absolute;left:0;top:0;font-size:0;border:solid 0;"; //opacity//

	    document.body.appendChild(inp.abs = document.createElement("div"));
	    inp.abs.style.cssText = "position:absolute;";
	    inp.abs.className = "suggest";

	    if (ie) {
	        inp.abs.appendChild(inp.ifr = document.createElement('iframe'));
	        inp.ifr.style.cssText = 'position:absolute;left:0;top:0;display:none;/*filter:alpha(opacity=0);opacity:0*/';
	    }

	    var ul = document.createElement('ul');
	    inp.abs.appendChild(ul);
	    ul.style.display = 'none';
	    inp.setAttribute("autocomplete", "off");
	    inp.suggest = suggest;
	    inp.ul = ul;
	};
	inp.undoSubmit = function(undo) {
		if (undo) {
			if (!inp.formSubmit) {
				inp.formSubmit = inp.form.onsubmit ? inp.form.onsubmit : function() { ; };
				inp.form.onsubmit = function() { return false; };
			}
		} else {
			if (inp.formSubmit) {
				inp.form.onsubmit = inp.formSubmit;
				inp.formSubmit = null;
			}
		}
	};
	inp.onkeyup = function(Event) {
		if (!inp.suggest) inp.create();
		var evt = Event ? Event : event;
		var ul = inp.ul;

		if (inp.oldvalue != inp.value) {
			if (inp.callback) inp.callback('', inp.callbackParams);
			if (inp.txt) inp.txt.innerHTML = '';
		}
		var offsetFocus = function(offset) {
			var ul = inp.ul;
			if (!ul.childNodes.length) return false;
			if (ul.firstChild.className == "empty") return false;
			for (var i = 0; i < ul.childNodes.length; i++) {
				if (ul.childNodes[i].className.match('hover')) {
					ul.childNodes[i].className = ul.childNodes[i].className.replace('hover', '');
					if ((i + offset) < 0) i = ul.childNodes.length;
					if ((i + offset) > (ul.childNodes.length - 1)) i = -1;
					ul.childNodes[i + offset].className += ' hover';
					inp.data(ul.childNodes[i + offset]);
					return 0;
				}
			}
			if (offset > 0) {
				ul.childNodes[0].className += ' hover';
				inp.data(ul.childNodes[0]);
			};
			if (offset < 0) {
				ul.childNodes[ul.childNodes.length - 1].className += ' hover';
				inp.data(ul.childNodes[ul.childNodes.length - 1]);
			};
			inp.oldvalue = inp.value;
		};
		if (evt.keyCode == 38)//point up
		{
			offsetFocus(-1);
			return false;
		}
		if (evt.keyCode == 40)//point down
		{
			offsetFocus(1);
			return false;
		}
		if (evt.keyCode == 13)//enter
		{
			ul.innerHTML = '';
			ul.style.display = inp.abs.style.display = 'none';
			if (ie) inp.ifr.style.display = 'none';
			inp.undoSubmit();
			return false;
		}
		if (evt.keyCode == 27)//esc
		{
			ul.innerHTML = '';
			ul.style.display = inp.abs.style.display = 'none';
			if (ie) inp.ifr.style.display = 'none';
			inp.undoSubmit();
			return false;
		}

		inp.suggest.style.width = (inp.offsetWidth - 2) + 'px'; //suggest min-width

		if (inp.suggestEnabled && inp.value && (inp.value.length > 0)) {
			if (inp.oldvalue == inp.value) return false; //if value not changed
			clearTimeout(this.timeout);
			inp.timeout = setTimeout(function() { inp.query(inp); }, 10); //set timeout request
			inp.oldvalue = inp.value;
		} else {
			ul.innerHTML = '';
			ul.style.display = inp.abs.style.display = 'none';
			if (ie) inp.ifr.style.display = 'none';
			inp.undoSubmit();
		}
	};
	/*inp.onkeydown = function()
	{
		//if (document.all && event.keyCode == 13)//stop submit propagation
		//	return false;
	};*/
	var onblur = function()//onblur - hide suggest
	{
		if (!inp.ul) return false;
		clearTimeout(this.timeout);
		this.timeout = false;
		inp.ul.innerHTML = '';
		inp.ul.style.display = inp.abs.style.display = 'none';
		if (ie) inp.ifr.style.display = 'none';
		inp.undoSubmit();
		if (inp.oldvalue != inp.value) {
			if (inp.txt) inp.txt.innerHTML = '';
		}
	};
	$(inp).bind('blur', onblur);
	inp.query = function(inp)//get data
	{
		if (!inp.value || FormatInput(inp.value, true).length == 0)
			return;
		$.ajax({
		    url: inp.url + escapeExt(FormatInput(inp.value, true)),
			dataType: 'json',
			contentType: "application/x-www-form-urlencoded; charset=utf-8",
			type:"POST",
			success: function(data) { inp.ready(data); }
		});
	};
	inp.data = function(obj)//set values text input [and hidden input]
	{
		inp.value = obj.data;
		if (inp.hiddenValue) inp.hiddenValue.value = obj.key ? obj.key : "";
		if (inp.txt) inp.txt.innerHTML = obj.txt ? obj.txt : "";
		if (inp.callback) inp.callback(obj.data, inp.callbackParams);
		if (inp.comment) inp.comment.innerHTML = obj.comment ? obj.comment : "";
		inp.oldvalue = inp.value;
	};
	inp.ready = function(data)//create suggest list
	{
		if (this.timeout === false) return false;
		var ul = inp.ul;
		var li;
		var esc = document.createElement("div");
		ul.innerHTML = '';
		if (!data.length) {
			if (emptyMessage === false) {
				inp.ul.style.display = inp.abs.style.display = 'none';
				if (ie) inp.ifr.style.display = "none";
				return;
			}
			ul.appendChild(li = document.createElement('li'));
			li.className = 'empty';
			li.innerHTML = emptyMessage;
			li.data = "";
		}
		for (var i = 0; i < data.length; i++) {
			ul.appendChild(li = document.createElement('li'));
			if (typeof (data[i]) == 'object') {
				//li.innerHTML = data[i].valueEncoded;//если здесь ошибок не возникло, стоит убрать valueEncoded из серверной части
				if (document.all)
					esc.innerText = data[i].value;
				else
					esc.textContent = data[i].value;
				li.innerHTML = esc.innerHTML;
				//li.innerHTML = data[i].value;
				if (data[i].key) li.key = data[i].key;
				if (data[i].value) li.data = data[i].value;
				if (data[i].title) {
					li.txt = data[i].title;
				}
				if (data[i].cssClass) li.className = data[i].cssClass;
			}
			else {
				li.innerHTML = data[i];
				li.data = data[i];
			}
			var words = FormatInput(inp.value.replace(/[^0-9a-zа-яё]+/gi, " "), false).split(" ");
			if (opts.light) {
				var title = li.innerHTML;
				var comm = data[i].comment;
				for (var ii = 0; ii < words.length; ii++) {
					var re = new RegExp('('+words[ii]+')','gi');
					title = title.replace(re, '<b>$1</b>');
					if (comm != null) {
						comm = comm.replace(re, '<b>$1</b>');
					}
				}
				li.innerHTML = title;
				if (comm != null)
					li.innerHTML += "<div class='comment'>" + comm + "</div>";
			}
			li.innerHTML += data[i].title ? "&nbsp;&nbsp;" + data[i].title + "" : '';
			li.onmouseover = function() {
				for (var i = 0; i < this.parentNode.childNodes.length; i++) {
					this.parentNode.childNodes[i].className = this.parentNode.childNodes[i].className.replace(/\s?hover/, '');
				}
				this.className += ' hover';
			};
			li.onmousedown = function() { inp.data(this); };
		}
		esc = null;

		//if (data.length == 1) inp.data(li); //if we have one variant

		//var sw = safari ? document.width : document.documentElement.scrollWidth;
		//var sh = safari ? document.height : document.documentElement.scrollHeight;
		/*if (window.opera) {
		sx = inp.w.contentWindow.screenLeft - window.screenLeft + document.documentElement.scrollLeft;
		sy = inp.w.contentWindow.screenTop - window.screenTop + document.documentElement.scrollTop;
		} else {
		var safari = !document.all && !window.netscape;
		inp.w.style.marginLeft = sw - 1 + 'px';
		inp.w.style.marginTop = sh - 1 + 'px';

		sx = (safari ? document.width : document.documentElement.scrollWidth) - sw;
		sy = (safari ? document.height : document.documentElement.scrollHeight) - sh;

		inp.w.style.marginLeft = 0 + 'px';
		inp.w.style.marginTop = 0 + 'px';
		}*/
		var sw = $(document).width();
		var sh = $(document).height();
		var ofs = $(inp.w).offset();
		var sx = ofs.left;
		var sy = ofs.top;

		inp.abs.style.left = sx + "px";
		inp.abs.style.top = sy + "px";

		inp.abs.style.width = (sw - sx - 20) + "px";

		ul.style.display = inp.abs.style.display = '';
		if (ie) inp.ifr.style.display = '';
		inp.undoSubmit(!opts.freeSubmit);
		if (ie) inp.ifr.style.width = ul.clientWidth + 2 + 'px';
		if (ie) inp.ifr.style.height = ul.clientHeight + 2 + 'px';
	};
}
//автоматическая проверка формы на изменения
function autoCheckForm(submitId)
{
	function checkForm(submitId)
	{
		var submit = document.getElementById(submitId);
		var form = submit.form;
		submit.disabled = true;
		var el;
		var isDefault = function(el)
		{
			if (undefined == el.dfltValue)
			{
				el.dfltValue = el.Value;
				return true;
			}
			else
			{
				return el.dfltValue == el.Value ? true : false;
			}
		};
		for (var i = 0; i < form.elements.length; i++)
		{
			el = form.elements[i];
			if (!el.name) continue;

			if (el.tagName.toLowerCase() == 'select')
			{
				for (var j = 0; j < el.options.length; j++)
					if (el.options[j].selected) el.Value = j;
			}
			else if (el.type && ((el.type == 'checkbox') || (el.type == 'radio')))
			{
				el.Value = el.checked ? true : false;
			}
			else
			{
				el.Value = el.value;
			}
			if (!isDefault(el)) submit.disabled = false;
		}
	}
	setInterval(function() { checkForm(submitId); }, 200);
}

//проверка наличия записей в текстовом баннере, если их нет, то скрываем блок
function checkTextBanner()
{
	try
	{
		var promo = $('#PromoJsInformer');
		if (!promo) return false;
		var promoItems = document.getElementById('PromoBlock').childNodes;
		var hide = true;
		for (var i = 0; i < promoItems.length; i++)
		{
			if (promoItems[i].tagName && (promoItems[i].tagName.toLowerCase() == 'div'))
			{
				var el = promoItems[i];
				if (el.firstChild.tagName && (el.firstChild.tagName.toLowerCase() == 'h5'))
				{
					hide = false;
				}
			}
		}
		if (!hide) promo.show();
	} catch (e) { }

}
//Инициализация лайт бокса редактирования связей (Оквэд, ПО)
function LinkLigthBoxInit(selectionHolderId, lightBoxId, allIsArray, groupsArray)
{
	checkBoxContainer = $("#" + lightBoxId + " div");
	var currentGroupId = 0;
	var currentSubgroup = "";
	for (j=0; j<allIsArray.length; j++)
	{
		if (currentGroupId != allIsArray[j].groupId)
		{
			currentGroupId = allIsArray[j].groupId;
			var index = 0;
			for (var i = 0; i < groupsArray.length; i++)
			{
				if (groupsArray[i].id == allIsArray[j].groupId)
				{
					currentGroupId = allIsArray[j].groupId;
					index = i;
				}
			}
			checkBoxContainer.append("<h4>" + groupsArray[index].title + "</h4>");

        }
        subgroup1 = String(allIsArray[j].title.split(" ", 1));
		if (j < (allIsArray.length - 1)) {
		    subgroup2 = String(allIsArray[j + 1].title.split(" ", 1));
		    if (currentSubgroup != subgroup1 && subgroup1 == subgroup2) {
		        currentSubgroup = subgroup1;
		        checkBoxContainer.append("<h5>" + subgroup1 + "</h5>");
		    }
		}
	    if (subgroup1 == currentSubgroup) {
	        subgroupIndent = "&nbsp;&nbsp;&nbsp;&nbsp;";
	    } else {
	        subgroupIndent = "";
	        currentSubgroup = "";
	    }
	    checkBoxContainer.append('<label for="' + lightBoxId + allIsArray[j].id + '">' + subgroupIndent + '<input id="' + lightBoxId + allIsArray[j].id + '" type="checkbox" value="' + allIsArray[j].id + '"/> ' + allIsArray[j].title + '</label>')
	}
	$("#" + lightBoxId + " div > label").bind('mouseover', function() { $(this).addClass('hover-') });
	$("#" + lightBoxId + " div > label").bind('mouseout', function() { $(this).removeClass('hover-') });
	$("#" + lightBoxId + " div > label").bind('click', function() { if ($(this).find("input")[0].checked) $(this).addClass('active-'); else $(this).removeClass('active-'); });
	idsStr = $("#" + selectionHolderId).get(0).value;
	OkvedSoftwareLigthBoxSetChecked(lightBoxId, selectionHolderId);
	/*if (idsStr.length > 0)
	{
		var ids = $("#" + selectionHolderId).get(0).value.split(",");
		$.each(ids, function() {
		    var checkBox = $("#" + lightBoxId + " input[value=" + this + "]");
		    checkBox.get(0).checked = true;
		    checkBox.parent().addClass('active-');
		})
	}*/
	
}

function OkvedSoftwareLigthBoxSetChecked(lightBoxId, selectionHolderId) {
    var selectedIds = $("#" + selectionHolderId).get(0).value.split(",");
    $("#" + lightBoxId + " div > label").each(function(i) {
        var checkBox = $(this).find("input")[0];
        checkBox.checked = false;
        $(this).removeClass('active-');
        for (var i = 0; i < selectedIds.length; i++) {
            if (checkBox.value == selectedIds[i]) {
                checkBox.checked = true;
                $(this).addClass('active-');
             }
        }
    });
}

//Сохраняет выбранные на лайтбоксе Id в хидден поле, отображает выбранные данные (Оквэд, ПО)
function LinkApplySelection(viewContainerId, lightBoxId, selectionHolderId, allIsArray, selectLinkId)
{
	var viewContainer = $("#" + viewContainerId);
	var selectedIds = "";
	viewContainer.empty();
	var selectLink = $("#" + selectLinkId).get(0);
	selectLink.innerHTML = "выбрать...";
	$("#" + lightBoxId + " input").each(function(i)
	{
		if (this.checked)
		{
			selectedIds += this.value + ",";
			var okved;
			for (var i = 0; i < allIsArray.length; i++)
			{
				if (allIsArray[i].id == this.value)
					okved = allIsArray[i];
			}
			viewContainer.append("<span>" + okved.title + "</span><br />")
			selectLink.innerHTML = "изменить...";

}
	});
	$("#" + selectionHolderId).get(0).value = selectedIds;
	$.unblockUI();
}

$(document).ready(function() { document.loaded = true; });
/*
function userFloat(el, userId, elType) {
	el = typeof (el) == 'string' ? document.getElementById(el) : el;
	el.userId = userId;
	el.elType = elType;
	el.timeout = 500;
	el.kx = navigator.appVersion.match(/MSIE 6/) ? 2 : document.all ? 4 : 0;
	el.ky = navigator.appVersion.match(/MSIE 6/) ? 5 : document.all ? 7 : 4;

	if (window.opera) {
		el.style.position = 'relative';
		el.appendChild(el.img = document.createElement('img'));
		el.img.style.position = 'absolute';
		el.img.style.left = 0;
		el.img.style.top = 0;
		el.img.style.width = el.clientWidth + 'px';
		el.img.style.height = el.clientHeight + 'px';
		el.img.style.border = 'solid 0';
	}
	
	el.show = function() {
		if (el.div) {
			//el.frame.style.display = el.div.style.display = 'block';
			el.frame.style.top = el.div.style.top = el.posY - el.ky + 'px';
			el.view();
			el.frame.style.display = el.div.style.display = 'block';
			if (el.elType == 'photo')
				el.frame.style.left = el.div.style.left = el.posX - el.kx + 'px';
			else if (el.elType == 'name')
				el.frame.style.left = el.div.style.left = (el.posX < 70 ? 70 : el.posX) - (66 + el.kx) + 'px';
			return;
		}
		if (!el.frame) document.body.appendChild(el.frame = document.createElement('iframe'));
		if (!el.div) document.body.appendChild(el.div = document.createElement('div'));
		var mouseout = function(Event) {
			var rt = document.all ? event.toElement : Event.relatedTarget;
			while (rt != document.body) {
				if (rt == el.div) return false;
				rt = rt.parentNode;
			};
			el.frame.style.display = el.div.style.display = 'none';
		};
		if (document.all)
			el.div.attachEvent('onmouseout', mouseout);
		else
			el.div.addEventListener('mouseout', mouseout, true);

		el.frame.style.position = el.div.style.position = 'absolute';
		el.frame.style.opacity = 0;
		el.frame.style.display = 'none';
		el.frame.style.filter = 'alpha(opacity=0)';
		//el.div.style.left = el.div.style.left = el.posX + 'px';
		el.frame.style.top = el.div.style.top = el.posY - el.ky + 'px';
		el.load();
	}
	el.load = function() {
		if (!el.data) {
			$.ajax({
				url: '/mypage/GetFloatCardAsync?userid=' + el.userId + '&clear=' + Math.random(),
				dataType: 'json',
				contentType: "application/json; charset=utf-8",
				success: function(data) { el.ready(data); }
			});
			el.timeout = 500;
		}
	}
	el.view = function() {
		var cssText;
		if (el.opacity == 0) {
			cssText = el.div.style.cssText;
		}
		el.div.style.filter = 'alpha(opacity=' + (100 * el.opacity) + ')';
		el.div.style.opacity = el.opacity;
		if (el.opacity < 0.9) {
			el.opacity += 0.1;
			setTimeout(el.view, 10);
		} else {
			el.div.style.filter = '';
			el.div.style.cssText = el.div.style.cssText.replace('FILTER: ;', '');
			el.div.style.opacity = '';
		}
	};
	el.ready = function(data) {
		el.data = data;
		var html;
		html = '<span class="sh-r"><b><i><!----></i></b><s><!----></s><u><!----></u></span><span class="sh-b"><b><!----></b><s><!----></s></span>'
				+ '<table class="user-card-popup"><tr><td class="img-"><a href="/users/' + el.userId + '" ><img src="' + data.imageUrl + '" /></a></td>'
				+ '<td class="txt-"><div class="user-card-short"><a href="/users/' + el.userId + '" class="user ' + (data.gender != 0 ? data.gender == 1 ? "man" : "woman" : "") + '" >' + HtmlEncode(data.userName) + '</a></div>'
				+ '<div>' + (data.profession ? '' : '<b>' + data.profession + '</b>') + '</div>'
				+ (data.isCollegue ? '<div class="is-friend-">В списке коллег</div>' : '')
				+ (data.isJobless ? '<div><span class="job-search-">Ищу работу</span></div>' : '')
				+ '<br /><div><a href="/mypage/messages/send/' + el.userId + '">Написать&nbsp;сообщение</a></div>'
				+ (data.isCollegue ? '' : '<div><a href="/mypage/profile/colleagues/invite/' + el.userId + '">Пригласить&nbsp;в&nbsp;коллеги</a></div>')
				+ '</td></tr></table>';
		el.div.innerHTML = html;
		el.opacity = 0;
		el.view();
		el.frame.style.display = el.div.style.display = 'block';
		if (el.elType == 'photo')
			el.frame.style.left = el.div.style.left = el.posX - el.kx + 'px';
		else if (el.elType == 'name')
			el.frame.style.left = el.div.style.left = (el.posX < 70 ? 70 : el.posX) - (66 + el.kx) + 'px';

		el.frame.style.width = el.div.clientWidth + 'px';
		el.frame.style.height = el.div.clientHeight + 'px';
	};
	var mousemove = function(Event) {
		var evt = window.event ? event : Event;
		this.layerX = evt.layerX || evt.x;
		this.layerY = evt.layerY || evt.y;
		el.posX = evt.clientX - this.layerX + document.documentElement.scrollLeft;
		el.posY = evt.clientY - this.layerY + document.documentElement.scrollTop;
		if (el.timer) clearTimeout(el.timer);
		el.timer = setTimeout(el.show, el.timeout);
	};
	var mouseout = function(Event) {
		clearTimeout(el.timer);
	};
	el.style.position = 'relative';

	if (document.all) {
		el.attachEvent('onmousemove', mousemove);
		el.attachEvent('onmouseout', mouseout);
	} else {
		el.addEventListener('mousemove', mousemove, true);
		el.addEventListener('mouseout', mouseout, true);
	}
}*/

function userPopup(el, userId, elType) {
	el = typeof (el) == 'string' ? document.getElementById(el) : el;
	el.userId = userId;
	el.elType = elType;
	el.timeout = 500;
	
	if (window.opera && !el.img && (el.elType == 'name')) {
		var test = document.createElement('div');
		el.parentNode.appendChild(test);
		test.appendChild(el.cloneNode(true));
		el.img = document.createElement('img');
		el.img.style.position = 'absolute';
		el.img.style.marginLeft = '-19px';
		el.img.style.width = el.clientWidth + 'px';
		el.img.style.height = test.clientHeight + 'px';
		el.parentNode.removeChild(test);
		el.img.style.opacity = '0';
		el.img.style.border = "solid 0";
		el.insertBefore(el.img, el.firstChild);
	}

	el.show = function() {
		if (el.div) {
			el.frame.style.top = el.div.style.top = el.posY + 'px';
			el.frame.style.display = el.div.style.display = 'block';
			if (el.elType == 'photo')
				el.frame.style.left = el.div.style.left = el.posX + 1 + 'px';
			else if (el.elType == 'name')
				el.frame.style.left = el.div.style.left = (el.posX < 70 ? 70 : el.posX) - 66 + 'px';
			return;
		}
		if (!el.frame) document.body.appendChild(el.frame = document.createElement('iframe'));
		if (!el.div) document.body.appendChild(el.div = document.createElement('div'));
		var mouseout = function(Event) {
			var rt = document.all ? event.toElement : Event.relatedTarget;
			while (rt != document.body) {
				if (rt == el.div) return false;
				rt = rt.parentNode;
			};
			el.frame.style.display = el.div.style.display = 'none';
		};
		if (document.all)
			el.div.attachEvent('onmouseout', mouseout);
		else
			el.div.addEventListener('mouseout', mouseout, true);

		el.frame.style.position = el.div.style.position = 'absolute';
		el.frame.style.opacity = 0;
		el.frame.style.display = 'none';
		el.frame.style.filter = 'alpha(opacity=0)';
		el.frame.style.top = el.div.style.top = el.posY + 'px';
		el.load();
	};
	el.load = function() {
		if (!el.data) {
			$.ajax({
				url: '/mypage/GetFloatCardAsync?userid=' + el.userId + '&clear=' + Math.random(),
				dataType: 'json',
				type: "POST",
				contentType: "application/json; charset=utf-8",
				success: function(data) { el.ready(data); }
			});
			el.timeout = 500;
		}
	};
	el.view = function() {
		var cssText;
		if (el.opacity == 0) {
			cssText = el.div.style.cssText;
		}
		el.div.style.filter = 'alpha(opacity=' + (100 * el.opacity) + ')';
		el.div.style.opacity = el.opacity;
		if (el.opacity < 0.9) {
			el.opacity += 0.1;
			setTimeout(el.view, 10);
		} else {
			el.div.style.filter = '';
			el.div.style.cssText = el.div.style.cssText.replace('FILTER: ;', '');
			el.div.style.opacity = '';
		}
	};
	el.ready = function(data) {
		el.data = data;
		var html;
		html = '<div class="usercart-popup"><span class="sh-r"><b><i><!----></i></b><s><!----></s><u><!----></u></span><span class="sh-b"><b><!----></b><s><!----></s></span>'
				+ '<table class="usercart-full"><tr><td class="img-"><a href="/users/' + el.userId + '" ><img src="' + data.imageUrl + '" alt="" /></a></td>'
				+ '<td class="txt-"><div class="usercart-short"><a href="/users/' + el.userId + '" class="name- ' + (data.gender != 0 ? data.gender == 1 ? "man-" : "woman-" : "") + '" >' + HtmlEncode(data.userName) + '</a></div>'
				+ '<div>' + (data.profession ? '' : '<b>' + data.profession + '</b>') + '</div>'
				+ (data.isCollegue ? '<div class="is-friend-">В списке коллег</div>' : '')
				+ (data.isLookingForAJob ? '<div><span class="job-search-label">Ищет работу</span></div>' : '')
				+ '<br /><div><a href="/mypage/messages/send/' + el.userId + '">Написать&nbsp;сообщение</a></div>'
				+ (data.isCollegue ? '' : '<div><a href="/mypage/profile/colleagues/invite/' + el.userId + '">Пригласить&nbsp;в&nbsp;коллеги</a></div>')
				+ '</td></tr></table></div>';
		el.div.innerHTML = html;
		el.opacity = 0;
		el.frame.style.display = el.div.style.display = 'none';
		if (el.timer === false) return;
		el.view();
		el.frame.style.display = el.div.style.display = 'block';
		if (el.elType == 'photo')
			el.frame.style.left = el.div.style.left = el.posX + 1 + 'px';
		else if (el.elType == 'name')
			el.frame.style.left = el.div.style.left = (el.posX < 70 ? 70 : el.posX) - 66 + 'px';

		el.frame.style.width = el.div.clientWidth + 'px';
		el.frame.style.height = el.div.clientHeight + 'px';
	};
	el.hist = "";
	var mousemove = function(Event) {
		var evt = window.event ? event : Event;
		this.layerX = evt.layerX || evt.x;
		this.layerY = evt.layerY || evt.y;
		el.posX = evt.clientX - this.layerX + (document.body.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft);
		el.posY = evt.clientY - this.layerY + (document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop);
		if (el.timer) clearTimeout(el.timer);
		el.timer = setTimeout(el.show, el.timeout);
	};
	var mouseout = function(Event) {
		clearTimeout(el.timer);
		el.timer = false;
	};
	el.style.position = 'relative';

	if (document.all) {
		el.attachEvent('onmousemove', mousemove);
		el.attachEvent('onmouseout', mouseout);
	} else {
		el.addEventListener('mousemove', mousemove, true);
		el.addEventListener('mouseout', mouseout, true);
	}
}

//подсказка в текстовом поле
function textNote(inputId, note) {
    //note элемент "берется" не через jquery потому, что в некоторых местах используются idшники вида что-тотам[некий индекс]_что-тотамеще (пример Education.aspx items[0]_EducationTypeValueId) и jquery('#'+inputId) не работает для таких id
    var element = document.getElementById(inputId);
	var input = $(element);
	//if (!input) return false;
	function onblur()
	{
		if (input.val() == '') {
			input.val(note);
			input.get(0).empty = true;
			input.css({color : '#999'});
			input.addClass('empty');
		}
		else {
			input.get(0).empty = false;
			input.removeClass('empty');
		}
	}
	function onfocus() {
		if (input.get(0).empty) input.val('');
		input.css({color: '#000'});
		input.addClass('empty');
	}
	function onkeyup() {
		if (this.value) this.empty = false;
	}
	$(input).blur(onblur);
	$(input).focus(onfocus);
	$(input).keyup(onkeyup);
	if (input.val() == note) input.val('');
	onblur();
}
function clearNotes(formId)
{
	var form = (typeof (formId) == 'string') ? document.getElementById(form) : formId;
	for (var i = 0; i < form.elements.length; i++)
		if (form.elements[i].empty) form.elements[i].value = '';
}
function HtmlEncode(s) {
	var pattern = /(\r\n)|\r|\n/g;
	return s.replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(pattern, "<br />");
}

function GetNoteContainer(link) {
	return $(".note", link.parent().parent());
}

function ThanksForForumMessage(link) {
    var coords = $(link).offset();
    var popup = $('.thanks-advanced');
    var parentOffset = popup.parent().offset();
    popup.hide();
    if (window.opera) parentOffset.top -= 4;
    popup.css({ left: coords.left - parentOffset.left, top: coords.top - parentOffset.top, position: 'absolute' }).fadeIn();
    popup.attr('data-message-id', $(link).attr("messageid"));
    var timer = null;
    $('.js-thanks-hide').click(function () {
        popup.fadeOut();
    });
    popup.mouseleave(function () {
        timer = setTimeout(function () { popup.fadeOut() }, 1000);
    }).mouseover(function () {
        clearTimeout(timer);
    });
	return false;
}
function ThanksForForumMessageAdvanced(link, points) {
    var popup = $(link).parent().parent().parent();
    popup.hide();
    var messageId = popup.attr("data-message-id");
    var button = $('.ThanksLink[messageid=' + messageId + ']');
    return ThanksForItem(button, "messageId", "SayThankYouAsync", messageId, points);
}
function ThanksForDocument(link, documentId) {
	return ThanksForItem(link, "id", "SayThankYouForDocumentAsync", documentId);
}
function ThanksForItem(link, attrIdName, actionName, itemId, points) {
	link = $(link);
	var noteContainer = GetNoteContainer(link);
	var messagePoints = $(".message-points", link.parent().parent());
	function OnSaidThankYou(result) {
		noteContainer.html(HtmlEncode(result.note));
		noteContainer.show();
		messagePoints.html(HtmlEncode(result.MessagePoints+' '+WordEndingByNumber(result.MessagePoints, 'балл', 'балла', 'баллов')));
		messagePoints.show();
		link.hide().attr("thanked", "true");
	}

	var url = "/rating/" + actionName + "?" + attrIdName + "=" + itemId;
	if (typeof (points) != 'undefined')
	    url = url + "&points=" + points;
    $.post(url, "", OnSaidThankYou, "json");
	return false;
}
function OpenForThanks(link) {
	link = $(link);
	var messageId = link.attr("messageId");
	var currentlyOpened = link.attr("opened") == "true";
	var needOpen = !currentlyOpened;
	var noteContainer = GetNoteContainer(link);

	function OnOpened(result) {
	    noteContainer.html(result.note);
		noteContainer.show();

		var image = $("img", link)[0];
		var thanksLink = $(".ThanksLink", link.parent().parent());
		var messagePoints = $(".message-points", link.parent().parent());
		var messagePointsMax = $(".message-points-max", link.parent().parent());
		var pointsPopup = $(link).parent().parent().find('.thanks-advanced');

		if (needOpen) {
			link.attr("opened", "true");
			link.attr("title", "Запретить баллы");
			image.src = image.src.replace("b_enable.gif", "b_block.gif");
			if (thanksLink.attr("thanked") != "true")
			    thanksLink.show();
			messagePoints.show();
		    messagePointsMax.show();
		} else {
			link.attr("opened", "false");
			link.attr("title", "Разрешить баллы");
			image.src = image.src.replace("b_block.gif", "b_enable.gif");
			thanksLink.hide();
			messagePoints.hide();
			messagePointsMax.hide();
		    pointsPopup.hide();
		}
	}
	$.post("/rating/OpenForThanksAsync", { open: needOpen, messageId: messageId }, OnOpened, 'json');
	return false;
}

function CalcLeftCharsAndTruncateValue(objId) {
    var obj = $('#' + objId);
    var maxChars = obj.attr('maxlength');
    if (maxChars == null) return;
    
    var val = obj.val();
	var leftChars = maxChars - val.length;
	if (leftChars < 0) {
	    obj.val(val.substr(0, maxChars));
		leftChars = 0;
    }

    $('#' + objId + 'Left').html(WordEndingByNumber(leftChars, 'Остался', 'Осталось', 'Осталось'));
    $('#' + objId + 'Counter').html(leftChars);
	$('#' + objId + 'Values').html(WordEndingByNumber(leftChars, 'знак', 'знака', 'знаков'));
}

function WordEndingByNumber(number, one, two, five) {
    number = Math.abs(number) % 100;
    if (number > 20) number %= 10;
    if (number == 1) return one;
    if (number > 1 && number < 5) return two;
    return five;
} 

function CalcLeftCharsAndTruncateValueInitAndBind(objId) {
    $('#' + objId).bind('keyup', function() { CalcLeftCharsAndTruncateValue(this.id); });
    CalcLeftCharsAndTruncateValue(objId);
    $('#' + objId + 'Holder').show();
}

function Remove(str, regex) {
		var flags = "g";
		if (regex.ignoreCase) flags += "i";
		if (regex.multiline) flags += "m";
		var globalRegex = new RegExp(regex.source, flags);
		return str.replace(globalRegex, "");
	}

function Trim(str) {
	return Remove(str,/^\s+|\s+$/); 
}

function RemoveMultipleSpaces(str) {
		return str.replace(/\s+/g, " ");
}

function FormatInput(str, removeQuotes) {
	if (removeQuotes) 
	{
		var withoutQuotes = str.replace(/\"/g, "");
	    return Trim(RemoveMultipleSpaces(withoutQuotes));
	}
	return Trim(RemoveMultipleSpaces(str));
}

function DisableSubmits(form, disable) {
	$("input[type=submit]", form).each(function() { this.disabled = disable; });
}
function OnClickExampleLink(textBoxId, link) {
	$('#' + textBoxId).get(0).focus();
	$('#' + textBoxId).get(0).empty = false;
	$('#' + textBoxId).get(0).value = link.innerHTML;
	 return false;
}

//всплывающая подсказка/расшифровка вешается на onmouseover для el
/*
function hint(el, text) {
	if (!text) return false;
	el.title = "";
	if (!el.popup) {
		document.body.appendChild(el.popup = document.createElement('div'));
		el.popup.className = 'hint-popup';
		el.popup.innerHTML = "<div>" + text.replace(/\n/, '<br />') + "</div>";
		el.popup.style.display = 'none';
	}
	el.onmousemove = function (Event) {
	    var evt = window.event ? event : Event;
        if(!document.all) {
            var x = evt.pageX;
            var y = evt.pageY;
        } else {
	        var x = evt.clientX + document.documentElement.scrollLeft;
	        var y = evt.clientY + document.documentElement.scrollTop;
        }

	    el.popup.style.left = x + 'px';
	    el.popup.style.top = y + 'px';
	};
	el.timer = setTimeout(function () {

	    el.popup.style.display = 'block';
	    var x = el.popup.offsetLeft;
	    var sl = document.documentElement.scrollLeft;
	    var pw = el.popup.firstChild.clientWidth;
	    el.popup.firstChild.style.marginLeft = 0;
	    if ((x - sl + pw) > document.documentElement.clientWidth) {
	        el.popup.firstChild.style.marginLeft = (document.documentElement.clientWidth - x - pw - 20 + document.documentElement.scrollLeft) + 'px';
	    }
	}, 300);
	el.onmouseout = function(Event) {
		clearTimeout(el.timer);
		el.timer = null;
		el.popup.style.display = 'none';
	}
}
*/

function hint(element, text) {
    if (!text) return;
    var $Element = $(element);
    var x, y;
    var timeout = 500;
    if (!element.timer) element.timer = 0;

    if (!element.$HintBlock) {
        var $HintBlock = element.$HintBlock = $('<div>');
        $(document.body).append($HintBlock);
        $HintBlock.addClass('hint-popup').hide();
    } else {
        var $HintBlock = element.$HintBlock;
    }

    $HintBlock.html('<div>' + text.replace(/\n/, '<br />') + '</div>');

    function show() {
        clearTimeout(element.timer);
        $HintBlock.css({
            left: x,
            top: y
        }).show();
        var DocScrollLeft = document.documentElement.scrollLeft;
        var DocWidth = document.documentElement.clientWidth;
        var $Div = $HintBlock.find('div');
        var HintBlockWidth = $Div.width();
        $Div.css({ marginLeft: 0 });
        if ((x - DocScrollLeft + HintBlockWidth) > DocWidth) {
            $Div.css({ marginLeft: (DocWidth - x - HintBlockWidth - 35 + DocScrollLeft) });
        }
    }

    $Element.mouseenter(function (event) {
        x = event.pageX;
        y = event.pageY;
        show();
    });

    $Element.bind('mousemove.hint', function (event) {
        x = event.pageX;
        y = event.pageY;
        $Element.unbind('mousemove.hint');
        show();
    });
    $Element.mouseleave(function () {
        clearTimeout(element.timer);
        element.timer = setTimeout(function () { $HintBlock.hide(); }, timeout);
    });
    $HintBlock.mouseenter(function () {
        clearTimeout(element.timer);
    }).mouseleave(function () {
        clearTimeout(element.timer);
        $Element[0].timer = setTimeout(function () { $HintBlock.hide(); }, timeout);
    });
    clearTimeout(element.timer);
}

/*$(function () {
	$(".js-head-announce_refresh").click(function () {
		var announces = $(this).parents(".js-head-announces-container").find(".js-head-announce");

		if (announces.length == 1)
			return false;

		var selectedIndex = -1;
		announces.each(function (index) {
			if ($(this).is(":visible")) {
				selectedIndex = index;
			}
		});

		if (selectedIndex >= 0) {
			$(announces[selectedIndex]).hide();
			if ((++selectedIndex) >= announces.length)
				selectedIndex = 0;

			$(announces[selectedIndex]).show();
		}

		return false;
	});
});*/

//note включение асинхронной работы блока подписки
//note используется в 3х проектах(если будут правки, то скопипастить везде)
function InitPostSimpleFormAsync(form, url, showSuccessMessage, successCallback) {
    ShowFormChildren(form);
    form.submit(function () {
        form.find("input[type=submit]").attr("disabled", "false");
        RemoveErrors(form);
        var data = form.serializeArray();
        $.ajax({
            type: "POST",
            url: url,
            data: data,
            dataType: "json",
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            success: function (data) {
                RemoveErrors(form);
                var hasErrors = false;
                for (var k in data.Errors) {
                    hasErrors = true;
                    var input = form.find('[name=' + k + ']');
                    //note хак выбираем инпуты, у которых нет нейма (отрезан textNote)
                    if (input.length == 0)
                        input = form.find('#' + k.replace(/\./gi, '_'));
                    input.addClass('input-validation-error');
                    var errorStr = "";
                    $.each(data.Errors[k], function(index, item) { errorStr += ' ' + item; });
                    input.after('<div><span  class = "field-validation-error">' + errorStr + '</span></div>');
                }
                if (data.Errors["Form"])
                    form.prepend('<div><span  class = "field-validation-error">' + data.Errors["Form"][0] + '</span></div>');
                if (!hasErrors) {
                    if (showSuccessMessage)
                        ShowSuccessMessage(data.Message, form);
                    ClearTextInputs(form);
                    if (successCallback)
                        successCallback(data);
                }

            },
            complete: function () { form.find("input[type=submit]").removeAttr("disabled"); }
        });
        return false;
    });
    //note Если на инпут повешано, что-то еще (например саджест), то могут возникнуть лишние запросы на сервер и др проблемы. Тк тут вызывается blur, для того, чтобы появилась серая подсказка (textNode)
    function ClearTextInputs(form) {
        form.find(":text,textarea").each(ClearInput);
    }

    function ClearInput() {
        var domElement = this;
        var jqElement = $(domElement);
        jqElement.val('');
        jqElement.blur();
    }

    function ShowFormChildren(form, showSuccessMessage) {
        if (showSuccessMessage)
            var messageContainer = GetMessageContainer(form);

        form.show();

        if (showSuccessMessage)
            messageContainer.hide();
    }

    function RemoveErrors(form) {
        var inputs = form.find(":input");
        inputs.removeClass('input-validation-error');
        form.find(".field-validation-error").parent().remove();
    }

    function GetMessageContainer(form) {
        var messageContainer = form.parent().find(".js-successMessage");
        if (messageContainer.length == 0)
            throw new Error('Ожидалось, что лайтбокс имеет класс js-successMessage');
        return messageContainer;
    }

    function ShowSuccessMessage(message, form) {
        var messageContainer = GetMessageContainer(form);
        form.hide();
        closeBtn = messageContainer.find('input');
        messageContainer.find('p').remove();
        closeBtn.before('<p class="form_submit_panel_message">' + message + '</p>');
        closeBtn.click(function () { LightBox.hide(); });
        messageContainer.show();
    }
}

function BindTextChangeEventHandler(elementId, handler) {
    $('#' + elementId).bind('keyup cut paste', function () {
        setTimeout(handler, 0);
    });
}


function BookmarkManager() {
    var defaultFolderNamePrefix = 'Новая папка';

    this.calculateNextFolderOrdinalNumber = CalculateNextFolderOrdinalNumber;
    this.generateFolderName = GenerateFolderName;
    this.clearWarning = ClearWarning;

    function CalculateNextFolderOrdinalNumber(titleElements) {
        var folderNameRegExp = new RegExp(defaultFolderNamePrefix + ' (\\d+)$');

        var ordinal = 0;
        
        for (var i = 0; i < titleElements.length; i++) {

            var folderTitle = $(titleElements[i]).text();

            if (ordinal == 0 && folderTitle == defaultFolderNamePrefix) {
                ordinal = 1;
                continue;
            }
            var matches = folderNameRegExp.exec(folderTitle);
            if (!matches || matches.length < 2) continue;
            
            var number = parseInt(matches[1]);

            if (number > ordinal) ordinal = number;

        }
        return ordinal + 1;
    }

    function GenerateFolderName(titleElements) {

        var ordinal = CalculateNextFolderOrdinalNumber(titleElements);

        if (ordinal > 1)
            return defaultFolderNamePrefix + ' ' + ordinal;
        return defaultFolderNamePrefix;
    }

    function ClearWarning(fieldId) {
        var field = $('#' + fieldId);

        field.parent().find(".js-folder-comment").html("");
    }
}

BookmarkManager = new BookmarkManager();

function escapeExt(text) {
    return escape(text).replace(/\/+/, "%2F");
}


