function $GbID(id) { return document.getElementById(id); } 

/*ALPHA TRANSPERANCY FOR PNG IMAGES IN IE6*/
function fixPNG(element)
{
	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
	{
		var src;
		if (/\.png$/.test(element.src))
		{
		src = element.src;
		element.src = "/media/system/imgs/blank.gif";
		}
		if (src) {
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='crop')";
			}
	}
}
/*END ALPHA TRANSPERANCY FOR PNG IMAGES IN IE6*/

/*UTILS*/
Utils = {
/* 
	*	Calculating page dimentsions if document is smaller then window selecting window {width; height} otherwise document {width; height}
	*	for IE 6,7 calculating left offset caused by centered layout
	*/
	getPageSize : function(isWinsize){
		if (window.innerHeight)
		{
			var height = window.innerHeight;
			var width =  window.innerWidth;
			var _ieMarginLeft = 0;
		}else{
			var height = document.documentElement.clientHeight;
			var width =  document.documentElement.clientWidth;
			var mainWidth = $('#main')[0].offsetWidth;
			var _ieMarginLeft = Math.round((width-mainWidth)/2);
		}
		var contentHeight = $('#main')[0].offsetHeight;
		if(contentHeight > height && !isWinsize){
			height = contentHeight;
		}
		var contentWidth = $('#main')[0].offsetWidth; 
		if(contentWidth > width && !isWinsize){
			width = contentWidth + 40; //adding 40px caused by #body and #scroller containeres padding
		}
		return {'x' : width,'y' : height,'_ieOffset' : _ieMarginLeft}
	},

	debug : function(obj){
		try{console.debug(obj);}catch(e){}
		try{opera.postError(obj);}catch(e){}
	},

	getScrollPosition : function(){
		var scrollTop = document.body.scrollTop;
		if (scrollTop == 0)
		{
		    if (window.pageYOffset)
		        {scrollTop = window.pageYOffset;}
		    else
		        {scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;}
		}
		return scrollTop;
	},
	
	getNavigationCities : getRegionCitiesFullList, /*function(value){
		return {
			"city": {
				"msk": [
					["msk", "Москва"],
					["chimki", "Химки"]
				],
				"spb": [
					["spb", "Санкт-петербург"]
				]
			}
		}
	},*/

	lastIDcookies : {
		set : function(caseID){
			if(caseID != '') {
				document.cookie = "caseData={caseID : '"+caseID+"', date : '"+new Date().toString()+"'}; expires=Thu, 1 Aug 2200 00:00:00 UTC; path=/";
			}
		},
		get : function(){
			var data = document.cookie.split('caseData=')[1];
			    return eval('('+data+')');
		},
		compare : function(wwwCookie, myCookie){
			return new Date(myCookie['date']) > new Date(wwwCookie['date']) ? myCookie['caseID'] : wwwCookie['caseID'];
		}	
	}
}
/*END UTILS*/



/* MAIN MENU*/
var Menu = {
	overlay: null,
	menuItems: null,
	blockedScreen: false,

	Menu: function()
	{
		if (this.menuItems == null && this.overlay == null)
		{
			this.overlay = $('#overlay');
			this.overlay[0].thisObj = this;
			this.overlay.click(this.toggleMenu);
			this.menuItems = $('#navigation li.menuItem');
			for (var i = 0, m, a, mm, body = $("body")[0]; i < this.menuItems.length; i++)
			{
				m = this.menuItems[i];	
				this.menuItems[i].imgdiv = $('div', this.menuItems[i])[0];
				this.menuItems[i].textSpan = $('span', this.menuItems[i])[0];
				m.thisObj = this;
				try
				{
					mm = $(m);
					a = $(document.createElement("a"));
					a.click(this.toggleMenu).mouseout(this.rollOver).mouseover(this.rollOver);
					a.css({ position: "absolute", left: "-10000px", top: "-10000px", display: "block", width: mm.width(), height: mm.height(), "z-index": 100 });
					m.anc = body.appendChild(a[0]);
					a[0].thisObj = this;
					a[0].menuItem = m;
				} catch (er) { }
			}
			this.menuItems.click(this.toggleMenu).mouseout(this.rollOver).mouseover(this.rollOver);
		} else
		{
			throw "Menu is already initialized";
		}
	},
	
	rollOver : function(e){
		var context = this.menuItem || this;
		if(context.style.zIndex){
			e.type === 'mouseover' ? context.textSpan.style.color = '' : context.textSpan.style.color = '';
//			e.type === 'mouseover' ? context.imgdiv.style.background = '' : context.imgdiv.style.background = '' ;
		}else{
			e.type === 'mouseover' ? context.textSpan.style.color = '#7D7D7D' : context.textSpan.style.color = '#a0792d';
			e.type === 'mouseover' ? context.imgdiv.className = 'bulletOver' : context.imgdiv.className = 'bullet' ;
		}
	},
	
	toggleMenu: function(evt)
	{
		var anc = this;
		var menuItem = anc.menuItem || this;
		var thisObj = menuItem.thisObj;
		$('#navigation .menuItem div').attr('class','bullet');
		// var thisObj = this.menuItem ? this.menuItem.thisObj : this.thisObj || this;
		if (!thisObj)
		{
			this.blockScreen(true);
			fbs.hide(fbs, true);
		} else if (thisObj.blockedScreen)
		{
			if(menuItem.style.zIndex){
				thisObj.blockScreen(true);
				fbs.hide(fbs, true);
			}else{
				evt.preventDefault();
				evt.stopImmediatePropagation();
				thisObj.blockedScreen = thisObj.blockScreen(menuItem);	
			}
		}
		// thisObj.blockedScreen = thisObj.blockScreen(this);
		if (thisObj && this.id != "overlay") thisObj.blockedScreen = thisObj.blockScreen(menuItem);
		/*if (thisObj.blockedScreen) {
		evt.preventDefault();
		evt.stopImmediatePropagation();
		}*/
		// if (this.menuItem && !thisObj.blockedScreen) thisObj.blockScreen(this.menuItem);
	},

	blockScreen: function(caller)
	{
		for (var i = 0, l = this.menuItems.length, m, offset, a; i < l; i++)
		{
			m = this.menuItems[i];
			offset = $(m).offset();
			a = m.anc;
			$(a).css({ left: offset.left + "px", top: offset.top + "px" });
		}
		if (this.blockedScreen && caller != null)
		{
			this.menuItems.css('z-index', '');
			this.menuItems.each(function()
			{
				var classes = this.className.split(' ');
				this.className = classes[0] + ' ' + classes[1];
				$('#' + classes[0]).css('display', 'none');
			});
			$('#submenu').css('display', 'none');
			this.overlay.css('display', 'none');
			return false;
		} else
		{
			try
			{
				caller.style.zIndex = 95;
				var curClass = caller.className;
				caller.className = curClass + ' active';
				$('#submenu').css('display', 'block');
				$('#' + curClass.split(' ')[0]).css('display', 'block');
			} catch (e) { }
			var dims = this.getpageDimensions();
			this.overlay.attr('style', 'display:block;width:' + dims['x'] + 'px; height:' + dims['y'] + 'px;//margin-left:-' + dims['_ieOffset'] + 'px;');
			return true;
		}
	},

	getpageDimensions: function()
	{
		return Utils.getPageSize(false);
	},

	popupNotify: function(b)
	{
		this.toggleMenu();
	},

	showMenu: function(menuItemClass)
	{
		var menuItem = $('#navigation li.menuItem.' + menuItemClass);
		menuItem.click();
	}
}

