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*/

/* BEGIN: jQuery вспомогательный метод для заполнения вып. списка */
$.fn.fill = function(arr, emptyText, optionCallback) {
	optionCallback = optionCallback || function(val) { return '<option>' + val + '</option>'; };
	var options = arr && emptyText != null ? '<option value="">' + emptyText + '</option>' : '';
	$.each(arr, function(key, val) {
		options += optionCallback(val, key);
	});
	this.html(options);
	if (arr.length === 1) {
		try { this.find('option[value!=""]').eq(0).attr('selected','selected'); } catch (e) { if (window.console) console.error(e); } // fix for ie6
	}
	return this.attr('disabled', arr.length < 1 && emptyText != null);
};
/* END: jQuery вспомогательный метод для заполнения вып. списка */

/*UTILS*/
Utils = {
	isHoliday: function(date, workingDaysInWeek){
		if (!date) return false;
		if (!workingDaysInWeek) workingDaysInWeek = 5;

		var workingdays = {			
			2012: {
				3: [11],
				4: [28],
				6: [9],
				12:[29]
			}
		};
		var holidays = {
			2011: { 12: [30]},
			2012: {
				1: [2,3,4,5,6,9],
				2: [23],
				3: [8,9],
				4: [30],
				5: [1,9],
				6: [11,12],
				11:[5],
				12:[31]
			}
		};
		var d = date.getDate(), m = date.getMonth() + 1, y = date.getFullYear();
		// Сб и Вс	
		if (date.getDay() == 0 || (workingDaysInWeek == 5 && date.getDay() == 6)) {
			// Рабочие дни в Сб или Вс
			if (workingdays[y] && workingdays[y][m] &&
				$.inArray(d, workingdays[y][m]) >= 0) return false;		
			return true;
		}

		// Праздничные дни
		if (holidays[y] && 
			holidays[y][m] &&
			$.inArray(d, holidays[y][m]) >= 0) return true;

		return false;
	},

	/*
	*	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}
	},

	clientDebugMode: false,
	
	debugDelegates:
	[
		function(obj) { console.log(obj); },
		function(obj) { console.debug(obj); },
		function(obj) { opera.postError(obj); }
	],
	
	debug : function(obj)
	{
		if (this.clientDebugMode 
					|| (typeof(globalDebugMode) != "undefined" && globalDebugMode)) {
			for (var i = 0; i < this.debugDelegates.length; ++i) {
				var succesful = false;
				try {
					this.debugDelegates[i](obj);
					succesful = true;
				} catch(e) { if (window.console) console.error(e); }
				
				if (succesful) break;
			}
		}
	},

	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;
	},

	lastIDcookies : {
		set : function(caseID){
			if(caseID != '') {
				document.cookie = "caseData="+encodeURI("{caseID : '"+caseID+"', date : '"+new Date().toString()+"'}")+"; expires=Thu, 1 Aug 2099 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 = {
	menuItems: null,
	animationSpeed: 0, 	// Скорость анимации меню
	openDelay: 0,		// Задержка отображения меню
	
	Menu: function()
	{	
		if (this.menuItems == null)
		{
			this.menuItems = $('#header li.menuItem');
			
			this.menuItems
				.bind('mouseleave blur', $.proxy(this.onHideMenu, this))
				.bind('mouseenter focus', $.proxy(this.onShowMenu, this));
				
			this.menuItems.find('ul.sub-menu')
				.bind('mouseleave blur', $.proxy(this.onHideMenu, this))
				.bind('mouseenter focus', $.proxy(this.onShowMenu, this));
			
			this.menuItems.children('a')
				.bind('mouseover', $.proxy(this.onShowMenu, this));				
		}
	},	
		
	onShowMenu: function(evt) {
		var menuItem = $(evt.target).closest('li.menuItem') || $(evt.target);
		var mainMenuItemCaption = $('.menuItem > a').not('.backlight');		
		if (menuItem.hasClass('active')) return false;
		
		var subMenu = menuItem.find('ul.sub-menu');
		
		menuItem.find('.backlight').show();
		if ( menuItem.find('.backlight').length > 0 ) {
			//mainMenuItemCaption.children().css({'opacity': '0.7', 'filter': 'alpha(opacity=70)'});
			//mainMenuItemCaption.children().fadeTo(0, 0.7);			
			mainMenuItemCaption.find('#active-button-life.active').hide();
			mainMenuItemCaption.find('#active-button-life.inactive').show();
			mainMenuItemCaption.siblings('h2').hide();
		}
		subMenu.show();
		//this.showWithAnimation(subMenu); // Плавное отобажение меню
		menuItem.addClass('active');
		return true;
	},
	
	onHideMenu: function(evt){
		var menuItem = $(evt.target).closest('li.menuItem') || $(evt.target);
		var mainMenuItemCaption = $('.menuItem > a').not('.backlight');
		if (!menuItem.hasClass('active')) return false;
		
		var subMenu = menuItem.find('ul.sub-menu');		
		menuItem.find('.backlight').hide();
		//mainMenuItemCaption.children().css({'opacity': '1', 'filter': 'alpha(opacity=100)'});
		//mainMenuItemCaption.children().fadeTo(0, 1);		
		mainMenuItemCaption.find('#active-button-life.active').show();	
		mainMenuItemCaption.find('#active-button-life.inactive').hide();
		subMenu.hide();	
		//this.hideWithAnimation(subMenu); // Плавное скрытие меню
		menuItem.removeClass('active');	
		//fbs.hide(fbs, true);				
		return true;	
	},	
	
	showWithAnimation: function(element){
		clearTimeout(this.subMenuTimer);
		
		this.subMenuTimer = setTimeout($.proxy(function(){
			if ($.browser.msie && $.browser.version == '6.0')
				$(element).show();
			else
				$(element).animate({ 'queue': false, 'opacity': 'show' }, this.animationSpeed);		
		}, this), this.openDelay);
	},
	
	hideWithAnimation: function(element, isOverlay) {
		clearTimeout(this.subMenuTimer);
		
		if ($.browser.msie && $.browser.version == '6.0') {
			$(element).hide();
		} else
			$(element).animate({ 'queue': false, 'opacity': 'hide' }, this.animationSpeed);
	},
	
	popupNotify: function(b) {
		this.toggleMenu();
	},

	ShowMenu: function(menuItemClass) {
		var menuItem = $('#navigation li.menuItem.' + menuItemClass);
		menuItem.focus();
	}	
}
/* 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.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 == '') ? 'alert' : mode;
	this.msg = msg;
	this.header = header;
	this.buttonText = (this.mode === 'alert') 
		? { ok: 'ОК' }
		: (this.mode === '3buttons')
		? { yes: 'Да', no: 'Нет', cancel: 'Отмена' }
		: (this.mode === 'stateless')
		? { }
		: { ok: 'OK', cancel: 'Отмена'};
	this.opened = false;
	this.resultListeners = new Array();
	
	if (target) {
		var $target = $(target);
		if ($target.length > 0) {
			$target[0].thisObj = this;
			$target.click(this.show);
		}
	}
	this.borderless = false;
}

PopUp.prototype = {
	setMessage: function(msg)
	{
		this.msg = msg
	},

	setContainer: function(selector) {
		this._container.after("<div id=" + selector + " />")
		this._container = $('#' + selector);
	},

	setButtonText: function(textArray) {
		this.buttonText = textArray;
	},

	addResultListeners: function(obj) {
		this.resultListeners.push(obj);
	},

	setPopupPosition: function(popup) {
		if (!popup[0].positioned || popup[0].positioned <= 2) {
		
			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 css = {
					left: '50%',
					marginLeft: - popup.width() / 2 + 'px',
					top: (clientHeight > popup.height()) ? scrollTop + (clientHeight - popup.height()) / 2 + 'px' : scrollTop + 10 + 'px'
				}
			if (parseInt(css.top) < scrollTop) css.top = scrollTop + 10 + 'px';
			popup.css(css);
			
			if (!popup[0].positioned) {
				popup[0].positioned = 1;
			} else {
				popup[0].positioned++;
			}
		}
	},

	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));
			if (this.borderless) {
	 			$('.whiteHeader', this._container).width(content.width() - 1);
	 			$('.whiteHeader', this._container).height(0).css('left','1px');
			} else {
				$('.header', this._container).width(content.width() - 2);
				$('.header', this._container).height(23).css('left','1px');
			}

		}
		thisObj.opened = true;
	},

	doHide: function() {
		this.opened = false;
		this._container.css('display', 'none');
		this._container.empty();
		this._container[0].positioned = false;
	},

	hide: function(e, skipListeners) {
		var e = !e ? window.event : e;
		var thisObj = (e.type != undefined) ? this.thisObj : e;
		var result = null;
		if (e.target && e.target.name) {
			if (e.target.name === 'ok') {
				result = true;
			} else if (e.target.name === 'cancel') {
				result = false;
			} else {
				result = e.target.name;
			}
		}

		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() { };
		if (this.borderless) {
			$(".whiteHeader", this._container).css("width", "600px");
		} else {
			$(".header", this._container).css("width", "600px");
		}
		this.opened = false;
		this.show(this);
		this._generateContent = g;
	},

	_generateContent: function(extraString) {
		if (this.borderless) {
			this._container.append('<div class="whiteHeader"></div>');
			this._container.append('<div class="whiteTopLeft"></div><div class="whitetopRight"></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>');
		} else {
			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 = '';
		for (var i in this.buttonText) {
			button += '<div class="doSend"><div class="left"><div class="right"><input type="button" name="' + i + '" value="' + this.buttonText[i] + '" /></div></div></div>';
		}
		button += '<div class="clear"></div>';
		return button;
	},

	_notifyResultListeners: function(b, o) {
		for (var i = 0; i < this.resultListeners.length; i++)
		{
			if (this.resultListeners[i].popupNotify){
				this.resultListeners[i].popupNotify(b, o); // it's a bug!!!!!!!! there is no popupNotify function in PopUp!!!
			} else {
				this.resultListeners[i](b, o);
			}
		}
	},

	fixPopupBordersHeight: function () {
		var newCont = $('#popup .content');
		var contHeight = newCont.height() + parseInt(newCont.css('padding-top')) + parseInt(newCont.css('padding-bottom'));
		$('#popup .contentLeft,#popup .contentRight').height(contHeight);
	}
}
/* 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);
		if (logout.length > 0) { logout[0].thisObj = this; }
	} catch(e) { if (window.console) console.error(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 = $(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 = 'https://www.rgs.ru/xml/xdomain.wbp';

		if (window.location.host.indexOf('.wbnet')>0) xdomainUrl = 'https://www.rgs.wbnet/xml/xdomain.wbp';
		if (window.location.host.indexOf('.wbnet.actis.ru')>0) xdomainUrl = 'https://www.rgs.wbnet.actis.ru/xml/xdomain.wbp';
		if (window.location.host.indexOf('local')>0) xdomainUrl = 'http://rgs.local:8080/xml/xdomain.wbp';
		if (window.location.host.indexOf('rgssite-test.epam.com')>=0) xdomainUrl = 'https://rgssite-test.epam.com/xml/xdomain.wbp';
		if (window.location.host.indexOf('rgssite-stg.epam.com')>=0) xdomainUrl = 'https://rgssite-stg.epam.com/xml/xdomain.wbp';
		if (window.location.host.indexOf('preprod.rgs.ru')>=0) xdomainUrl = 'https://preprod.rgs.ru/xml/xdomain.wbp';

		window.frames[0].name = authData;
		
		window.frames[0].location.replace(xdomainUrl);
		return false;
	},
			
	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,
				data: dataArray,
				contentType: 'application/x-www-form-urlencoded;charset=utf-8'
			});
			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 = { GetSavedQuotationCase: true };
	this.url = '/XML/calcLocator.wbp';
	var form = $(formSelector).get(0);
	
	form.thisObj = this;
	var submitHandler = function(evt)
	{
		dublicate.sendRequest.call(form);
		try
		{
			evt.preventDefault();
			evt.stopImmediatePropagation();
		} catch (e) { if (window.console) console.error(e); };
	};
	
	var validatorParserData = {
		form: { id: form.id },
		check: [
			{
				type: "inline",
				lang: "rus",
				onOk: { needSubmit: false, call: submitHandler },
				onEr: { needSubmit: false },
				fields: [
					{
						name: "CaseID", type: "int-chars", req: true, container: "inputWrapper", errorTarget: "error", autoupdate: true,
						min: 7, max: 7
					}]
			}]
	};

	var parser = new ValidatorParser("StaticForm", false, validatorParserData);
}

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);

			if (reset) {
				$('.error-input', clone).removeClass("error-input");
			}
			
			var inputs = $('input, select, span.error-label, 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" || tagName == "SPAN") && reset) {
						var isCheckBox = false;
						if (tagName == "INPUT" 
								&& (inputs[i].className.toUpperCase() == "CHECKBOX" 
									|| inputs[i].type.toUpperCase() == "CHECKBOX")) {
							$(inputs[i]).removeAttr("checked");
						} else if(tagName == "SPAN") {
							$(inputs[i]).empty();
						} else {
							$(inputs[i]).val("");
						}
					}
				}
				catch (e) { if (window.console) console.error(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) { if (window.console) console.error(e); }
			}

			// заменяем число в заголовке:
			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).hide();
		$("dt", this).click( toggle );
	});
	
	function toggle() {
		var $dt = $(this);
		var isOpen = $dt.hasClass("open");
		$dt.toggleClass("open", !isOpen).next("dd").toggle(!isOpen);
	}
};

/*
*	Initialization Statements for all pages. Custom Init statements must be added to actual page
*/

$(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();

		/* 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()*/
});

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) != "undefined" && !window.XMLHttpRequest) 
		document.execCommand("BackgroundImageCache", false, true) 
} catch(e) { if (window.console) console.error(e); }


