﻿/*Сайты СКБ Контур*/
function KonturSites(button, popup) {
	button = typeof (button) == 'string' ? document.getElementById(button) : button;
	popup = typeof (popup) == 'string' ? document.getElementById(popup) : popup;

	button.onclick = function() {
	    //var pos = getAbsolutePosition(button);
	    //popup.style.left = pos.x + "px";
	    //popup.style.top = pos.y + "px";
	    $(popup).toggle();
	    return false;
	}
	popup.onmouseout = function(Event) {
		var rt = window.event ? event.toElement : Event.relatedTarget;
		while (rt && rt != document.documentElement) {
			if (rt == popup) return false;
			rt = rt.parentNode;
		};
		popup.style.display = 'none';
	};
}
//возвращает абсолютную позицию блока
function getAbsolutePosition(id) {
	id = typeof (id) == 'string' ? ('#' + id) : id;
	var pos = $(id).offset();
	var marg = (document.documentElement.clientWidth - document.body.offsetWidth) / 2;
	marg = marg > 0 ? Math.floor(marg) : 0;
	return { x: (pos.left - marg), y: pos.top };
}

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 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';
	if (window.opera) t.style.cssText = "overflow:hidden;border:solid 1px #ccc;";
	t.h = t.clientHeight;
	var tresize = function () {
		if (!t.h) t.h = t.clientHeight - 2;
		if (!document.all && !window.opera) t.style.height = "0px";
		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).bind('keyup', tresize)
	.bind('blur', tresize)
	.bind('focus', tresize)
	.bind('cut', function () { setTimeout(tresize, 0) })
	.bind('paste', function () { setTimeout(tresize, 0) });
	t.style.height = div.style.minHeight = ((t.scrollHeight + 20) > t.h ? (t.scrollHeight + 20) : t.h) + 'px';
	t.style.height = 0;
	$(t).keyup();
};

function SelectText(text) {
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}

function coptyToClipBoard(id) {
    $("#" + id).get(0).createTextRange().execCommand("Copy");
}