/*Changing dimensions of overlay layer when resizing window */
window.onresize = function(){
	if(Menu.blockedScreen){
		Menu.blockScreen(null);
		}
} 
/* END MAIN MENU*/

/*INPUT DEFAULT VALUE TOGGLER*/
/*
* 	Accepts any selector that results in <input> collection and adds to every input callback function for toggling 
*	default value that was in @value attribute/
*/
InputTextToggler = function(selector){	
	this.field = $(selector);
	for(var i = 0;i < this.field.length; i++){
		this.oldValue = this.field[i].value;
		this.field[i].thisToggler = this;
		this.field.focus(this.toggleField);
		this.field.blur(this.toggleField);
	}
}

InputTextToggler.prototype = {
	toggleField : function(){
		var thisObj = this.thisToggler;
		if(this.value == thisObj.oldValue){
			this.value = '';
		}else if(this.value == ''){
			this.value = thisObj.oldValue;
		}
	}
}
/* END INPUT DEFAULT VALUE TOGGLER*/

/* DEPEND OPTIONS */
DependOptions = function(source, dependent, dataType) {
	var dublicate = this;
	this.node = typeof(source)=="string" ? $(source)[0] : source;
	this.depNode = typeof(dependent)=="string" ? $(dependent)[0] : dependent;
	this.dataType = dataType || "";
	this.callBack = function(){};
	this.node.onchange = function() {
		dublicate._do.call(dublicate);
	};
};

DependOptions.prototype = {
	_do: function() {
		var id = this.node.id;
		var dispatcher = {
		};
		var dataName = this.dataType;
/*		var fullList = this.getData(this.node.value)[dataName] || {};*/
		var fullList = this.callBack(this.node.value)[dataName];
		var list = fullList[this.node.value];
		if (!list) return;
		
		this.depNode.options.length = 0;
		for (var i=0, l=list.length, opt; i<l; i++) {
			if (list[i])
			{
				opt = document.createElement("option");
				opt.value = list[i][0];
				if(list[i][2]){
					opt.selected = 'selected';
				}
				opt.innerHTML = list[i][1];
				this.depNode.appendChild(opt);
			}
		}
	},
	
	setCallback : function(callback){
		this.callBack = callback;
	}

};
/* END DEPEND OPTIONS */

/*  ALERT/CONFIRM POPUPS*/
var PopUp = function(target, mode, msg, header){
	this._container = $('#popup');
	this.mode = (mode == 'stateless') ? 'stateless' : mode;
	this.mode = (mode == '') ? 'alert' : mode;
	this.msg = msg;
	this.header = header;
	this.buttonText = {'ok' : 'ok', 'cancel' : 'cancel'};
	this.opened = false;
	this.resultListeners = new Array();
	
	if(target != ''){
		var target = $(target);
		target[0].thisObj = this;
		target.click(this.show);
	}
}

