// JavaScript Document
function log(data) { if (window.console) console.log(data); }
function inherits(Child, Parent) {
	var F = function() { };
	F.prototype = Parent.prototype;
	Child.prototype = new F();
	Child.prototype.constructor = Child;
	Child.parent = Parent.prototype;
}

var sUserAgent = navigator.userAgent;
if (/MSIE (\d+\.\d+);/.test(sUserAgent)) var IEVersion= new Number(RegExp.$1);
if (/Gecko\//.test(sUserAgent)) { var TempArr = sUserAgent.match(/rv:(\d+)\.(\d+)(?:\.(\d+))?/); var GeckoVersion = new Number(TempArr[1] + "." + TempArr.slice(2).join('')); }
if (/AppleWebKit\/(\d+\.\d+?)/.test(sUserAgent)) var WebKitVersion= new Number(RegExp.$1);
if (/Opera[\/\s](\d+\.\d+)/.test(sUserAgent)) var OperaVersion= new Number(RegExp.$1);
if (/Chrome[\/\s](\d+\.\d+)/.test(sUserAgent))var ChromeVersion= new Number(RegExp.$1);
if (/Firefox[\/\s](\d+\.\d+)/.test(sUserAgent)) var FirefoxVersion=new Number(RegExp.$1);
var reTestMacOS = new RegExp("Mac OS X","ig");

var reEmail = new RegExp("^[a-z0-9\\._%+\\-]+@[a-z0-9]+[a-z0-9\\.\\-]+\\.[a-z]{2,4}$", "i");
var reLatin = new RegExp("^[a-z\.\\-\\s]+$", "i");

var MoscowLocation = {
	latitude: "55.7522222",
	longitude: "37.6155556"
};

var arTranslit = {};
var arUpper = { "А": "A", "Б": "B", "В": "V", "Г": "G", "Д": "D", "Е": "E", "Ё": "Ye", "Ж": "ZH", "З": "Z", "И": "I", "Й": "Y", "К": "K", "Л": "L", "М": "M", "Н": "N", "О": "O", "П": "P", "Р": "R", "С": "S", "Т": "T", "У": "U", "Ф": "F", "Х": "Kh", "Ц": "TS", "Ч": "Ch", "Ш": "SH", "Щ": "SHCH", "Ь": "", "Ы": "Y", "Ъ": "", "Э": "E", "Ю": "YU", "Я": "YA" };
for (l in arUpper) {
	arTranslit[l] = arUpper[l];
	arTranslit[l.toLowerCase()] = arUpper[l].toLowerCase();
}

var texts_calendar = {
	monthesFNames:	["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
	monthesDNames:	["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
	monthesSNames:	["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sen", "Oct", "Nov", "Dec"],
	daysFNames:		["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
	daysSNames:		["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
	daysS1Names: 	["S", "M", "T", "W", "T", "F", "S"],
	weekend:		[0, 6],
	weekstart:		1
};
if (language === "ru") {
	texts_calendar = {
		monthesFNames:	["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"],
		monthesDNames:	["Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августa", "Сентября", "Октября", "Ноября", "Декабря"],
		monthesSNames:	["Янв", "Фев", "Мар", "Апр", "Май", "Июн", "Июл", "Авг", "Сен", "Окт", "Ноя", "Дек"],
		daysFNames:		["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"],
		daysSNames:		["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"],
		daysS1Names: 	["В", "П", "В", "С", "Ч", "П", "С"],
		weekend:		[0, 6],
		weekstart:		1
	};
}
if (language === "ua") {
	texts_calendar = {
		monthesFNames:	["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"],
		monthesDNames:	["Січня", "Лютого", "Березня", "Квітня", "Травня", "Червня", "Липня", "Серпня", "Вересня", "Жовтня", "Листопада", "Грудня"],
		monthesSNames:	["Січ", "Лют", "Бер", "Квітт", "Трав", "Чер", "Лип", "Сер", "Вер", "Жовт", "Лист", "Груд"],
		daysFNames:		["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"],
		daysSNames:		["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"],
		daysS1Names:	["Н", "П", "В", "С", "Ч", "П", "С"],
		weekend:		[0, 6],
		weekstart:		1
	};
}

monthsGenitive = [];
$(texts_calendar.monthesDNames).each(function() {
	monthsGenitive.push(this.toLowerCase());
})

Date.prototype.cutTime = function() {
	var new_date = new Date(this.getFullYear(), this.getMonth(), this.getDate());
	this.setTime(new_date.getTime());
	return this;
};
Date.parseISOString = function(string) {
	var arrDate = string.split('-');
	var date = new Date(arrDate[0], 0, 1);
	if (arrDate[1]) date.setMonth(arrDate[1] - 1);
	if (arrDate[2]) date.setDate(arrDate[2]);
	return date.valueOf();
};
Date.parseRUString = function(string) {
	var arrDate = string.split('.');
	date = new Date(arrDate[2], arrDate[1] - 1, arrDate[0]);
	return date.valueOf();
};
Date.parseAWADString = function(string) {
	var arrDate = string.split('.');
	date = new Date(arrDate[2], arrDate[1] - 1, arrDate[0]);
	return date;
};
Date.prototype.toAWADString = function() {
	var tempDate = this.getDate();
	var tempMonth = this.getMonth() + 1;
	if (tempDate < 10) tempDate = '0' + tempDate;
	if (tempMonth < 10) tempMonth = '0' + tempMonth;
	return tempDate + "." + tempMonth + "." + this.getFullYear();
};
Date.prototype.toDateTimeString = function() {
	var tempHours = parseInt(this.getUTCHours(), 10);
	var tempMinutes = parseInt(this.getUTCMinutes(), 10);
	if (tempHours < 10) tempHours = '0' + tempHours;
	if (tempMinutes < 10) tempMinutes = '0' + tempMinutes;
	return parseInt(this.getUTCDate(), 10) + '\u00A0' + texts_calendar.monthesDNames[this.getUTCMonth()].toLowerCase() + '\u00A0' + tempHours + ':' + tempMinutes;
};
Date.prototype.toLocaleDateTimeString = function() {
	var tempHours = parseInt(this.getHours(), 10);
	var tempMinutes = parseInt(this.getMinutes(), 10);
	if (tempHours < 10) tempHours = '0' + tempHours;
	if (tempMinutes < 10) tempMinutes = '0' + tempMinutes;
	return parseInt(this.getDate(), 10) + '\u00A0' + texts_calendar.monthesDNames[this.getMonth()].toLowerCase() + '\u00A0' + tempHours + ':' + tempMinutes;
};

var JSON = JSON || {};
JSON.parse = JSON.parse || function(text) { return eval("(" + text + ")"); };
JSON.stringify = JSON.stringify || function(obj) {
	var t = typeof(obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"' + obj + '"';
		return String(obj);
	} else {
		// recurse array or object 
		var n, v, json = [], arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n];
			t = typeof(v);
			if (t == "string") v = '"' + v + '"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);
			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
};

function stopPropagation(event) {
	event = event || window.event;
	event.preventDefault && event.preventDefault();
	event.stopPropagation ? event.stopPropagation() : event.cancelBubble = true;
}

function getOffset(oNode, pNode){
	if (!pNode) {
		var pNode = document.body;
	}
	var oCurrentNode = oNode;
	var offset = {
		top: 0,
		left: 0
	};
	while (oCurrentNode && (oCurrentNode != pNode)) {
		offset.left += oCurrentNode.offsetLeft - oCurrentNode.scrollLeft;
		offset.top += oCurrentNode.offsetTop - oCurrentNode.scrollTop;
		oCurrentNode = oCurrentNode.offsetParent;
	}
	return offset;
}

function AjaxAbort(arrAjax) {
	try {
		for (objAjax in arrAjax) {
			if (arrAjax[objAjax].readyState !== 0 && arrAjax[objAjax].readyState != 4) arrAjax[objAjax].abort();
		}
	} catch (e) {}
}

function launchWindow(url, w, h, winName) {
	if (!h) popHeight = screen.availHeight - 100;
	else popHeight = h;
	winParams = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' + w + ',height=' + popHeight;
	newwin = window.open(url, winName, winParams);
	newwin.focus();
}
$('label').live('click', function() {});
function changeRadioLabels(labels) {
	var el_Label = labels || document.getElementsByTagName("label");
	$(el_Label).each(function(i) {
		var el_Input = document.getElementById(el_Label[i].htmlFor);
		if (el_Input.type == 'radio' || el_Input.type == 'checkbox') {
			if (el_Input.checked == true) {
				$(el_Label[i]).addClass("checked");
			} else {
				$(el_Label[i]).removeClass("checked");
			}
		}
	});
}

function FieldClass(elField, options) {
	var self = this;
	this.elField = elField;
	this.input = this.elField;//Old
	this.options = options || {};
	this.onPaste = false;
	this.label = $('label[for=' + this.elField.id + '][class*="defaultValue"]')[0];
	this.maxLength = $(this.elField).attr('maxlength') ? $(this.elField).attr('maxlength') : null;
	
	$(this.elField).focus(function() {
		self.elField.select();
	});
	$(this.input).bind("keydown change", function() {
		self.removeError();
	});
	
	if (options instanceof Object) {
		var _isMac = reTestMacOS.test(sUserAgent.toLowerCase());
		if (this.options.latin == true) {
			this.options.reTyping = new RegExp("^[A-Z ]+$");
			this.options.textCase = "upper";
		}
		if (this.options.latinAndCyrillic == true) {
			if (!_isMac) {
				this.options.reTyping = new RegExp("^[а-яa-z ]+$", "i");
				this.options.textCase = null;
			}
		}
		if (this.options.email == true) {
			if (!_isMac) {
				this.options.reTyping = new RegExp("^[\\w\\-\.@]+$", "i");
				this.options.textCase = null;
			}
		}
		if (this.options.numbers == true) {
			this.options.reTyping = new RegExp("^[\\d]+$");
			this.options.textCase = null;
		}
		if (this.options.latinAndNumbers == true) {
			this.options.reTyping = new RegExp("^[\\dA-Z]+$");
			this.options.textCase = "upper";
		}
		
		if (this.options.reTyping != null) {
			this.filterString();
			$(this.elField).bind("keydown", function(event) {
				self.getCode(event);
			});
			$(this.elField).bind("keypress", function(event) {
				if (!this.readOnly) {
					self.testTyping(event);
				}
			});
			$(this.elField).bind("blur", function(event) {
				self.filterString();
			});
		}
	}
	
	if (this.label != null) {
		$(this.label).click(function(){});
		setTimeout(function() {
			self.Update();
		}, 0);
		$(this.input).bind("keypress change", function() {
			self.Update();
		});
		$(this.input).bind("keypress keyup change", function() {
			setTimeout(function() {
				self.Update();
			}, 10);
		});
	}
}
FieldClass.prototype.removeError = function() {
	$(this.elField).removeClass('error');
};
FieldClass.prototype.Update = function() {
	if (this.elField.value != "" && this.label != null && this.label.className.indexOf("invisible") == -1) {
		$(this.label).addClass('invisible');
	} else if (this.elField.value == "" && this.label != null && this.label.className.indexOf("invisible") >= 0) {
		$(this.label).removeClass('invisible');
	}
};
FieldClass.prototype.testTyping = function(event) {
	var self = this;
	var charCode = (event.charCode) ? event.charCode : event.keyCode;
	var charCodeStr = String.fromCharCode(charCode);
	var keyCodeStr = String.fromCharCode(this.keyCode).toLowerCase();
	if (event.shiftKey) keyCodeStr = String.fromCharCode(this.keyCode).toUpperCase();
	keyCodeStr = this.toTextCase(keyCodeStr);
	
	if (event.ctrlKey && this.keyCode == 86) { //Ctrl + v (FF & Opera)
		setTimeout(function() {
			self.filterString();
		}, 1);
	}
	
	if (event.ctrlKey || event.altKey || (0 < this.keyCode && this.keyCode < 47 && this.keyCode != 32)) {
		return true;
	} else if ($(this.elField).attr('maxlength') > 0 && this.elField.value.length >= $(this.elField).attr('maxlength')){
		return false;	
	} else if (this.options.reTyping.test(charCodeStr)) {
		return true;
	} else {
		var strInCase = this.toTextCase(charCodeStr);
		if (this.options.reTyping.test(strInCase)) {
			this.pasteString(strInCase);
		} else if (0 < this.keyCode && 65 <= this.keyCode && this.keyCode <= 90 && this.options.reTyping.test(keyCodeStr)) {
			this.pasteString(keyCodeStr);
		}
		if (this.options.email == true) {
			if (event.shiftKey && this.keyCode == 50) this.pasteString("@");
			if (event.shiftKey == false && this.keyCode == 190) this.pasteString(".");
		}
		event.preventDefault ? event.preventDefault() : event.returnValue = false;
	}
};
FieldClass.prototype.filterString = function() {
	var str = this.toTextCase(this.elField.value);
	var newStr = "";
	for (var i = 0, textLength = str.length; i < textLength; i++) {
		var iChar = str.charAt(i);
		if (this.options.reTyping.test(iChar)) {
			newStr += iChar;
		} else if (arTranslit[iChar]) {
			if (this.options.reTyping.test(arTranslit[iChar])) newStr += arTranslit[iChar];
		}
	}
	this.elField.value = newStr;
	if($(this.elField).attr('maxlength') > 0 && this.elField.value.length >= $(this.elField).attr('maxlength')) this.elField.value = this.elField.value.substr(0,$(this.elField).attr('maxlength'));
};
FieldClass.prototype.toTextCase = function(str) {
	var strNew = str;
	switch (this.options.textCase) {
		case "upper":
			strNew = strNew.toUpperCase();
			break;
		case "lower":
			strNew = strNew.toLowerCase();
			break;
	}
	return strNew;
};
FieldClass.prototype.pasteString = function(strNew) {
	this.getSelection();
	var strStart = this.elField.value.substring(0, this.selectionStart);
	var strEnd = this.elField.value.substr(this.selectionEnd, this.elField.value.length);
	this.elField.value = strStart + strNew + strEnd;
	
	if (this.elField.setSelectionRange) {
		this.elField.setSelectionRange(this.selectionStart + 1, this.selectionStart + 1);
	} else {
		var SelectionRange = this.elField.createTextRange();
		SelectionRange.move("character", this.selectionStart + 1);
		SelectionRange.select();
	}
};
FieldClass.prototype.getCode = function(event) {
	this.keyCode = event.keyCode;
};
FieldClass.prototype.getSelection = function() {
	this.selectionStart = this.getSelectionStart() || 0;
	this.selectionEnd = this.getSelectionEnd();
};
FieldClass.prototype.getSelectionStart = function() {
	if (!this.elField.createTextRange) {
		return this.elField.selectionStart;
	} else {
		var SelectionRange = document.selection.createRange().duplicate();
		SelectionRange.moveEnd('character', this.elField.value.length);
		return this.elField.value.lastIndexOf(SelectionRange.text);
	}
};
FieldClass.prototype.getSelectionEnd = function() {
	if (!this.elField.createTextRange) {
		return this.elField.selectionEnd;
	} else {
		var SelectionRange = document.selection.createRange().duplicate();
		SelectionRange.moveStart('character', -this.elField.value.length);
		return SelectionRange.text.length;
	}
};

function PasswordInput(elInput) {
	var self = this;
	
	this.PassInput = elInput;
	$(this.PassInput).blur(function() {
		if (self.PassInput.value == '') {
			self.setTextInput();
		}
	});
	
	this.Parent = this.PassInput.parentNode;
	
	this.TextInput = document.createElement("input");
	this.TextInput.type = "text";
	this.TextInput.maxlength = this.PassInput.maxlength;
	this.TextInput.name = this.PassInput.name;
	this.TextInput.id = this.PassInput.id;
	this.TextInput.setAttribute("default", this.PassInput.getAttribute("default"));
	this.TextInput.value = this.TextInput.getAttribute("default");
	this.TextInput.Field = new FieldClass(this.TextInput);
	
	this.setTextInput();
}
PasswordInput.prototype.setTextInput = function() {
	var self = this;
	this.Parent.removeChild(this.PassInput);
	this.Parent.appendChild(this.TextInput);
	this.TextInput.Field.Update();
	$(this.TextInput).one("focus", function() {
		self.setPassInput();
	});
};
PasswordInput.prototype.setPassInput = function() {
	var self = this;
	this.PassInput.value = '';
	this.Parent.removeChild(this.TextInput);
	this.Parent.appendChild(this.PassInput);
	setTimeout(function() {
		self.PassInput.focus();
	}, 1);
};

function FieldsErrors() {
	this.Error = false;
	this.ErrorElements = [];
	this.ErrorAlerts = [];
}

/* FadeIn */
function FadeIn(className, opacity) {
	if (!window.XMLHttpRequest) $('select').addClass('invisible');
	var div = $("#FadeInDiv");
	if (!div.length) {
		div = $('<div id="FadeInDiv" />');
		if (opacity != null) {
			div.css({
				'opacity': opacity,
				'filter': 'alpha(opacity=' + opacity * 100 + ')'
			});
		}
		if (isIPad()) {
			// Просто растягиваем на весь экран, потому что:
			// Оне не скроллирует тег body, он показывает всю страницу и работает со своим масштабированием и скроллингом
			// Да и ширину/высоту определяет бе учета паддинга и маржина
			div.css({
				width: document.body.scrollWidth,
				height: document.body.scrollHeight
			})
		}
		div.appendTo(document.body);
	}
	div.attr("className", className || "");
	div.show();
}
function FadeOut() {
	var div = document.getElementById("FadeInDiv");
	if (div != null) {
		document.body.removeChild(div);
		if (!window.XMLHttpRequest) $('select').removeClass('invisible');
	}
}
/* /Fade */

/* Cookies */
function CreateCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
	}
	document.cookie = name + "=" + escape(value) + ((days) ? "; expires=" + date.toGMTString() : "") + "; path=/";
}
function ReadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}
function EraseCookie(name) {
	this.CreateCookie(name, "", -1);
}
/* //Cookies */

/*4Email*/
function Reverse(Text) {
	splitext = Text.split("");
	revertext = splitext.reverse();
	reversed = revertext.join("");
	return reversed;
}

/* Preloader */	
function CreateLoader() {
	if (document.getElementById('Loader') == null && document.body != null) {
		var div = document.createElement('div');
		var image = document.createElement('div');
		div.id = 'Loader';
		div.className = 'invisible';
		div.appendChild(image);
		document.body.appendChild(div);
	}
}
function ShowLoader() {
	var div = document.getElementById('Loader');
	if (div != null) $(div).removeClass('invisible');
}
function HideLoader() {
	var div = document.getElementById('Loader');
	if (div != null) $(div).addClass('invisible');
}
/* /Preloader */


function LoadingShow() {
	var LoadingBlock = document.getElementById('Loading');
	if (!LoadingBlock) {
		LoadingCreate();
	}
	$("#Loading").removeClass('invisible').center();
}
function LoadingCreate() {
	var elLoadingBlock = document.createElement("div");
		elLoadingBlock.className = "LoadingBlock invisible";
		elLoadingBlock.id = "Loading";
	
	if(IEVersion) {
		$(elLoadingBlock).addClass("LoadingBlockIe");
		var vml_code = '<v:roundrect arcsize=".1" fillcolor="white" stroked="True" strokecolor="white"></v:roundrect>';
		elLoadingBlock.innerHTML = vml_code;
	}
	
	var elLoading = document.createElement("div");
		elLoading.className = "Loading";
	
	elLoadingBlock.appendChild(elLoading);
	document.body.appendChild(elLoadingBlock);
}
function LoadingHide(){
	var LoadingBlock = document.getElementById('Loading');
	if (LoadingBlock) {
		$(LoadingBlock).addClass('invisible');
	}
}

/* Popup */
function Popup1(Content, options) {
	var self = this;
	this.Content = Content || null;
	this.options = options || {};
	this.SetStyleLink = function() {
		self.SetStyle();
	};
	this.OnKeyupCloseLink = function(event) {
		self.OnKeyupClose(event);
	};
	this.OnClickOutsideLink = function(event) {
		self.OnClickOutside(event);
	};
	this.Create();
}
Popup1.prototype.Create = function() {
	var self = this;
	this.elPopup = document.createElement("div");
	this.elPopup.className = "Popup1 invisible";
	$(this.elPopup).click(function(event){
		event.stopPropagation();
	});
	this.elContent = document.createElement("div");
	this.elContent.className = "PopupContent";
	if(this.Content){
		this.elContent.appendChild(this.Content);
	}
	this.elPopup.appendChild(this.elContent);
	if (IEVersion || OperaVersion < 9.8 || GeckoVersion < 1.91) {
		this.CreateShadow();
	}
	
	this.elLoading = document.createElement("div");
	this.elLoading.className = "Loading";
	
	this.CreateCloseButton();
};
Popup1.prototype.CreateCloseButton = function() {
	var self = this;
	this.CloseButton = document.createElement("div");
	this.CloseButton.className = "PopupCloseButton";
	this.elPopup.appendChild(this.CloseButton);
	if (!window.XMLHttpRequest) {
		var IE6 = document.createElement("div");
			IE6.className = "IE6";
		this.CloseButton.appendChild(IE6);
	}
	this.CloseButton.onclick = function() {
		self.Hide();
	};
};
Popup1.prototype.CreateShadow = function() {
	this.elShadow = document.createElement("div");
	this.elShadow.className = "PopupShadow";
	this.elShadow.innerHTML = '<div class="tl"></div><div class="t"></div><div class="tr"></div><div class="r"></div><div class="br"></div><div class="b"></div><div class="bl"></div><div class="l"></div>';
	this.elPopup.appendChild(this.elShadow);
};
Popup1.prototype.GetStyles = function() {
	this.cssWidth = parseInt($(this.elPopup).css("width"), 10);
	this.cssHeight = parseInt($(this.elPopup).css("height"), 10);
	this.cssMinWidth = parseInt($(this.elPopup).css("min-width"), 10);
	this.cssMinHeight = parseInt($(this.elPopup).css("min-height"), 10);
	if (IEVersion) {
		this.elPopup.style.minWidth = this.cssWidth;
		this.elPopup.style.minHeight = this.cssHeight;
	}
};
Popup1.prototype.SetStyle = function() {
	if(IEVersion < 8) {
		this.elPopup.style.top = (document.documentElement.scrollTop + 45) + "px";
	} else if (isIPad()) {
		this.elPopup.style.position = "absolute";
		this.elPopup.style.bottom = -$(window).scrollTop() + "px";
		this.elPopup.style.top = $(window).scrollTop() + "px";
	} else	{
		if ((document.documentElement.clientWidth < (this.cssMinWidth + 20) || document.documentElement.clientHeight < (this.cssMinHeight + 20))
			 || (IEVersion && (document.documentElement.clientWidth < (this.cssWidth + 20) || document.documentElement.clientHeight < (this.cssHeight + 20)))) {
			this.elPopup.style.position = "absolute";
			this.elPopup.style.bottom = "auto";
			this.elPopup.style.top = (document.documentElement.scrollTop + document.body.scrollTop + 10) + "px";
		} else {
			this.elPopup.style.position = "fixed";
			this.elPopup.style.top = "10px";
			this.elPopup.style.bottom = "10px";
		}
	}
};
Popup1.prototype.SetId = function(Id){
	this.elPopup.id = Id;
};
Popup1.prototype.Add = function() {
	var self = this;
	document.body.appendChild(self.elPopup);
	this.Added = true;
};
Popup1.prototype.Remove = function() {
	var self = this;
	document.body.removeChild(self.elPopup);
	delete self;
};
Popup1.prototype.Show = function(Content) {
	var self = this;
	if(Content){
		this.Content = Content;
		this.elContent.appendChild(this.Content);
	}
	if(!this.Added){
		this.Add();
	}
	
	FadeIn();
	this.GetStyles();
	this.SetStyleLink();
	$(window).bind("resize", self.SetStyleLink);
	$(document).bind("keyup", self.OnKeyupCloseLink);
	setTimeout(function(){
		$(document).bind("click", self.OnClickOutsideLink);
	}, 1000);
	$(self.elPopup).removeClass("invisible");
};
Popup1.prototype.Hide = function() {
	var self = this;
	$(this.elPopup).addClass("invisible");
	$(window).unbind("resize", self.SetStyleLink);
	$(document).unbind("keyup", self.OnKeyupCloseLink);
	$(document).unbind("click", self.OnClickOutsideLink);
	FadeOut();
};
Popup1.prototype.ShowLoading = function(){
	this.elPopup.appendChild(this.elLoading);
};
Popup1.prototype.HideLoading = function(){
	$(this.elLoading).addClass("invisible");
};
Popup1.prototype.OnKeyupClose = function(event) {
	if (event.keyCode == 27) {
		this.Hide();
	}
};
Popup1.prototype.OnClickOutside = function(event) {
	this.Hide();
};
function Popup_Iframe(Link, options) {
	var self = this;
	this.elLink = Link;
	this.CreateIframe();
	this.options = options || {};
	Popup_Iframe.parent.constructor.call(this, this.elIframe, this.options);
	this.elPopup.className += " Popup_Iframe";
	$(this.elLink).one("click", function(){
		self.BindListeners();
		self.ShowLoading();
		self.Show();
		return false;
	});
}
inherits(Popup_Iframe, Popup1);
Popup_Iframe.prototype.CreateIframe = function(){
	this.elIframe = document.createElement("iframe");
	this.elIframe.frameBorder = "0";
	if (this.elLink.href.indexOf('?') != -1) {
		this.elIframe.src = this.elLink.href + '&Popup=True';
	} else {
		this.elIframe.src = this.elLink.href + '?Popup=True';
	}
};
Popup_Iframe.prototype.BindListeners = function(){
	var self = this;
	$(this.elIframe).load(function(){
		self.HideLoading();
	});
	$(this.elLink).click(function(){
		self.Show();
		return false;
	});
};


Popup = function(ContentXHTML, PopupHideType) {
	var self = this;
	this.Content = ContentXHTML;
	this.OnClose = function() {
	};
	this.ShadowImageURL = "/images/overlay/overlay-bkg.png";
	this.OnKeyupCloseLink = function(event) {
		self.OnKeyupClose(event);
	};
	this.HideLink = function(event) {
		self.Hide(event);
	};
	this.SetStyleLink = function(event) {
		self.SetStyle(event);
	};
	this.PopupHideType = PopupHideType || "Delete"; /* Delete (удаляет), Hide (прячет) */
	this.Create();
	this.Add();
};
Popup.prototype.Create = function() {
	var self = this;
	this.Box = document.createElement("div");
	this.Box.className = "Popup";
	this.BackgroundLayer = document.createElement("div");
	this.BackgroundLayer.className = "PopupBackground";
	this.Box.appendChild(this.BackgroundLayer);
	this.BoxContent = document.createElement("div");
	this.BoxContent.className = "PopupContent";
	this.Box.appendChild(this.BoxContent);
	this.BoxContent.appendChild(this.Content);
	this.CloseButton = document.createElement("div");
	this.CloseButton.className = "PopupCloseButton";
	this.Box.appendChild(this.CloseButton);
	this.CloseButton.onclick = function() {
		self.Hide();
	};
	this.ShadowImage = document.createElement("img");
	this.ShadowImage.className = "PopupShadowImage";
	this.ShadowImage.alt = "";
	this.ShadowImage.src = this.ShadowImageURL;
	this.Box.appendChild(this.ShadowImage);
	if (!window.XMLHttpRequest) {
		this.ShadowImageIE6 = document.createElement("div");
		this.ShadowImageIE6.className = "PopupShadowImageIE6";
		this.Box.appendChild(this.ShadowImageIE6);
		this.CloseButtonIE6 = document.createElement("div");
		this.CloseButtonIE6.className = "IE6";
		this.CloseButton.appendChild(this.CloseButtonIE6);
		$(this.CloseButton).mouseover(function() {
			$(this.firstChild).addClass("hover");
		});
		$(this.CloseButton).mouseout(function() {
			$(this.firstChild).removeClass("hover");
		});
	}
	this.FadeInDiv = null;
};
Popup.prototype.OnKeyupClose = function(event) {
	if (event.keyCode == 27) {
		this.Hide();
	}
};
Popup.prototype.Add = function() {
	var self = this;
	document.body.appendChild(this.Box);
	$(document).bind("keyup", self.OnKeyupCloseLink);
};
Popup.prototype.RemoveAndDelete = function() {
	var self = this;
	$(document).unbind("keyup", self.OnKeyupCloseLink);
	document.body.removeChild(self.Box);
	delete self;
};
Popup.prototype.Show = function() {
	var self = this;
	FadeIn();
	this.FadeInDiv = document.getElementById("FadeInDiv");
	$(this.FadeInDiv).bind("click", self.HideLink);
	this.SetStyle();
	this.Box.style.display = "block";
	$(window).bind("resize", self.SetStyleLink);
};
Popup.prototype.SetStyle = function() {
	if (document.documentElement.clientWidth < 775 || document.documentElement.clientHeight < 400) {
		this.Box.style.position = "absolute";
		this.Box.style.bottom = -$(window).scrollTop() + "px";//-document.documentElement.scrollTop + "px";
		this.Box.style.top = $(window).scrollTop() + "px";//document.documentElement.scrollTop + "px";
	} else {
		$(this.Box).center();
//		this.Box.style.position = "fixed";
//		this.Box.style.top = "0px";
//		this.Box.style.bottom = "0px";
	}
//	if (!window.XMLHttpRequest || isIPad()) {
//		this.Box.style.position = "absolute";
//		this.Box.style.top = $(window).scrollTop() + "px";//document.documentElement.scrollTop + "px";
//		this.Box.style.bottom = "0px";
//	}
};
Popup.prototype.Hide = function(event) {
	var self = this;
	this.Box.style.display = "none";
	$(this.FadeInDiv).unbind("click", self.HideLink);
	$(window).unbind("resize", self.SetStyleLink);
	this.OnClose();
	if (self.PopupHideType == "Delete") self.RemoveAndDelete();
	FadeOut();
};
/* /Popup */

/* Center Positioning Extension */
$.fn.center = function(obj) {
	var forCentring = this.filter(":not([centered])");
	if (!forCentring.length) {
		this.data("centerFunc") && this.data("centerFunc")();
		return this;
	} else {
		forCentring.attr("centered", "centered");
	}
	var element = forCentring;//this;
	var centerFunc = function() {
//		$(element).css({
//			position: "absolute", width: "auto", height: "auto",
//			margin: "0",right: "auto",bottom: "auto"
//		});
		var elementHeight = $(element).height();
		var elementWidth = $(element).width();
		
		if (element.is(":visible")) {
			$(element).css({
				"width": elementWidth,
				"height": elementHeight
			});
		}
		$(element).css({
			"position": "fixed",
			"margin": "auto",
			"top": "0px",
			"right": "0px",
			"bottom": "0px",
			"left": "0px",
			"z-index": "100"
		});
		
		if ($.browser.msie) {
			$(element).css({
				"left": "50%",
				"top": "50%",
				"margin-top": (-elementHeight / 2),
				"margin-left": (-elementWidth / 2)
			});
			if (!window.XMLHttpRequest) { //ie6
				$(element).attr("style", "position: absolute; top: expression(documentElement.scrollTop+documentElement.offsetHeight/2-" + elementHeight / 2 + "); left: expression(documentElement.scrollLeft+documentElement.offsetWidth/2-" + elementWidth / 2 + ");");
			}
		}
		if (isIPad()) {
			$(element).css({
				"position": "absolute",
				"left": "50%",
				"top": "50%",
				"margin-top": ($(window).scrollTop() - elementHeight / 2) + "px",
				"margin-left": ($(window).scrollLeft() - elementWidth / 2) + "px"
			});
		}
		
		if (obj != null) {
			$(obj).append(element);
			var objHeight = $(obj).height();
			var objWidth = $(obj).width();
			$(element).css({
				"position": "relative",
				"top": objHeight / 2 - elementHeight / 2 + 'px',
				"margin": "auto",
				"left": '0px'
			});
			if (!window.XMLHttpRequest) { //ie6
				$(element).attr("style", "position: absolute; top: expression(parentNode.offsetHeight/2-" + elementHeight / 2 + "); left: expression(parentNode.offsetWidth/2-" + elementWidth / 2 + ");");
			}
		}
	};
	centerFunc();
	forCentring.data("centerFunc", centerFunc);
	$(window).resize(centerFunc);
	$(window).scroll(centerFunc);
};
/* /Center Positioning Extension */	

/* Fading Alert Message */
	function AlertMessage(text, fix) {
		var self = this;
		this.Text = text;
		this.isTemp = (fix != null) ? fix : true;
		this.RoundBlock = null;
		this.Indent = 20;
		//for msie
		this.ieDiv = null;
		this.Height = 0;
		this.Width = 0;
		this.Style = '';
		
		this.FadeAlertLink = function() {
			self.FadeAlert();
		};
		this.RemoveLink = function() {
			self.Remove();
		};
		this.InitDOMManipulation();
	}
	
	AlertMessage.prototype.InitDOMManipulation = function() {
		//for msie
		if ($.browser.msie) {
			this.ieDiv = document.createElement("div");
			$(this.ieDiv).html(this.Text);
			$(this.ieDiv).css({
				"font-size": "200%",
				"display": "inline"
			});
			document.body.appendChild(this.ieDiv);
			this.Height = $(this.ieDiv).height() + this.Indent * 2;
			this.Width = $(this.ieDiv).width() + this.Indent * 2;
			this.Style = "height:" + this.Height + "px;" + " width:" + this.Width + "px;";
			$(this.ieDiv).remove();
		}
		// end for msie	
		this.CreateMessage();
	};
	AlertMessage.prototype.CreateMessage = function() {
		this.RoundBlock = document.createElement("div");
		this.inset = document.createElement("div");
		if ($.browser.msie) {
			this.RoundBlock.className = "alertMessageIe";
			var code = '<div style="font-size: 200%; margin:' + this.Indent + 'px;">' + this.Text + '</div>';
			var vml_code = '<v:roundrect arcsize=".2" fillcolor="#818E92" stroked="True" strokecolor="#818E92" class="" style="' + this.Style + '">' + code + '</v:roundrect>';
			this.inset.innerHTML = vml_code;
		} else {
			this.RoundBlock.className = "alertMessage";
			$(this.inset).css({
				"padding": this.Indent,
				"margin": "auto"
			});
			this.inset.innerHTML = this.Text;
		}
		this.RoundBlock.appendChild(this.inset);
		document.body.appendChild(this.RoundBlock);
		this.ApplyCSS();
	};
	AlertMessage.prototype.ApplyCSS = function() {
		var self = this;
		$(this.RoundBlock).center(); //Center Positioning extension
		// redefining z-index set to 100 while centring 
		// in order to exceed that of other popups
		$(this.RoundBlock).css("z-index", "800");
		if (!window.XMLHttpRequest) $('select').addClass('invisible');
		if (self.isTemp) {
			setTimeout(function() {
				self.FadeAlert();
			}, 1500);
		}
	};
	AlertMessage.prototype.FadeAlert = function() {
		var self = this;
		$(this.RoundBlock).css({
			filter: 'alpha(opacity=90)'
		}).fadeOut(1500);
		setTimeout(function() {
			self.RemoveObj();
		}, 1600);
	};
	AlertMessage.prototype.RemoveObj = function() {
		var self = this;
		$(self.RoundBlock).empty();
		$(self.RoundBlock).remove();
		if (!window.XMLHttpRequest) $('select').removeClass('invisible');
		delete self;
	};
/* /Fading Alert Message */

/* Smooth Focus */
	function SmoothFocus(element) {
		var size = document.documentElement.clientHeight / 2;
		var offsetTop = $(element).offset().top 
		if (isIPad()) {
			// jquery error http://bugs.jquery.com/ticket/6446
			offsetTop -= window.pageYOffset;
		}
		var ScrollTo = offsetTop - size + $(element).height() - 80;
		if (ScrollTo < 0) ScrollTo = 0;
		$.scrollTo(ScrollTo, 400);
		//$('html,body').animate({scrollTop: $(element).offset().top - size + $(element).height() }, 800);  //in opera scroll begins from top //http://www.nabble.com/Scroll-to-top-animate-in-Opera-9%2B-td20248444s27240.html
		setTimeout(function() {
			element.focus();
		}, 400);
	}
/* /Smooth Focus */

/* GeoLocation */
	function GeoLocation() {
		this.Callback = function() {};
	}
	GeoLocation.prototype.GetIpLocation = function() {
		var self = this;
		$.ajax({
			cache: false,
			type: "get",
			url: "/_references/GeoLocation/",
			success: function(xml) {
				self.Country = xml.getElementsByTagName("Country")[0].firstChild.data;
				self.CountryCode = xml.getElementsByTagName("Country")[0].getAttribute("Code");
				self.City = xml.getElementsByTagName("CityName")[0].firstChild.data;
				self.Latitude = xml.getElementsByTagName("Latitude")[0].firstChild.data;
				self.Longitude = xml.getElementsByTagName("Longitude")[0].firstChild.data;
				self.Callback();
			}
		});
	};
/* /GeoLocation */

/* Currency */
	function Currency(number, Code) {
		this.number = number;
		this.CurrencyCode = Code || null;
		this.numberStr = this.number.toString();
	}
	Currency.prototype.GetFormatNumber = function() {
		return FormatMoney(this.number);
	};
	Currency.prototype.GetSymbol = function() {
		return CurrencyList[this.CurrencyCode].Symbol;
	};
	Currency.prototype.GetAbbr = function() {
		return CurrencyList[this.CurrencyCode].Abbr;
	};
	Currency.prototype.GetString = function() {
		var LastNumber = this.numberStr.substr(this.numberStr.length - 1);
		var PreLastNumber = this.numberStr.substring(this.numberStr.length - 2, 1);
		if (LastNumber == 1) {
			return CurrencyList[this.CurrencyCode].Nominative;
		} else {
			if (PreLastNumber != 1 && (LastNumber == 2 || LastNumber == 3 || LastNumber == 4)) {
				return CurrencyList[this.CurrencyCode].Genitive;
			} else {
				return CurrencyList[this.CurrencyCode].Genitive_Plural;
			}
		}
	};
	function FormatMoney(Money, isFullNumber) {
		Money += '';
		x = Money.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1].substr(0, 2) : '';
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + '\u00A0' + '$2');
		}
		if (isFullNumber) {
			if (x2.length == 2) x2 = x2 + '0';
			if (x2.length == 0) x2 = '.00';
		}
		return (x1 + x2);
	}