/**
* SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
*
* SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
if (typeof deconcept == "undefined") { var deconcept = new Object(); } if (typeof deconcept.util == "undefined") { deconcept.util = new Object(); } if (typeof deconcept.SWFObjectUtil == "undefined") { deconcept.SWFObjectUtil = new Object(); } deconcept.SWFObject = function(_1, id, w, h, _5, c, _7, _8, _9, _a) { if (!document.getElementById) { return; } this.DETECT_KEY = _a ? _a : "detectflash"; this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY); this.params = new Object(); this.variables = new Object(); this.attributes = new Array(); if (_1) { this.setAttribute("swf", _1); } if (id) { this.setAttribute("id", id); } if (w) { this.setAttribute("width", w); } if (h) { this.setAttribute("height", h); } if (_5) { this.setAttribute("version", new deconcept.PlayerVersion(_5.toString().split("."))); } this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion(); if (!window.opera && document.all && this.installedVer.major > 7) { deconcept.SWFObject.doPrepUnload = true; } if (c) { this.addParam("bgcolor", c); } var q = _7 ? _7 : "high"; this.addParam("quality", q); this.setAttribute("useExpressInstall", false); this.setAttribute("doExpressInstall", false); var _c = (_8) ? _8 : window.location; this.setAttribute("xiRedirectUrl", _c); this.setAttribute("redirectUrl", ""); if (_9) { this.setAttribute("redirectUrl", _9); } }; deconcept.SWFObject.prototype = { useExpressInstall: function(_d) { this.xiSWFPath = !_d ? "expressinstall.swf" : _d; this.setAttribute("useExpressInstall", true); }, setAttribute: function(_e, _f) { this.attributes[_e] = _f; }, getAttribute: function(_10) { return this.attributes[_10]; }, addParam: function(_11, _12) { this.params[_11] = _12; }, getParams: function() { return this.params; }, addVariable: function(_13, _14) { this.variables[_13] = _14; }, getVariable: function(_15) { return this.variables[_15]; }, getVariables: function() { return this.variables; }, getVariablePairs: function() { var _16 = new Array(); var key; var _18 = this.getVariables(); for (key in _18) { _16[_16.length] = key + "=" + _18[key]; } return _16; }, getSWFHTML: function() { var _19 = ""; if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); this.setAttribute("swf", this.xiSWFPath); } _19 = "<embed type=\"application/x-shockwave-flash\" src=\"" + this.getAttribute("swf") + "\" width=\"" + this.getAttribute("width") + "\" height=\"" + this.getAttribute("height") + "\" style=\"" + this.getAttribute("style") + "\""; _19 += " id=\"" + this.getAttribute("id") + "\" name=\"" + this.getAttribute("id") + "\" "; var _1a = this.getParams(); for (var key in _1a) { _19 += [key] + "=\"" + _1a[key] + "\" "; } var _1c = this.getVariablePairs().join("&"); if (_1c.length > 0) { _19 += "flashvars=\"" + _1c + "\""; } _19 += "/>"; } else { if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); this.setAttribute("swf", this.xiSWFPath); } _19 = "<object id=\"" + this.getAttribute("id") + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"" + this.getAttribute("width") + "\" height=\"" + this.getAttribute("height") + "\" style=\"" + this.getAttribute("style") + "\">"; _19 += "<param name=\"movie\" value=\"" + this.getAttribute("swf") + "\" />"; var _1d = this.getParams(); for (var key in _1d) { _19 += "<param name=\"" + key + "\" value=\"" + _1d[key] + "\" />"; } var _1f = this.getVariablePairs().join("&"); if (_1f.length > 0) { _19 += "<param name=\"flashvars\" value=\"" + _1f + "\" />"; } _19 += "</object>"; } return _19; }, write: function(_20) { if (this.getAttribute("useExpressInstall")) { var _21 = new deconcept.PlayerVersion([6, 0, 65]); if (this.installedVer.versionIsValid(_21) && !this.installedVer.versionIsValid(this.getAttribute("version"))) { this.setAttribute("doExpressInstall", true); this.addVariable("MMredirectURL", escape(this.getAttribute("xiRedirectUrl"))); document.title = document.title.slice(0, 47) + " - Flash Player Installation"; this.addVariable("MMdoctitle", document.title); } } if (this.skipDetect || this.getAttribute("doExpressInstall") || this.installedVer.versionIsValid(this.getAttribute("version"))) { var n = (typeof _20 == "string") ? document.getElementById(_20) : _20; n.innerHTML = this.getSWFHTML(); return true; } else { if (this.getAttribute("redirectUrl") != "") { document.location.replace(this.getAttribute("redirectUrl")); } } return false; } }; deconcept.SWFObjectUtil.getPlayerVersion = function() { var _23 = new deconcept.PlayerVersion([0, 0, 0]); if (navigator.plugins && navigator.mimeTypes.length) { var x = navigator.plugins["Shockwave Flash"]; if (x && x.description) { _23 = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split(".")); } } else { if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0) { var axo = 1; var _26 = 3; while (axo) { try { _26++; axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + _26); _23 = new deconcept.PlayerVersion([_26, 0, 0]); } catch (e) { axo = null; } } } else { try { var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); } catch (e) { try { var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); _23 = new deconcept.PlayerVersion([6, 0, 21]); axo.AllowScriptAccess = "always"; } catch (e) { if (_23.major == 6) { return _23; } } try { axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); } catch (e) { } } if (axo != null) { _23 = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(",")); } } } return _23; }; deconcept.PlayerVersion = function(_29) { this.major = _29[0] != null ? parseInt(_29[0]) : 0; this.minor = _29[1] != null ? parseInt(_29[1]) : 0; this.rev = _29[2] != null ? parseInt(_29[2]) : 0; }; deconcept.PlayerVersion.prototype.versionIsValid = function(fv) { if (this.major < fv.major) { return false; } if (this.major > fv.major) { return true; } if (this.minor < fv.minor) { return false; } if (this.minor > fv.minor) { return true; } if (this.rev < fv.rev) { return false; } return true; }; deconcept.util = { getRequestParameter: function(_2b) { var q = document.location.search || document.location.hash; if (_2b == null) { return q; } if (q) { var _2d = q.substring(1).split("&"); for (var i = 0; i < _2d.length; i++) { if (_2d[i].substring(0, _2d[i].indexOf("=")) == _2b) { return _2d[i].substring((_2d[i].indexOf("=") + 1)); } } } return ""; } }; deconcept.SWFObjectUtil.cleanupSWFs = function() { var _2f = document.getElementsByTagName("OBJECT"); for (var i = _2f.length - 1; i >= 0; i--) { _2f[i].style.display = "none"; for (var x in _2f[i]) { if (typeof _2f[i][x] == "function") { _2f[i][x] = function() { }; } } } }; if (deconcept.SWFObject.doPrepUnload) { if (!deconcept.unloadSet) { deconcept.SWFObjectUtil.prepUnload = function() { __flash_unloadHandler = function() { }; __flash_savedUnloadHandler = function() { }; window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs); }; window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload); deconcept.unloadSet = true; } } if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }; } var getQueryParamValue = deconcept.util.getRequestParameter; var FlashObject = deconcept.SWFObject; var SWFObject = deconcept.SWFObject;

// Всплывающее окно для показа изображения/изображений (если есть imgObjectArray)
function ShowImagesLightBox(imgObjectArray, currentImageSrc, srcPath) {
	var ic = document.getElementById("ImageContainer");
	var img;
	var load;
	var imgIndex = GetImgIndex(imgObjectArray, currentImageSrc);
	var prevImage = $('#previousImage');
	var prevImage = $('#nextImage');
	var prevImageEmpty = $("#previousImageEmpty");
	var nextImageEmpty = $('#nextImageEmpty');
	var title = $('#TitleContainer');
	var announce = $('#AnnounceContainer');
	if (imgObjectArray.length == 0) {
		prevImage.hide();
		prevImage.hide();
	}
	window.__resize = function() {
		if (!img.load) return false;
		var w = document.documentElement.clientWidth - 40;
		announce.css('width', img.width);
		var h = document.documentElement.clientHeight - (imgObjectArray.length == 0 ? 90 : 110) - announce.height();
		w = w < 100 ? 100 : w;
		h = h < 80 ? 80 : h;
		
		img.removeAttribute("height");
		img.removeAttribute("width");
		if ((h / img.maxHeight) < (w / img.maxWidth)) {
			if (h < img.maxHeight) img.height = h;
		} else {
			if (w < img.maxWidth) img.width = w;
		}
		announce.css("width", img.width);
	};
	var newImage = function() {
		ic.innerHTML = "";
		img = document.createElement("img");
		load = document.createElement("div");
		ic.appendChild(load);
		load.style.cssText = "width:200px;height:200px;position:relative;background:url(/theme/images/imgload.gif) center no-repeat;";
		ic.appendChild(img);
		img.load = false;
		img.style.display = "none";
		img.removeAttribute("height");
		img.removeAttribute("width");
		if (document.all && !window.opera) document.body.removeExpression("resize");
		if (document.all) {
			document.body.setExpression("resize", "window.__resize()");
			$(window).load(function() {
				document.body.removeExpression("resize");
			});
		}
		img.onload = function() {
			if (load.parentNode) ic.removeChild(load); //?
			else load = null;

			img.style.display = "inline";
			img.maxHeight = img.offsetHeight;
			img.maxWidth = img.offsetWidth;
			img.load = true;
			window.__resize();
		};
	};
	newImage();
	LightBox.show("ImageLightBox", {Width:'200'});

	function setLightboxContent(imgIndex) {
		img.src = srcPath + imgObjectArray[imgIndex].Image;
		title.html(imgObjectArray[imgIndex].Title);
		announce.html(imgObjectArray[imgIndex].Announce);
	}

	setLightboxContent(imgIndex);

	$(window).resize(function() {
		if (document.all && document.body.getExpression("resize")) {
			document.body.removeExpression("resize");
		}
		window.__resize();
	});

	function ShowHideArrows(imgIndex) {
		if (imgIndex <= 0) {
			prevImage.hide();
			prevImageEmpty.show();
		}
		else {
			prevImage.show();
			prevImageEmpty.hide();
		}
		if (imgIndex >= imgObjectArray.length - 1) {
			nextImage.hide();
			nextImageEmpty.show();
		}
		else {
			nextImage.show();
			nextImageEmpty.hide();
		}
	}

	function GetImgIndex(images, img) {
		for (var i = 0; i < images.length; i++) {
			if (images[i].Image == img)
				return i;
		}
		return -1;
	}

	var prevImage = $('#previousImage');
	var nextImage = $('#nextImage');
	ShowHideArrows(imgIndex);


	$(prevImage).unbind('click').bind('click', function() {
		imgIndex--;
		newImage();
		setLightboxContent(imgIndex);
		ShowHideArrows(imgIndex);
		return false;
	});

	$(nextImage).unbind('click').bind('click', function() {
		imgIndex++;
		newImage();
		setLightboxContent(imgIndex);
		ShowHideArrows(imgIndex);
		return false;
	});
	$(prevImageEmpty).click(function() { return false; });
	$(nextImageEmpty).click(function() { return false; });
	$("#previousNextContainer").click(function() {
		lightBox.hide();
	});
	if (imgObjectArray.length <= 1) {
		$(prevImageEmpty).hide();
		$(nextImageEmpty).hide();
	}

}


function SubstituteIndexInTemplate(template, index) {
	return template.replace(/\:index\:/ig, index);
}
function FormInsertItem(sourceIdStr, insertBeforeObj, afterAction, start) {
	var l = document.getElementById(sourceIdStr);
	insertBeforeObj = typeof (insertBeforeObj) == 'string' ? document.getElementById(insertBeforeObj) : insertBeforeObj;
	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);
}

function copyAllAttributes(source, dest) {
	if (document.all)
		for (var j in source.attributes) {
		dest.setAttribute(j, source.getAttribute(j));
	}
	else
		for (var j = 0; j < source.attributes.length; j++) {
		dest.setAttribute(source.attributes[j].name, source.attributes[j].value);
	}
	return dest;
}

function FormTableDeleteRow(rowObj) {
	var lineNumber = rowObj.lineNumber;
	if (lineNumber == null)
		return;

	var table = rowObj.parentNode.parentNode;

	var rows = table.rows;
	var index = 0;
	// далее length-1 -- чтобы не стереть ряд-якорь для добавления новых строк
	while (index < rows.length - 1 && rows[index].lineNumber != lineNumber)
		index++;
	while (index < rows.length - 1 && rows[index].lineNumber == lineNumber)
		table.deleteRow(index);
}

function FormTableInsertRow(sourceIdStr, insertBeforeObj, afterAction, start) {
	start = start || 0;

	var insertBeforeObj = typeof (insertBeforeObj) == 'string'
		? document.getElementById(insertBeforeObj)
		: insertBeforeObj;

	var template = $("#" + sourceIdStr);
	var isTable = template[0].tagName.toLowerCase() == "table";

	var sourceTrs = isTable
		? $("tbody > tr", template)
		: template;

	if (!insertBeforeObj.i)
		insertBeforeObj.i = start;

	sourceTrs.each(function() {
		var sourceTr = this;
		var newRow = insertBeforeObj.parentNode.insertRow(insertBeforeObj.rowIndex);
		var newCell;
		for (var i = 0; i < sourceTr.cells.length; i++) {
			newCell = newRow.insertCell(i);
			newCell.innerHTML = SubstituteIndexInTemplate(sourceTr.cells[i].innerHTML, insertBeforeObj.i);
			copyAllAttributes(sourceTr.cells[i], newCell);
		}
		copyAllAttributes(sourceTr, newRow);
		newRow.removeAttribute("id");

		newRow.numberOfRowsInGroup = sourceTrs.length;
		newRow.lineNumber = insertBeforeObj.i;
	});

	if (typeof (afterAction) == 'function')
		afterAction(insertBeforeObj.i);
	insertBeforeObj.i++;
}

function FormInsertTbody(sourceIdStr, insertBeforeObj, afterAction, start) {
	var insertBeforeObj = typeof (insertBeforeObj) == 'string' ? $('#' + insertBeforeObj) : $(insertBeforeObj);
	var template = $("#" + sourceIdStr);

	if (!insertBeforeObj[0].i)
		insertBeforeObj[0].i =  start || 0;

	var newObj = template.clone(true).insertBefore(insertBeforeObj);
	
	newObj.removeAttr("id");
	newObj.html(SubstituteIndexInTemplate(newObj.html(), insertBeforeObj[0].i));

	if (typeof (afterAction) == 'function')
		afterAction(insertBeforeObj.i);

	insertBeforeObj[0].i++;
}
function FormDeleteTbody(tbodyObj) {
	$(tbodyObj).remove();
}

function ReindexNames(form) {
	function GetElementsArray() {
		var elements = [];
		for (var i = 0; i < form.elements.length; i++)
			elements.push(form.elements[i]);
		return elements;
	}


	var indexedNameRegex = /\[(\d+)\]/;
	var indexInGroup = {};


	$(GetElementsArray())
		.filter(function() { return this.name != null && indexedNameRegex.test(this.name); })
		.map(function() {
			var group = this.name.replace(indexedNameRegex, "");
			indexInGroup[group] = 0;
			return { Element: $(this), Group: group };
		})
		.each(function() {
			var currentIndexInGroup = indexInGroup[this.Group]++;
			var reindexedName = this.Element.attr("name").replace(indexedNameRegex, "[" + currentIndexInGroup + "]");
			this.Element.attr("name", reindexedName);
		});
}


function PreventFormSubmitOnEnter() {
	$(":text,:radio,:checkbox").live("keypress", function(event) {
		event = event || window.event;
		return (event.which || event.keyCode) != 13;
	});
}

// желательно вызывать последним на странице
function AttachDataLossPreventor() {
	$(document).ready(Init);

	function Init() {
		var preventDataLoss = true;

		MarkButtonsAllowingDataLoss();
		SetDefaultValues();
		AttachOnBeforeUnload();

		function MarkButtonsAllowingDataLoss() {
			function AllowDataLoss() {
				preventDataLoss = false;
			}

			$("[allowdataloss=true]").click(AllowDataLoss);
		}

		function SetDefaultValues() {
			ChangeableElements().each(function() {
				this.defaultValue = this.value;
				this.defaultChecked = this.checked;
			});
		}

		function AttachOnBeforeUnload() {
			function OnBeforeUnload(evt) {
				if (preventDataLoss && FormDataChanged()) {
					var message = "При переходе заполненные данные будут потеряны.";
					if (evt != null)
						evt.returnValue = message;
					return message;
				}
			}
			window.onbeforeunload = OnBeforeUnload;

			function FormDataChanged() {
				function ElementChanged() {
					return this.value != this.defaultValue || this.checked != this.defaultChecked;
				}
			
				return ChangeableElements().filter(ElementChanged).length > 0;
			}
		}

		function ChangeableElements() {
			return $("input,textarea");
		}
	}
}

function UserManual(expandAllId, headTextClass, headTitleClass) {
    var showLinkText = 'Развернуть все';
    var hideLinkText = 'Свернуть все';
	function ShowHideAllHeads() {
		var blocks = $('.' + headTextClass);
		if ($('#' + expandAllId).text() == showLinkText) {
			blocks.show();
		}
		else {
			blocks.hide();
		}
		UpdateLink();
}

	function ShowHideHeads() {
		var blocks = $('.' + headTitleClass);
		blocks.each(function() {
		    $(this).click(function() {
		        $(this).parent().next().toggle();
		        UpdateLink();
		        return false;
		    });
		});
	}

	function UpdateLink() {
		if (AllAreVisible()) {
		    $('#' + expandAllId).text(hideLinkText);
		} else if (AllAreHidden()) {
		$('#' + expandAllId).text(showLinkText);
		}
	}

	function AllAreVisible() {
		var blocksAll = $('.' + headTextClass);
		var blocksVisible = $('.' + headTextClass + ':visible');
		return blocksAll.length == blocksVisible.length;
	}

	function AllAreHidden() {
		var blocksAll = $('.' + headTextClass);
		var blocksVisible = $('.' + headTextClass + ':visible');
		return blocksVisible.length == 0;
	}

	function Init() {
		$('#' + expandAllId).click(function() { ShowHideAllHeads(); return false; })
		ShowHideHeads();
	}

	$(Init);
}


/// Заявка {

function AttachKppHider(innId, kppId) {
	var inn = $("#" + innId);
	var kpp = $("#" + kppId);

	function KeyUpHandler() {
		var input = this;
		if (!input.disabled) {
			setTimeout(function() {
				ToggleKpp(input.value != null && input.value.length != 12);
			}, 0);
		}
	}

	function ToggleKpp(isForOrganization) {
		if (isForOrganization) {
			kpp[0].disabled = false;
			FindTr(kpp).removeClass("dim");
		} else {
			kpp[0].disabled = true;
			FindTr(kpp).addClass("dim");
		}
	}

	function FindTr(element) {
		while (element != null && element[0] != null && element[0].tagName != "TR") {
			element = element.parent();
		}
		return element;
	}

	inn.keyup(KeyUpHandler).blur(KeyUpHandler).bind('cut', KeyUpHandler).bind('paste', KeyUpHandler);
	KeyUpHandler.call(inn[0]);
}

function IsClientSelector() {
	This = this;

	function Init() {
		This.clientInfo = $('#clientInfoId');
		This.regionAndCity = $('#notClientInfoId');
		This.isSkbKonturClientYes = $('#isSkbKonturClientYes');
		This.isSkbKonturClientNo = $('#isSkbKonturClientNo');
		This.isSkbKonturClientYes.change(function() { SelectForm(); })
		This.isSkbKonturClientNo.change(function() { SelectForm(); });
		$('#isSkbKonturClientId').show();
		SelectForm();
	}

	function EnableBlock(block) {
		block.show();
	}

	function DisableBlock(block) {
		block.hide();
	}

	function SelectForm() {
		if (This.isSkbKonturClientYes.attr('checked') == true) {
			EnableBlock(This.clientInfo);
			DisableBlock(This.regionAndCity);
			This.isSkbKonturClientNo.parents('.js-orderTab').removeClass('js-orderTab__active');
			This.isSkbKonturClientYes.parents('.js-orderTab').addClass('js-orderTab__active');
			$('#notClientStep2Title').hide();
		}
		else {
			EnableBlock(This.regionAndCity);
			DisableBlock(This.clientInfo);
			This.isSkbKonturClientYes.parents('.js-orderTab').removeClass('js-orderTab__active');
			This.isSkbKonturClientNo.parents('.js-orderTab').addClass('js-orderTab__active');
			$('#notClientStep2Title').show();
        }
	}

	$(Init);
}

/// Заявка }

// 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 (!inp.form) return;
	    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",
			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.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];
	        }
	        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 sx, sy, sw, sh;
	    sw = $(document).width();
	    sh = $(document).height();
	    sx = $(inp.suggest).offset().left;
	    sy = $(inp.suggest).offset().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';
	};
}
/* оставить покачто для отладки */

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 textNote(inputId, note) {
	function init() {
		var input = $('#' + inputId);
		if (!input[0]) return false;
		var name = '';
		var onblur = function () {
			if (input.val() == '') {
				input.val(note);
				input.empty = true;
				name = input.attr('name');
				input.removeAttr('name');
				input.css({ color: '#999' }); 
				input.addClass('empty');
			} else {
				input.empty = false;
				if (name)
					input.attr('name', name);
				input.removeClass('empty');
			}
		};
		var onfocus = function () {
		    if (input.empty) input.val('');
		    input.css({ color: '#000' });
		    input.addClass('empty');
		    if (name)
		        input.attr('name', name);
		};
        var onkeyup = function (event) {
            if (!event.keyCode) return;
			if ($(this).val()) $(this).empty = false;
			if (name)
				input.attr('name', name);
		};
		input.bind('blur', onblur);
		input.bind('focus', onfocus);
		input.bind('keyup', onkeyup);
		if (input.val() == note) input.val('');
		onblur();
	}
	$(document).ready(init);
}

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 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();
    }
}