StartDateAndDurationSync = function(durationInput, startDateInput)
{
	this.initialize(durationInput,startDateInput);	
	var thisObj = this;
	this.startDateInput.change(function() { thisObj.sync(); });
	this.startDateInput.blur(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);
			}
		}
	}
}

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);
	}
}

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, onSelect, disableHolidays)
{
	var options = InputMasks._GetDefaultOptions();
	var extendedOptions =
	{
		minDate: minDate,
		maxDate: maxDate,
		onSelect: onSelect
	};
	
	if (disableHolidays) extendedOptions.beforeShowDay = function(date) { return [!Utils.isHoliday(date)]; };

	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);
}

// Return new array with duplicate values removed
Array.prototype.unique = function()
{
	var a = [];
	var l = this.length;
	for (var i = 0; i < l; i++)
	{
		for (var j = i + 1; j < l; j++)
		{
			// If this[i] is found later in the array
			if (this[i] === this[j])
			{
				j = ++i;
			}
		}
		a.push(this[i]);
	}
	return a;
};

Math.roundNumber = function(number, decimalDigits)
{
	var multiple = Math.pow(10, decimalDigits);
	var result = Math.round(number * multiple) / multiple;
	return result;
}

	// ************************************************************
	// Заполнение выпадающего списка.
	// ************************************************************
	bindSelectBox = function(/*String*/ container, /*Array*/values, /*Function*/getIsDefaultValue, /*Function*/getValue, /*Function*/getText) {
		var element = $(container);
		var html =  "";
		element.empty();
		if ($.isArray(values)) {
			$.each(values, function(index, item) {
				if (item) {
					var id = getValue(item);
					html += "<option value=\"" + id + "\"";
					
					if (getIsDefaultValue(item)) {
						html += " selected=\"true\"";
					}
					
					html += ">";
					html += getText(item);
					html += "</option>";
				}
			});
		}
		element.html(html);
		$.autosuggest.changeOptions(element);
	}
	
	// ************************************************************
	// Функции для обработки асинхронных запросов
	// ************************************************************
	var jsonCache = {};

	getJson = function(/*String*/ url, /*Function*/ successCallback) {
		
		if (jsonCache[url])
		{
			successCallback(jsonCache[url]);
		}
		else {
			$.getJSON(url,
				null,
				function(jsonResult) {
					jsonCache[url] = jsonResult;
					if ($.isFunction(successCallback)) {
						successCallback(jsonResult);
					}
				}
			);
		}
	};