/* /Currency */

(function ($) {
/* ToolTip */
$.fn.tooltip = function(options) {
	if (isIPad()) {
		// disable tooltip for iPad with touchscreen
		return this;
	}
	
	var defaults = {
		background: '#e3e3e3',
		color: 'black',
		padding: '5',
		showBody: ", ", // devider, transform symbol to <br/>
		contentId: false,  // container identifier (overrides title content)
		rounded: true
	}, settings = $.extend(defaults, options);
	
	var WindowHeight = (window.innerHeight) ? window.innerHeight : document.body.clientHeight;
	var WindowWidth = (window.innerWidth) ? window.innerWidth : document.body.clientWidth;
	
	$(window).resize(function() {
		ScreenSize();
	});
	function ScreenSize() {
		WindowHeight = (window.innerHeight) ? window.innerHeight : document.body.clientHeight;
		WindowWidth = (window.innerWidth) ? window.innerWidth : document.body.clientWidth;
		$('#win').html(' width: ' + WindowWidth + '   height: ' + WindowHeight);
	}
	
	this.each(function() {
		var $this = $(this);
		// var title = this.title;
		var title;
		if (settings.contentId) {
			title = $("#"+settings.contentId).html();
		} else {
			title = this.title;
		}
		if (title != '') {
			this.title = '';
			
			if (settings.showBody) {
				var parts = title.split(settings.showBody);
				temp = '';
				for (i = 0, partsLength = parts.length; i < partsLength; i++) {
					temp += parts[i];
					if (i + 1 < partsLength) temp += '<br/>';
				}
				title = temp;
			}
			
			$this.hover(function(e) {
				//mouse over
				$('#tooltip').remove();
				$('<div id="tooltip" />').appendTo('body').hide().html(title).css({
					"background-color": settings.background,
					"font-size": "80%",
					"color": settings.color,
					"border": "1px solid gray",
					"white-space": "nowrap",
					"top": e.pageY + 10,
					"left": e.pageX + 15,
					"padding": settings.padding + "px",
					"position": "absolute",
					"overflow": "hidden",
					"z-index": "101"
				//							"filter": "Alpha(opacity=90)",
				//						"opacity": "0.9"
				}).fadeIn(150);
				
				if (settings.rounded) {
					$('#tooltip').css({
						"-moz-border-radius": "10px",
						"-webkit-border-radius": "10px",
						"-khtml-border-radius": "10px",
						"border-radius": "10px"
					});
				}
			}, function() {
				// mouse out  
				$('#tooltip').remove();
			});
		}
		
		$this.mousemove(function(e) {
			titleHeight = $('#tooltip').height() + 2 * settings.padding;
			titleWidth = $('#tooltip').width() + 2 * settings.padding;
			focusTop = e.pageY + 10;
			focusLeft = e.pageX + 15;
			if (WindowHeight - e.clientY - titleHeight < 10) focusTop = e.pageY - titleHeight;
			if (WindowWidth - e.clientX < titleWidth + 40) focusLeft = e.pageX - titleWidth;
			
			$('#tooltip').css({
				top: focusTop,
				left: focusLeft
			});
		});
		
	});
	return this;
};

/* JSON functions */
$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

$.extend({valueTags: ["input", "select", "textarea"]});

$.extend($.fn, {
	fullClick: function(eventHandler){
		// В ИЕ событие click чередуется с dblclick
		// поэтому чтобы реакция шла на каждое нажатие мыши нужно вешать хендлер на два эвента
		var eventNames = ($.browser.msie) ? "click dblclick" : "click";
		return (eventHandler != undefined) ? this.bind(eventNames, eventHandler) : this.trigger("click");
	},
	
	_val: function(value, add){
		// 
		if ( value == undefined ) {
			if ( this.length ) {
				var elem = this[0];
				if(jQuery.inArray((elem.tagName + "").toLowerCase(), jQuery.valueTags) < 0){
					return $(elem).text();
				}else{
					return $(elem).val();
				}
			}
			return undefined;
		}else{
			return this.each(function(){
				if(jQuery.inArray((this.tagName + "").toLowerCase(), jQuery.valueTags) < 0){
					$(this).text(add ? $(this).text() + value : value);
				}else{
					$(this).val(add ? $(this).val() + value : value);
				}
			});
		}
	}
});

$.extend($.expr[":"], {
	// РегистоНезависимый поск контента
	Contains: function(a,i,m){return (a.textContent||a.innerText||jQuery(a).text()||"").toLowerCase().indexOf((m[3]||"".toLowerCase()))>=0;}
});
})(jQuery);