//note включение асинхронной работы блока подписки
//note используется в 3х проектах(если будут правки, то скопипастить везде)
function InitPostSimpleFormAsync(form, url, successCallback) {
	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) {
					ShowLightBox(data.Message, form);
					ClearTextInputs(form);
					if (successCallback)
						successCallback();
				}
},
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 RemoveErrors(form) {
		var inputs = form.find(":input");
		inputs.removeClass('input-validation-error');
		form.find(".field-validation-error").parent().remove();
	}

	function ShowLightBox(message, form) {
		var lightBox = form.find(".b-subscription_lightbox");
		if (lightBox.length == 0)
			throw new Error('Ожидалось, что лайтбокс имеет класс b-subscription_lightbox');
		lightBox.html(message);
		//todo Юра попробовать использовать индекс формы в доме или текущее время, для генерации уникального ид (не испльзуя ид формы)
		var lightBoxId = form.attr('id') + 'lightBox';
		lightBox.attr('id', lightBoxId);
		LightBox.show(lightBoxId);
	}
}


/* Отслеживание событий */

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 plural(n, form1, form2, form3) {
    var pluralForm = ((n % 10 == 1) && n % 100 != 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2));
    switch (pluralForm) {
        case 0:
        default:
            return form1;
        case 1:
            return form2;
        case 2:
            return form3;
    }
} 