PopUp.prototype = {

	//	_container: null,

	setMessage: function(msg)
	{
		this.msg = msg
	},


	setContainer: function(selector)
	{
		this._container.after("<div id=" + selector + " />")
		this._container = $('#' + selector);
	},

	setButtonText: function(textArray)
	{
		this.buttonText = { 'ok': textArray['ok'], 'cancel': textArray['cancel'] };
	},

	addResultListeners: function(obj)
	{
		this.resultListeners.push(obj);
	},

	setPopupPosition: function(popup)
	{
		var scrollLeft = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
		var scrollTop = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);

		var clientWidth;
		if (window.innerWidth)
		{
			clientWidth = jQuery.browser.safari ? window.innerWidth : Math.min(window.innerWidth, document.documentElement.clientWidth);
		}
		else
		{
			clientWidth = document.documentElement.clientWidth;
		}

		var clientHeight;
		if (window.innerHeight)
		{
			clientHeight = jQuery.browser.safari ? window.innerHeight : Math.min(window.innerHeight, document.documentElement.clientHeight);
		}
		else
		{
			clientHeight = document.documentElement.clientHeight;
		}

		var left = scrollLeft + ((clientWidth - popup.width()) / 2);
		var top = scrollTop + ((clientHeight - popup.height()) / 2)

		popup.css("top", top + "px");
		popup.css("left", left + "px");
	},

	show: function(self, extraString)
	{
		// extraString goes to _generateContent where '%extraString%' in 'msg' is replaced by it
		var thisObj = !self ? this.thisObj : self;
		if (!thisObj.opened)
		{
			//thisObj._container.empty();
			thisObj._generateContent(extraString);

			thisObj.setPopupPosition(thisObj._container);
			thisObj._container.css("display", "block");

			var content = $('.content', this._container);
			var totalHeight = content.height() + parseInt(content.css('padding-top')) + parseInt(content.css('padding-bottom'));
			$('.contentLeft, .contentRight', this._container).height(totalHeight);
			$('.contentBottom', this._container).width((content.width()-1));
			$('.header', this._container).width(content.width() - 2);
			$('.header', this._container).height(23).css('left','1px');

		}
		thisObj.opened = true;
	},
	/*
	hide : function(e){
	var thisObj = this.thisObj;
	var e = !e ? window.event : e;
	var result = true;
	if(e.target.name != 'ok'){result = false}
	thisObj.opened = false;
	thisObj._notifyResultListeners(result);
	thisObj._container.css('display','none');
	thisObj._container.empty();
	},
	*/

	doHide: function()
	{
		this.opened = false;
		this._container.css('display', 'none');
		this._container.empty();
	},

	hide: function(e, skipListeners)
	{
		var e = !e ? window.event : e;
		var thisObj = (e.type != undefined) ? this.thisObj : e;
		var result = true;
		try
		{
			if (e.target.name != 'ok') { result = false }
		} catch (ex) { }

		if (skipListeners !== true)
		{
			var cancel = false;
			var myEvtObj = { stop: function() { cancel = true; }, self: thisObj }
			thisObj._notifyResultListeners(result, myEvtObj);
			delete myEvtObj;
			if (cancel)
			{
				delete cancel;
				return;
			}
			delete cancel;
		}

		thisObj.doHide();
	},

	isOpened: function(b)
	{
		return this.opened;
	},

	insert: function(node)
	{
		var c = $(".content", this._container);
		if (node && node.jquery) c.prepend(node);
		c.addClass("black");
		var g = this._generateContent;
		this._generateContent = function() { };
		$(".header", this._container).css("width", "600px");
		this.opened = false;
		this.show(this);
		this._generateContent = g;
	},

	_generateContent: function(extraString)
	{
		this._container.append('<div class="header">' + this.header + '</div>');
		this._container.append('<div class="topLeft"></div><div class="topRight"></div><div class="bottomRight"></div><div class="bottomLeft"></div><div class="contentLeft"></div><div class="contentRight"></div><div class="contentBottom"></div><div class="content"><!--[if lte IE 6.5]><iframe class="selectHider"></iframe><![endif]--></div>');
		var content = $('.content', this._container);

		var messageText = extraString ? this.msg.replace(/%extraString%/g, extraString) : this.msg
		content.append('<div style="padding:5px">' + messageText + '</div>');

		content.append(this._generateButtons());
		content.css("width", "600px");

		var buttons = $('input[type=button], input[type=submit], input[type=image]', this._container)
		buttons.click(this.hide);
		for (var i = 0; i < buttons.length; i++)
		{
			buttons[i].thisObj = this;
		}
	},

	_generateButtons: function()
	{
		var button = '<div class="doSend"><div class="left"><div class="right"><input type="button" name="ok" value="' + this.buttonText['ok'] + '" /></div></div></div>';
		if (this.mode != 'alert')
		{
			button += '<div class="doSend"><div class="left"><div class="right"><input type="button" name="cancel" value="' + this.buttonText['cancel'] + '" /></div></div></div>';
		}
		if (this.mode == 'stateless') { button = ''; }
		button += '<div class="clear"></div>';
		return button;
	},
	/*
	_notifyResultListeners : function(b){
	for(var i = 0;i < this.resultListeners.length;i++){
	this.resultListeners[i].popupNotify(b);
	}
	}*/
	_notifyResultListeners: function(b, o)
	{
		for (var i = 0; i < this.resultListeners.length; i++)
		{
			this.resultListeners[i].popupNotify(b, o);
		}
	}
}

/* END  ALERT/CONFIRM POPUPS*/



/* SUBDOMAIN AUTHENTICATION */
LoginAgent = function(){
	var buttons = $('.loginButton').parents('form');
	buttons.submit(this.doAuth);
	try{
		var logout = $('#exitTarget');
		logout.click(this.doAuth);
		logout[0].thisObj = this;
	}catch(e){}
	for(var i = 0;i < buttons.length;i++){
		buttons[i].thisObj = this;
		}
	}
		
LoginAgent.prototype = {

	targetForm : null,
		
	doAuth : function(e){
		var e = !e ? window.event : e;
		var thisObj = this.thisObj;
		//thisObj.targetForm = $('#'+e.target.id).parents('form');
		thisObj.targetForm = $(this);
		var sendForm = function() {
			$(thisObj.targetForm).submit();
		};
		var authDataObj = {'Login': $("input[name*='Login']", thisObj.targetForm).attr('value') || false, 'Password': $("input[name*='Password']", thisObj.targetForm).attr('value') || false, 'protocol' : document.location.protocol };
		var authData = '';
		    authData = "{'Login': '"+$("input[name*='Login']", thisObj.targetForm).attr('value')+"','Password': '"+$("input[name*='Password']", thisObj.targetForm).attr('value')+"', 'protocol' : '"+document.location.protocol+"'}";

		var xdomainUrl = 'http://www.rgs.ru/xml/xdomain.wbp';

		if(window.location.host.indexOf('.wbnet')>0) xdomainUrl = 'http://www.rgs.wbnet/xml/xdomain.wbp';
		if(window.location.host.indexOf('.wbnet.actis.ru')>0) xdomainUrl = 'http://www.rgs.wbnet.actis.ru/xml/xdomain.wbp';
		if (window.location.host == 'rgs.local:8080') xdomainUrl = 'http://rgs.local:8080/xml/xdomain.wbp';
		if (window.location.host.indexOf('rgs-site.moscow.epam.com')>=0) xdomainUrl = 'http://rgs-site.moscow.epam.com/xml/xdomain.wbp';

		window.frames[0].name = authData;

		var xdomainUrl = 'http://www.rgs.ru/xml/xdomain.wbp';

		if(window.location.host.indexOf('.wbnet')>0)
			xdomainUrl = 'http://www.rgs.wbnet/xml/xdomain.wbp';

		if(window.location.host.indexOf('.wbnet.actis.ru')>0)
			xdomainUrl = 'http://www.rgs.wbnet.actis.ru/xml/xdomain.wbp';

		// This is hack, sorry.
		if (window.location.host == 'rgs.local:8080')
		{
			xdomainUrl = 'http://rgs.local:8080/xml/xdomain.wbp';
		};

		if (window.location.host.indexOf('rgs-site.moscow.epam.com')>=0)
		{
			xdomainUrl = 'http://rgs-site.moscow.epam.com/xml/xdomain.wbp';
		};

		//window.frames[0].location = xdomainUrl;
		//window.frames[0].location.href = xdomainUrl;
		window.frames[0].location.replace(xdomainUrl);
		return false;
		/*
		try {
			window.frames[0].location.href = xdomainUrl;
		} catch(er) {

		}*/
	},
			
	subDomainAuthFinished : function(){
		$(this.targetForm).unbind();
		$(this.targetForm).submit();
	}
}
/* END SUBDOMAIN AUTHENTICATION */