String.prototype.supplant = function(obj) {
    return this.replace(/{([^{}]*)}/g, function(a, b) {
        var r = obj[b];
        return typeof r === 'string' || typeof r === 'number' ? r : a;
    });
};

/* reservation time zone */
function ShowDateByTimeZone(span) {
	var self = this;
	this.Span = span;
	this.Select = $('select[name="GMTZone"]')[0];
	this.SpanTarget = $(this.Span).attr('target');
	if(this.SpanTarget) this.Select = $('select[aim="' +this.SpanTarget+ '"]')[0];
	this.iUTC = parseInt($(self.Span).attr('default'), 10);
	$(this.Select).change(function() { self.ChangedZone(this.value) });
	var currentTZ = -parseFloat(new Date().getTimezoneOffset() / 60);
	this.Select.value = currentTZ;
	this.ChangedZone(currentTZ);
}
ShowDateByTimeZone.prototype.ChangedZone = function(value) {
	var self = this;
	var NewDate = new Date(self.iUTC);
	var valueH = parseInt(value);
	if (String(value).indexOf('.') != -1) {
		var time = String(value).split('.');
		valueH = parseInt(time[0], 10);
		if (time[1]) {
			var valueM = time[1];
			if (valueM < 10) valueM = valueM + '0';
			valueM = parseInt(valueM * 3 / 5, 10);
			if (parseFloat(value) < 0) valueM = -valueM;
			NewDate.setMinutes(NewDate.getMinutes() + valueM);
		}
	}
	NewDate.setHours(NewDate.getHours() + valueH);
	$(this.Span).html(NewDate.toDateTimeString());
}


