﻿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: '50%', left: '50%', margin: '-115px -190px'} });
}

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("<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();
	$.get(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);
	$.get(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();
	$.get(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());
		$.get(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',
		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 = escape(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(idStr)
{
	var t = document.getElementById(idStr);
	var div = document.createElement('div');
	t.parentNode.insertBefore(div, t);
	div.appendChild(t.parentNode.removeChild(t));
	t.style.overflowY = 'hidden';
	t.style.overflowX = document.all != undefined ? '' : 'hidden';
	t.h = t.clientHeight;
	t.onkeyup = function() {
	if (!t.h) t.h = t.clientHeight - 2;
		if (!document.all && !window.opera) t.style.height = "0px";
		t.style.height = div.style.minHeight = ((t.scrollHeight + 20) > t.h ? (t.scrollHeight + 20) : t.h) + 'px';
	};
	t.onfocus = t.onkeyup;
};

function commentsQuote(name, message)
{
	$('#addCommentClosedBlock').hide(); $('#addCommentOpenedBlock').show();
	q = '[quote=' + name + ']' + message + '[/quote]';
	t = document.getElementById('message');
	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 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.hidden = 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 + escape(FormatInput(inp.value, true)), //escape wrong for safari
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(data) { inp.ready(data); }
		});
	};
	inp.data = function(obj)//set values text input [and hidden input]
	{
		inp.value = obj.data;
		if (inp.hidden) inp.hidden.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];
			}
			//li.innerHTML += data[i].comment ? "<div class='comment'>" + data[i].comment + "</div>" : '';
			var re = new RegExp('(' + FormatInput(inp.value, false) + ')', 'gi')
			if (opts.light) {
				li.innerHTML = li.innerHTML.replace(re, '<b>$1</b>');
				if (data[i].comment != null) {
					var comm = data[i].comment.replace(re, '<b>$1</b>')
					li.innerHTML += data[i].comment ? "<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 sx, sy;
		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';
		}

		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',
				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)
{
	var input = document.getElementById(inputId);
	if (!input) return false;
	var onblur = function()
	{
		if (input.value == '')
		{
			input.value = note;
			input.empty = true;
			input.style.color = '#999';
			input.className = 'empty';
		}
		else
		{
			input.empty = false;
			input.className = '';
		}
	};
	var onfocus = function() {
		if (input.empty) input.value = '';
		input.style.color = '#000';
		input.className = 'empty';
	};
	var onkeyup = function()
	{
		if (this.value) this.empty = false;
	};
	$(input).bind('blur', onblur);
	$(input).bind('focus', onfocus);
	$(input).bind('keyup', onkeyup);
	if (input.value == note) input.value = '';
	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) {
	link = $(link);
	var noteContainer = GetNoteContainer(link);
	var messageId = link.attr("messageId");

	function OnSaidThankYou(result) {
		noteContainer.html(result.note);
		noteContainer.show();
		link.hide().attr("thanked", "true");
	}
	$.getJSON("/rating/SayThankYouAsync", { messageId: messageId }, OnSaidThankYou);
	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());

		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();
		} else {
			link.attr("opened", "false");
			link.attr("title", "Разрешить баллы");
			image.src = image.src.replace("b_block.gif", "b_enable.gif");
			thanksLink.hide();
		}
	}
	$.getJSON("/rating/OpenForThanksAsync", { open: needOpen, messageId: messageId }, OnOpened);
	return false;
}

function CalcLeftCharsAndTruncateValue(obj, charLeftHolder) {
	if (obj == null || obj.value == null || $(obj).attr('maxlength') == null || charLeftHolder.length == 0) return;
	var chars = obj.value.length;
	var maxChars = $(obj).attr('maxlength');
	var leftChars = maxChars - chars;
	if (leftChars < 0) {
		obj.value = obj.value.substr(0, maxChars);
		leftChars = 0;
	}
	charLeftHolder.html(leftChars);
}

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; });
}