/* AJAX FORM SENDER */
FormSender = function(formId, actionButton, url, feedbackSentAlert, errorsAlert){
		this.dataFields = $(formId+' input, '+formId+' select, '+formId+' textarea');
		this.container = $(formId)[0];
		this.url = url;
		var action = $(actionButton);
		action.click(this.sendForm);
		action[0].thisObj = this;
		this.feedbackSent = feedbackSentAlert;
		this.errorsAlert = errorsAlert;
	}
	
	FormSender.prototype = {
		sendForm : function(){
			var thisObj = this.thisObj;
			if (thisObj.container.formNode && thisObj.container.formNode.validate) {
				if (!thisObj.container.formNode.onsubmit()) return;
			}
			var dataArray = new Object();
			for(var i = 0;i < thisObj.dataFields.length;i++){
				dataArray[thisObj.dataFields[i].name] = thisObj.dataFields[i].value;
			}
			var response = $.ajax({
				type: "POST",
				url: thisObj.url,
				async: false,
				beforeSend: function(xhr) {
					if($.browser.mozilla === false){
						xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml")
//						xhr.setRequestHeader("Content-type","text/html; charset=utf-8");						
						xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");						

					}
				},
				data: dataArray
			});
			var hasErrors = response.responseXML.getElementsByTagName('success').length ? false : true;
			thisObj.confirm(hasErrors)
		},
		
		confirm : function(hasErrors){
			if(hasErrors){
				this.errorsAlert.show(this.errorsAlert);
			}else{
				this.feedbackSent.show(this.feedbackSent);
			}
		}
	}
/* END AJAX FORM SENDER */

/* REQUEST TO CALCULATOR CHOOSER PAGES */
CalcLocator = function(formSelector){
	var dublicate = this;
	this.data = $(formSelector + ' input');
	this.dataJSON = {};
	this.url = '/XML/calcLocator.wbp';
	/*
	var button = $(formSelector + " input[type='submit']");
	button[0].thisObj = this;
	button.click(this.sendRequest);
	button[0].onclick = this.sendRequest;
	*/
	var form = $(formSelector);
	form[0].thisObj = this;
	form.submit(function(evt) {
		dublicate.sendRequest.call(form[0]);
		try {
			evt.preventDefault();
			evt.stopImmediatePropagation();
		} catch (er) {};
	});
	/*
	form[0].onsubmit = function() {
		dublicate.sendRequest.call(form[0]);
		return true;
	};
	*/
}

CalcLocator.notification = null;

CalcLocator.prototype = {
	sendRequest : function(){
		var thisObj = this.thisObj;
		thisObj._populateForm();
		$(this).ajaxStart(function(){
   			$('#popup').empty();
   			CalcLocator.notification = new PopUp('', 'stateless','<p>Ваш запрос обрабатывается</p>','Обработка запроса')
			CalcLocator.notification.show(CalcLocator.notification);
 		});
 		$.get(thisObj.url, thisObj.dataJSON,
 			function(data){
 				CalcLocator.notification.hide(CalcLocator.notification);
 				var data = eval("("+data+")");
 				if(data['Status'] == 'Successful'){
 					window.location.replace(data['url']);
 				}else{
 					$('#popup').empty();
 					error = new PopUp('', 'alert', '<p>Расчет не найден. Проверьте пожалуйста корректность введенного номера расчета.</p>', 'Обработка запроса')
					error.show(error);
 				}
 			}
 		)
	},
	
	_populateForm : function(){
		for(var i = 0;i < this.data.length;i++){
			this.dataJSON[this.data[i].name] = this.data[i].value;
		}
	}
}
/* END	 REQUEST TO CALCULATOR CHOOSER PAGES */


/* CLONING GROUP OF FIELDS */

var CloneableNameRegex = /(?=.*)\d+(?=.*?)/;

Cloneable = function(patternID, actionButton, reinit, counterField, maxClonesNumber, afterClone)
{
	var pattern = $(patternID);

	this.reinit = reinit;
	this.maxClonesNumber = maxClonesNumber + 1; //сейчас в калькуляторах задается именно число возможных клонов, исключая первый.
	this.startIndex = 1
	this.counter = $(counterField);
	this.actionButton = $(actionButton);
	this.actionButton.click(this.append);
	if (typeof afterClone == 'function'){
		this.actionButton.click(afterClone);	
	};
	this.actionButton[0].thisObj = this;
	this.actionContainer = null;
	this.clones = [] ;
	
	var initialClones = pattern.parent().children ("DIV.cloneable");
	if (initialClones.length == 0)
	{
		initialClones.push(pattern);
	}
	
	for (var i = 0; i < initialClones.length; ++i)
	{
		this.clones.push($(initialClones[i]));
		this.clones[i].attr("cloneIndex", i);

		// reinit only this clone
		for (var j = 0; j < this.reinit.length; ++j)
		{
			if (this.reinit[j].initializeClone)
			{
				this.reinit[j].initializeClone(this.clones[i]);
			}
		}

	}

	this._syncClonesCount();
}