function isIPad() {
	return navigator.platform == "iPad";
}

/* decline word */
function declineWordByQuantity(variants, quantity, lang) {
	var variant = 0;
	if (!lang || lang == "ru") {
		// Русский язык
		var sign = quantity % 10 ;
		var doubleSign = quantity % 100;
		if ($.inArray(sign, [5,6,7,8,9,0]) != -1 || $.inArray(doubleSign, [11,12,13,14]) != -1) {
			variant = 2;
		} else if ($.inArray(sign, [2,3,4]) != -1) {
			variant = 1;
		} else {
			variant = 0;
		}
	} else if (lang == "en") {
		// Английский язык
		if (quantity != 1) {
			variant = 1;
		} else {
			variant = 0;
		}
	} else if (lang == "ua") {
		// Украинский язык
		var sign = quantity % 10 ;
		var doubleSign = quantity % 100;
		if ($.inArray(sign, [5,6,7,8,9,0]) != -1 || $.inArray(doubleSign, [11,12,13,14]) != -1) {
			variant = 1;
		} else {
			variant = 0;
		}
	}
	
	return variants[variant] || variants[0];
}

function extend(Child, Parent) {
	var F = function() { };
	F.prototype = Parent.prototype;
	Child.prototype = new F();
	Child.prototype.constructor = Child;
	Child.superclass = Parent.prototype;
}

function extractFromObject(targetObject, attributesArray, notNull, valueAdjuster) {
	if (typeof notNull != "boolean") {
		valueAdjuster = notNull;
		notNull = null;
	}
	var extractedObject = {};
	for (var i in attributesArray) {
		var attributeName = attributesArray[i];
		var attributeValue = targetObject[attributeName];
		if (valueAdjuster) {
			attributeValue = valueAdjuster(attributeValue, attributeName);
		}
		if (notNull && attributeValue == null) {
			continue;
		}
		extractedObject[attributeName] = attributeValue;
	}
	return extractedObject;
}

/*
$(function() {
	if ($(".elementToggler").length) {
		var setTogglerTitle = function() {
			var toggler = $(this);
			var toggleTarget = $(toggler.attr("toggleTarget"));
			if (toggleTarget.filter(":visible").length) {
				toggler.html(toggler.attr("hideTitle"));
			} else {
				toggler.html(toggler.attr("showTitle"));
			}
		}
		
		$(".elementToggler").each(setTogglerTitle).live("click", function() {
			$(toggler.attr("toggleTarget")).toggle();
			setTogglerTitle.call(this);
		})
	}
})
*/