$.fn.disableBtn = function() {
	return this.add(this.parents('.left,.right')).addClass('disabled').end().attr('disabled', 'disabled');
};

$.fn.enableBtn = function() {
	return this.add(this.parents('.left,.right')).removeClass('disabled').end().removeAttr('disabled');
};

$.fn.hrefQueryString = function(s) {
	if (typeof s != 'string') {
		s = $.param(s);
	}
	return this.attr('href', this.attr('href').split('?')[0] + '?' + s);
};

jQuery.extend({
	loadedScripts: [],
				
	getStaticScript: function(url, asyncParam) {
		var asyncParam = (typeof(asyncParam) != 'undefined') ? asyncParam : true;

		if ($.inArray(url, $.loadedScripts) != -1) {
			return $.Deferred ? $.Deferred().resolve() : true;
		} else {
			return $.ajax({ url: url, dataType: 'script', cache: true, async: asyncParam, success: function() { $.loadedScripts.push(url); } });
		}
	}
});

/* \/ Отправка формы из меню контакты */
function SendContactForm(form, formId, callbackSuccess, callbackError) {
	try {
		if ($('textarea.textarHelper').val() == $('textarea.textarHelper').attr('default')) $('textarea.textarHelper').val('');
	
		// Отправка формы
		var dataArray = {};		
		var dataFields = $(form).find('input, select, textarea');
		for(var i = 0; i < dataFields.length;i++){
			dataArray[dataFields[i].name] = dataFields[i].value;
		}
		dataArray['form'] = formId;
		$.ajax({
			type: "POST",
			url: '/xml/feedback.wbp',
			data: dataArray,
			success: callbackSuccess,
			error: callbackError,
			contentType: 'application/x-www-form-urlencoded;charset=utf-8'
		});
	} catch(e) {
		if(window.console) console.error(e);
	}		
}
/* /\ Отправка формы из меню контакты */