Cloneable.prototype =
{
	_setActionContainer: function(container) {
		this.actionContainer = container;
		this._syncClonesCount();
	},
	_replaceIndex: function(text, index)
	{
		return text != null ? text.replace(CloneableNameRegex, index + this.startIndex) : null;
	},

	// Инициализация клона - простановка ID и индекса в заголовках.
	_initializeClone: function(clone, index, reset)
	{
		var prevCloneIndex = clone.attr("cloneIndex");

		if (prevCloneIndex != index)
		{
			clone.removeAttr('id');
			clone.attr("cloneIndex", index);

			var inputs = $('input, select, textarea,.fields div', clone);
			for (var i = 0; i < inputs.length; i++)
			{
				try
				{
					if (inputs[i].id)
					{
						inputs[i].id = this._replaceIndex(inputs[i].id, index);
					}

					inputs[i].name = this._replaceIndex(inputs[i].name, index);
					
					var tagName = inputs[i].tagName.toUpperCase();
					
					if ((tagName == "INPUT" || tagName == "SELECT" || tagName == "TEXTAREA") && reset) 
					{
						var isCheckBox = false;
						if (tagName == "INPUT" 
								&& (inputs[i].className.toUpperCase() == "CHECKBOX" 
									|| inputs[i].type.toUpperCase() == "CHECKBOX"))
						{
							$(inputs[i]).removeAttr("checked");
						}
						else
						{
							$(inputs[i]).val("");
						}
					}
				}
				catch (e) { }

			}

			var labels = $('label', clone);
			for (var i = 0; i < labels.length; i++)
			{
				try
				{
					var label = $(labels[i]);
					label.attr("for", this._replaceIndex(label.attr("for"), index));
				} catch (e) { }
				// var numberPosition = $(labels [i]).text ().indexOf ("1") ;
				// $(labels [i]).text ($(labels [i]).text ().substring (0, numberPosition) + this.cloneNumber + $(labels [i]).text ().substring (numberPosition + 1, $(labels [i]).text ().length)) ;
			}

			// заменяем число в заголовке:
			var titles = $(".blocktitle", clone);
			for (var i = 0; i < titles.length; ++i)
			{
				var title = $(titles[i]);
				title.html(this._replaceIndex(title.html(), index));
			}

			// reinit only this clone
			for (var i = 0; i < this.reinit.length; ++i)
			{
				if (this.reinit[i].initializeClone)
				{
					this.reinit[i].initializeClone(clone);
				}
			}
		}
	},

	_clone: function()
	{
		if (this.clones.length < this.maxClonesNumber)
		{
			var newClone;
			if (this.clones.length > 0)
			{
				newClone = this._internalClone(this.clones[0]);
			}
			else
			{
				newClone = this.backup;
			}
			
			newClone.hide();

			if (this.clones.length > 0)
			{
				this.clones.push(newClone.insertAfter(this.clones[this.clones.length - 1]));
			}
			else
			{
				if (this.backupPrev != null)
				{
					this.clones.push(newClone.insertAfter(this.backupPrev));
				}
				else
				{
					this.clones.push(newClone.appendTo(this.backupParent));
				}
			}

			this._initializeClone(newClone, this.clones.length - 1, true);
			this._internalInit(newClone);
			this.backup = null;

			newClone.show();
			
			this._reinit();
			this._syncClonesCount();
		}
	},

	_internalClone: function(elt)
	{
		// prepare element for cloning
		for (var i = 0; i < this.reinit.length; ++i)
		{
			if (this.reinit[i].OnBeforeCloning)
			{
				this.reinit[i].OnBeforeCloning(elt);
			}
		}

		var clone = elt.clone(true);

		// restore element after cloning
		for (var i = 0; i < this.reinit.length; ++i)
		{
			if (this.reinit[i].OnAfterCloning)
			{
				this.reinit[i].OnAfterCloning(elt);
			}
		}
		
		return clone;
	},

	_internalInit: function(elt)
	{
		for (var i = 0; i < this.reinit.length; ++i)
		{
			if (this.reinit[i].OnInit)
			{
				this.reinit[i].OnInit(elt);
			}
		}
	},
	_backup: function()
	{
		this.backup = this._internalClone(this.clones[0]);

		var prev = this.clones[0].prev();
		if (prev.length > 0)
		{
			this.backupPrev = this.clones[0].prev();
			this.backupParent = null;
		}
		else
		{
			this.backupPrev = null;
			this.backupParent = this.clones[0].parent();
		}
	},

	_syncClonesCount: function()
	{
		this.counter.val(this.clones.length);
		if (this.clones.length == 1)
		{
			this._backup();
		}
		if (this.actionContainer != null) {
			if (this.clones.length == this.maxClonesNumber) {
				$(this.actionContainer).hide();
			}
			else {
				$(this.actionContainer).show();
			}
		}
	},

	_reinit: function()
	{
		for (var i = 0; i < this.reinit.length; i++)
		{
			this.reinit[i].init(this)
		}
	},

	append: function()
	{
		var thisObj = this.thisObj;
		thisObj._clone();
	},

	empty: function(startIndex)
	{
		if (startIndex == null)
			startIndex = 0;

		if (this.clones.length > 0)
		{
			this._backup();

			for (var i = startIndex; i < this.clones.length; ++i)
			{
				this.clones[i].remove();
			}

			this.clones.splice(startIndex, this.clones.length - startIndex);
			this._syncClonesCount();
		}
	},

	onRemove: function()
	{
		var newClones = [];

		for (var i = 0; i < this.clones.length; ++i)
		{
			var clone = this.clones[i];
			if (clone != null)
			{
				if (clone.children().length == 0)
				{
					clone.remove();
				}
				else
				{
					this._initializeClone(clone, newClones.length, false);
					newClones.push(clone);
				}
			}
		}

		this.clones = newClones;
		this._syncClonesCount();
	}
}

/* END CLONING GROUP OF FIELDS */
/* COLLAPSING AND DELETING GROUP OF FIELDS*/
Closeable = function(confirm) {
	this.confirm = confirm;
	this.confirm.addResultListeners(this);
	this.callback = new Array();
	this.init();
}

Closeable.prototype = {

	init: function() {
		this.closeable = $('.closeable');
		for (var i = 0; i < this.closeable.length; i++) {
			var minmax = $('.minmax', this.closeable[i]);
			minmax.click(this.toggle);
			minmax[0].thisObj = this;
			var remove = $('.delete', this.closeable[i]);
			remove.click(this.remove);
			remove[0].thisObj = this;
		}
	},

	toggle: function() {
		var fields = $('.fields', $(this).parents('fieldset'));
		if (fields.css('display') != 'none') {
			this.thisObj.hide(fields, this);
		} else {
			this.thisObj.show(fields, this);
		}
	},

	hide: function(el, button) {
		$(button).css('background', ('url(/media/system/imgs/maximize.gif)'))
		$('.bottomLeft, .bottomRight', $(button).parent()).css('display', 'block')
		el.css('display', 'none');
	},

	show: function(el, button) {
		$(button).css('background', ('url(/media/system/imgs/minimize.gif)'));
		$('.bottomLeft, .bottomRight', $(button).parent()).css('display', 'none')
		el.css('display', 'block');
	},

	remove: function(e) {
		var e = !e ? window.event : e;
		this.thisObj.target = e.target;
		this.thisObj.confirm.show(this.thisObj.confirm);
	},

	empty: function(target) {
		$(target).parents('fieldset').parent().empty();
		this.doCallback();
	},

	popupNotify: function(b) {
		if (b) {
			this.empty(this.target);
		}
	},

	doCallback: function() {
		for (var i = 0; i < this.callback.length; i++) {
			this.callback[i].onRemove();
		}
	},

	setCallback: function(object) {
		this.callback.push(object)
	}
}
/* END COLLAPSING AND DELETING GROUP OF FIELDS*/




$.fn.faq = function(obj) {
	this.each( function() { 
		$("dd", this).css("display", "none");
		$("dt", this).click( toggle );
	} );
	
	function toggle() {
		var node = this;
		var nodes = node.parentNode.getElementsByTagName("dt");
		for (var i=0, l=nodes.length; i<l; ++i) {
			if (nodes[i]==node) {
				open(nodes[i]);
			} else {
				close(nodes[i]);
			}
		}
		/*var node = this, d;
		$(this).toggleClass( "open" );
		while( (node=node.nextSibling) && (node.tagName || "").toLowerCase()!="dt" ) {
			if (node.nodeType!=1) continue;
			d = node.style.display;
			node.style.display = d=="none" ? "block" : "none";
		}
		*/
		var a=1;
	}
	
	function close(dt) {
		var node = dt;
		while( (node=node.nextSibling) && (node.tagName || "").toLowerCase()!="dt" ) {
			if (node.nodeType!=1) continue;
			node.style.display = "none";
		}
		$(dt).removeClass("open");
	}
	
	function open(dt) {
		var node = dt;
		while( (node=node.nextSibling) && (node.tagName || "").toLowerCase()!="dt" ) {
			if (node.nodeType!=1) continue;
			node.style.display = "block";
		}
		$(dt).addClass("open");
	}
};

/*
*	Initialization Statements for all pages. Custom Init statements must be added to actual page
*/

InitFeedbackForm = function(){
	$('#navContactType').change(function(){				
		(this.value == 'Телефон') ? $('#navEmailWrapper').css('display','none') : $('#navEmailWrapper').css('display','block');
		(this.value == 'E-mail') ? $('#navPhoneWrapper').css('display','none') : $('#navPhoneWrapper').css('display','block');
		(this.value == 'E-mail') ? $('#navFromTimeFld').parent().css('display','none') : $('#navFromTimeFld').parent().css('display','block');
		(this.value == 'E-mail') ? $('select[name=amountTime]').parent().css('display','none') : $('select[name=amountTime]').parent().css('display','block');
		}
	)
}

$(
	function(){
		loginAgent = new LoginAgent();
		new CalcLocator('#navigationCaseSearch');
		Menu.Menu();
		new InputTextToggler('#query');
		new InputTextToggler('#navLoginInp');
		new InputTextToggler('#navPasswdInp');
		new InputTextToggler('#navThemeFld');
		new InputTextToggler('#navNameFld');
		new InputTextToggler('#navPhoneNumberFld');
		new InputTextToggler('#navEmailFld');
		new InputTextToggler('#navNumLastCalc');
		new InputTextToggler('#navConsultantName');
		new InputTextToggler('#navConsultantEmail');
		//var office = new DependOptions('#navContactsOfficeRegion', '#navContactsOfficeCity', 'city');
		// office.setCallback(Utils.getNavigationCities);
		//office.setCallback(getRegionCitiesFullList);
		//var centers = new DependOptions('#navContactsCenterRegion', '#navContactsCenterCity', 'city');
		// centers.setCallback(Utils.getNavigationCities);
		//centers.setCallback(getRegionCitiesFullList);
		$("dl.faq").faq();

		InitFeedbackForm();

		/* Alert windows for feedback FormSender */
		//var fbs = new PopUp('', 'alert','<p>Ваше сообщение отправлено</p>','Статус отправки')
		fbs = new PopUp('', 'alert','<p>Ваше сообщение отправлено</p>','Статус отправки')
			fbs.setButtonText({'ok' : 'OK'});
			fbs.addResultListeners(Menu);
		var errorsAlert = new PopUp('', 'alert','<p>Произошла ошибка во время отправки сообщения</p>','Статус отправки')
			errorsAlert.setButtonText({'ok' : 'OK'});
		/* Send feedback form with FormSender()*/
		$("#navFeedbackForm")[0].formNode = $("#navFeedbackFormNode")[0];
		new FormSender('#navFeedbackForm','#navFeedbackButton','/xml/feedback.wbp', fbs, errorsAlert);
		validator_FeedbackForm.timer = window.setInterval(validator_FeedbackForm.waitValidatorJS, 100);
	}
);

$(function() {
	// overlay + ie6
	var overlay = document.getElementById("overlay");
	if (!overlay) return;
	var iframe = overlay.getElementsByTagName("iframe")[0];
	if (!iframe) return;
	iframe.contentWindow.document.write("1");
	iframe.contentWindow.document.body.onclick = function() { 
		var evt = {
			preventDefault: dummy,
			stopImmediatePropagation: dummy
		};
		window.parent.Menu.toggleMenu.call(window.parent.document.getElementById('overlay'), evt);
	};
	function dummy() { }
});


var validator_FeedbackForm = {};
validator_FeedbackForm.waitValidatorJS = function() {
	if (typeof(ValidatorParser)!="undefined") {
		window.clearInterval(validator_FeedbackForm.timer);
		validator_FeedbackForm.timer = null;
		delete validator_FeedbackForm.timer;
		validator_FeedbackForm.parser = new ValidatorParser("StaticForm", false, validator_FeedbackForm.json);
		document.getElementById(validator_FeedbackForm.json.form.id).validate = validator_FeedbackForm.parser;
		//document.getElementById("navFeedbackForm").validate = validator_FeedbackForm.parser;
	}
};
validator_FeedbackForm.fn = {
	phoneReq: function(contactType) {
		return contactType!="E-mail";
	},
	mailReq: function(contactType) {
		return contactType=="E-mail";
	},
	eraseDefaultValues: function() {
		var input = document.getElementById("navPhoneNumberFld");
		if (input.value == "Телефон") input.value = "";
		input.value = validator_FeedbackForm.fn.trim(input.value);
		var input = document.getElementById("navEmailFld");
		if (input.value == "E-mail") input.value = "";
		input.value = validator_FeedbackForm.fn.trim(input.value);
		var input = document.getElementById("navNameFld");
		if (input.value == "Имя") input.value = "";
		input.value = validator_FeedbackForm.fn.trim(input.value);
	},
	restoreDefaultValues: function() {
		var input = document.getElementById("navPhoneNumberFld");
		if (input.value == "") input.value = "Телефон";
		var input = document.getElementById("navEmailFld");
		if (input.value == "") input.value = "E-mail";
		var input = document.getElementById("navNameFld");
		if (input.value == "") input.value = "Имя";
		
	},
	trim: function(str) {
		return str.replace(/^\s*|\s*$/g, "");
	}
};
validator_FeedbackForm.json = {
	form: { id: "navFeedbackFormNode" },
	check: [
		{
			// убираем дефолтовые ("Телефон"/"E-mail") значения из соотв. полей
			type: "alert",
			lang: "rus",
			onOk: { "call": validator_FeedbackForm.fn.eraseDefaultValues, needSubmit: true },
			fields: [ { name: "contactType", title: "", type: "any", req: false } ]
		},
		{
			// проверка и возврат дефолтовых значений
			type: "inline",
			lang: "rus",
			onOk: { "call": validator_FeedbackForm.fn.restoreDefaultValues, needSubmit: true },
			onEr: { "call": validator_FeedbackForm.fn.restoreDefaultValues, needSubmit: false, "break": true },
			fields: [
				{ name: "contactType", title: "", type: "any", req: false, container: "inputWrapper", errorTarget: "error" },
				{ name: "theme", title: "Тема", type: "any", req: true, min: 5, container: "inputWrapper", errorTarget: "error" },
				{ name: "name", title: "Имя", type: "any", req: true, min: 1, container: "inputWrapper", errorTarget: "error"},
				{ 
					name: "phoneNumber", title: "Телефон", type: "phone", 
					req: {fn:validator_FeedbackForm.fn.phoneReq, args:[{name: "contactType",role: "value"}]}, 
					container: "inputWrapper", errorTarget: "error"
					//, min: 3, max: 16 // кол-во символов в городском номере, без кода, скобок, разделителей
				},
				{ 
					name: "email", title: "E-mail", type: "email", 
					req: {fn:validator_FeedbackForm.fn.mailReq, args:[{name: "contactType",role: "value"}]}, 
					container: "inputWrapper", errorTarget: "error"
				}
			]
		},
		{
			// проверка и возврат дефолтовых значений
			type: "inline",
			lang: "rus",
			onOk: { needSubmit: true },
			onEr: { needSubmit: false },
			fields: [
				{ 
					name: "phoneNumber", title: "Телефон", type: "any", max: 16,
					req: {fn:validator_FeedbackForm.fn.phoneReq, args:[{name: "contactType",role: "value"}]}, 
					container: "inputWrapper", errorTarget: "error"
				}
			]
		}
	]
};

function cookiesTranslator() {
	// получаем список кук
	// var h = window.location.host;
	// h = h.substr( h.indexOf(".") +1 );
	var cookies = {};
	for (var i=0, arr=(document.cookie +"").split(";"), l=arr.length, c, trim=/^\s*|\s*$/g; i<l; i++) {
		c = arr[i].split("=");
		cookies[c[0].replace(trim, "")] = c[1].replace(trim, "");
	}
	var needRefresh = false;
	for (var key in cookiesTranslator.pairs) {
		// key - наименование "общей" куки, в которой будет сохраняться зн-е нужной куки, видимой только в этом поддомене
		// например, sid
		var keyFor = cookiesTranslator.pairs[key];
		// keyFor - наименование нужной куки
		// например, token
		if (!cookies[key]) {
			// sid - кука со зн-ем первоначальной сессии, видна во всех поддменах
			// когда мы открываем сессию, нам надо создать эту куку
			// document.cookie = key +"="+ cookies[keyFor] +"; path=/; domain=."+ h;
			cookiesTranslator.setCookie(key, cookies[keyFor]);
		} else if (cookies[key] != cookies[keyFor]) {
			// если мы открыли сессию в другом поддомене, и общая кука с не совпадает с "локальной",
			// нам надо поменять идентификатор сессии и перезагрузить страницу
			document.cookie = keyFor +"="+ cookies[key] +"; path=/;";
			needRefresh = true;
		}
	}
	if (cookies.backAfterAuth) {
		//window.location.href = cookies.backAfterAuth;
		//cookiesTranslator.remCookie("backAfterAuth");
	} else if (needRefresh) {
		window.location.href += (window.location.href.indexOf("?") > -1 ? "&r=" : "?r=") + String(Math.random());
	}
};
cookiesTranslator.setCookie = function(name, value) {
	var h = window.location.host;
	h = h.substr( h.indexOf(".") +1 );
	document.cookie = name +"="+ value +"; path=/; domain=."+ h;
};
cookiesTranslator.remCookie = function(name) {
	var h = window.location.host;
	h = h.substr( h.indexOf(".") +1 );
	document.cookie = name +"=; path=/; domain=."+ h +";expires=Thu, 01-Jan-1970 00:00:01 GMT";
};
cookiesTranslator.pairs = {
	"sid": "ASP.NET_SessionId", 
	"token": "RgsToken"
};

// cookiesTranslator(); // дожидаться загрузки dom-дерева не надо

try { if (typeof(document.execCommand && !window.XMLHttpRequest)!="undefined") document.execCommand("BackgroundImageCache", false, true) }
catch(er) { }


StartDateAndDurationSync = function(durationInput, startDateInput)
{
	this.initialize(durationInput,startDateInput);	
	var thisObj = this;
	this.startDateInput.change(function() { thisObj.sync(); });
};

// Синхронизация возраста и даты рождения.
StartDateAndDurationSync.prototype.initialize = function(durationInput, startDateInput)
{
	this.durationInput = durationInput;
	this.startDateInput = startDateInput;
};

// Синхронизация возраста и даты рождения.
StartDateAndDurationSync.prototype.sync = function()
{
	var startDateValue = this.startDateInput.val();

	if (startDateValue != null)
	{
		var startDate = Date.parseExact(startDateValue, "d.M.yyyy");
		if (startDate != null)
		{
			var age = Date.today().DiffInYears(startDate);
			if (age >= 0)
			{
				this.durationInput.val(age);
			}
		}

		/*
		var regexp = /(\d{1,2}).(\d{1,2}).(\d{4})/;
		var match = startDateValue.match(regexp);

		if (match != null && match.length == 4)
		{
		var day = parseInt(match[1], 10);
		var month = parseInt(match[2], 10);
		var year = parseInt(match[3], 10);

			if (0 < day && day <= 31
		&& 0 < month && month <= 12)
		{
		month = month - 1;

				var now = new Date();

				var age = now.getFullYear() - year;
		if (now.getMonth() < month)
		{
		age--;
		}
		else if (now.getMonth() == month)
		{
		if (now.getDate() < day)
		{
		age--;
		}
		}

				if (age >= 0)
		{
		this.durationInput.val(age);
		}
		}
		}
		*/
	}
}

Date.prototype.DaysInMonth = function(Y, M)
{
	var date = new Date(Y, M, 1, 12);
	date.setDate(0);
	return date.getDate();
}

Date.prototype.DiffInYears = function(date)
{
	var y1 = this.getFullYear(), m1 = this.getMonth(), d1 = this.getDate();
	var y2 = date.getFullYear(), m2 = date.getMonth(), d2 = date.getDate();

	if (d1 < d2)
	{
		m1--;
	}

	var result = y1 - y2;
	
	if (m1 < m2)
	{
		result--;
	}
	
	return result;
}

Date.prototype.DiffInDays = function(date)
{
	var diff = this - date;
	return Math.round(diff / 1000 / 60 / 60 / 24);
}

InputMasks = function()
{
	$.mask.definitions = $.extend(
		{
			"3": "[0-3]",
			"1": "[0-1]"
		},
		$.mask.definitions);

	InputMasks.initialized = true;
	this.initializeMasks();
}

InputMasks.initialized = false;

InputMasks.prototype =
{
	init: function() { },

	initializeMasks: function(context)
	{
		if (InputMasks.initialized)
		{
			var dateInputs = $("input:text.dateInput", context);
			dateInputs.mask("39.19.9999");
		}
	},

	OnBeforeCloning: function(clone)
	{
		if (InputMasks.initialized)
		{
			$("input:text.dateInput", clone).unmask();
		}
	},

	OnAfterCloning: function(clone)
	{
		this.initializeMasks(clone);
	},

	initializeClone: function(clone)
	{
		if (InputMasks.initialized)
		{
			$("input:text.dateInput", clone).unmask();
		}
		this.initializeMasks(clone);
	}
}

$(function()
{
	if (window.DP_jQuery != null)
	{
		// Hack - Cut off datepicker autopositioning
		$.extend(window.DP_jQuery.datepicker, { _checkOffset: function(inst, offset, isFixed) { return offset } });
	}
});

InputMasks._GetDefaultOptions = function()
{
	return {
		changeMonth: true,
		changeYear: true,
		yearRange: "1929:2020",
		showOn: 'none'
	};
}

InputMasks._InitializeDatePicker = function(inputs, options)
{
	inputs.each(
		function()
		{
			var input = $(this);
			input.datepicker(options);

			var button = input.next("div.datepickerButton");
			button.bind("click.datepickerShow", function() { input.datepicker("show"); });
		}
	);
}

InputMasks.InitializeDatePicker = function(inputs, minDate, maxDate)
{
	var options = InputMasks._GetDefaultOptions();
	var extendedOptions =
	{
		minDate: minDate,
		maxDate: maxDate
	};
	
	var options = $.extend(options,	extendedOptions);

	InputMasks._InitializeDatePicker(inputs, options);
}

InputMasks.InitializeDatePickerForBirthday = function(inputs, minAge, maxAge)
{
	var options = InputMasks._GetDefaultOptions();
	var extendedOptions =
	{
		minDate: maxAge != null ? new Date().addYears(-maxAge) : null,
		maxDate: minAge != null ? new Date().addYears(-minAge) : null
	};
	
	var options = $.extend(options,	extendedOptions);
	InputMasks._InitializeDatePicker(inputs, options);
}

InputMasks.ClearDatePicker = function(inputs)
{
	inputs.each(
		function()
		{
			var input = $(this);
			input.datepicker("destroy");
	
			var button = input.next("div.datepickerButton");
			button.unbind("click.datepickerShow");
		}
	);
}

function ShowMessageAndRedirect(message, url)
{
	var messagePopup = new PopUp('', 'alert', message, 'Сообщение');
	messagePopup.modal = true;
	messagePopup.setButtonText({ 'ok': 'Да' });
	
	var listener = 
	{
		popupNotify : function(result, event)
		{
			if (result)
			{
				window.location.href = url;
			}
		}
	}
	messagePopup.addResultListeners(listener);
	
	messagePopup.show(messagePopup);
}

Math.roundNumber = function(number, decimalDigits)
{
	var multiple = Math.pow(10, decimalDigits);
	var result = Math.round(number * multiple) / multiple;
	return result;
}