if(typeof(String.prototype.trim) == "undefined") {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/, '');
	};
};


Date.prototype.format = function(format) {
	var returnStr = '';
	var replace = Date.replaceChars;
	for (var i = 0; i < format.length; i++) {
		var curChar = format.charAt(i);
		if (i - 1 >= 0 && format.charAt(i - 1) == "\\") {
			returnStr += curChar;
		}
		else if (replace[curChar]) {
			returnStr += replace[curChar].call(this);
		} else if (curChar != "\\"){
			returnStr += curChar;
		}
	}
	return returnStr;
};

Date.replaceChars = {
	shortMonths: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
	longMonths: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
	shortDays: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
	longDays: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],

	// Day
	d: function() { return (this.getDate() < 10 ? '0' : '') + this.getDate(); },
	D: function() { return Date.replaceChars.shortDays[this.getDay()]; },
	j: function() { return this.getDate(); },
	l: function() { return Date.replaceChars.longDays[this.getDay()]; },
	N: function() { return this.getDay() + 1; },
	S: function() { return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th'))); },
	w: function() { return this.getDay(); },
	z: function() { var d = new Date(this.getFullYear(),0,1); return Math.ceil((this - d) / 86400000); }, // Fixed now
	// Week
	W: function() { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((((this - d) / 86400000) + d.getDay() + 1) / 7); }, // Fixed now
	// Month
	F: function() { return Date.replaceChars.longMonths[this.getMonth()]; },
	m: function() { return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1); },
	M: function() { return Date.replaceChars.shortMonths[this.getMonth()]; },
	n: function() { return this.getMonth() + 1; },
	t: function() { var d = new Date(); return new Date(d.getFullYear(), d.getMonth(), 0).getDate();}, // Fixed now, gets #days of date
	// Year
	L: function() { var year = this.getFullYear(); return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)); },	// Fixed now
	o: function() { var d  = new Date(this.valueOf());  d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear();}, //Fixed now
	Y: function() { return this.getFullYear(); },
	y: function() { return ('' + this.getFullYear()).substr(2); },
	// Time
	a: function() { return this.getHours() < 12 ? 'am' : 'pm'; },
	A: function() { return this.getHours() < 12 ? 'AM' : 'PM'; },
	B: function() { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24); }, // Fixed now
	g: function() { return this.getHours() % 12 || 12; },
	G: function() { return this.getHours(); },
	h: function() { return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12); },
	H: function() { return (this.getHours() < 10 ? '0' : '') + this.getHours(); },
	i: function() { return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes(); },
	s: function() { return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds(); },
	u: function() { return "Not Yet Supported"; },
	// Timezone
	e: function() { return "Not Yet Supported"; },
	I: function() { return "Not Yet Supported"; },
	O: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00'; },
	P: function() { return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':00'; }, // Fixed now
	T: function() { var m = this.getMonth(); this.setMonth(0); var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1'); this.setMonth(m); return result;},
	Z: function() { return -this.getTimezoneOffset() * 60; },
	// Full Date/Time
	c: function() { return this.format("Y-m-d\\TH:i:sP"); }, // Fixed now
	r: function() { return this.toString(); },
	U: function() { return this.getTime() / 1000; }
};

var SGSNiE = new Object();

SGSNiE.jsonrpc = null;

SGSNiE.connect = function() {
	try {
		SGSNiE.jsonrpc = new JSONRpcClient("json-rpc");
		return true;
	}
	catch(e) {
		SGSNiE.jsonrpc = null;
		alert("Не удалось инициализировать подключение к удаленному сервису.\r\n" + e);
		return false;
	} finally {
		SGSNiE.init();
	}
};

SGSNiE.reconnect = function() {
	if(SGSNiE.connect()) {
		SGSNiE.action.processState();
		SGSNiE.handle.auth();
		return true;
	}
	return false;
};

SGSNiE.init = function() {
	if(SGSNiE.jsonrpc != null && typeof(SGSNiE.jsonrpc.userservice) != "undefined") {
		try {
			SGSNiE.state.user = SGSNiE.jsonrpc.userservice.getUser();
		} catch(e) {
			alert("Системная ошибка получения сведений о пользователе.\r\n" + e);
		}
	} else {
		SGSNiE.state.user = null;
		SGSNiE.state.access = false;
	}
	if(SGSNiE.user && SGSNiE.user.action && SGSNiE.user.action.init) {
		SGSNiE.user.action.init(SGSNiE.state.user);
	}
};


SGSNiE.consts = {
	PAGE_DEFAULT: "main",
	PAGE_FADE_TIME: 200,
	PAGE_SCROLL_TIME: 500,
	PAGE_SLIDE_TIME: 200,
	PAGE_MOVE_TIME: 'slow'
};

SGSNiE.handle = {
	call: function(call) {
		try {
			call();
		} catch(e) {
			SGSNiE.handle.callError(e);
		}
	},
	cb: function(cb,stack) {
		if(typeof(stack) == "undefined") {
			stack = true;
		}
		if(stack) {
			SGSNiE.stack.push();
		}
		return function(result, exception) {
			try {
				if(typeof(result) != "undefined") {
					if(exception) {
						SGSNiE.handle.cbError(exception);
					} else {
						cb(result);
					}
				}
			} catch(error) {
				SGSNiE.handle.callError(error);
			}
			if(stack) {
				SGSNiE.stack.pop();
			}
		};
	},
	auth: function(func) {
		if(SGSNiE.state.user != null) {
			SGSNiE.state.access = true;
			if(func) {
				try {
					return func(SGSNiE.state.user);
				} catch(e) {
				}
			}
		} else {
			SGSNiE.state.access = false;
			alert("Вы не авторизованы");
		}
	},
	callError: function(error) {
		alert('Ошибка вызова обработчика.' + '\r\n' + error);
	},
	netError: function(error) {
		alert('Ошибка сети.' + '\r\n' + error);
	},
	cbError: function(error) {
		if(error.code && error.code == JSONRpcClient.Exception.CODE_ERR_NOMETHOD) {
			if(SGSNiE.state.access) {
				SGSNiE.reconnect();
			}
		} else {
			alert('Ошибка получения ответа.' + '\r\nCode: ' + error.code + '\r\nMessage: ' + error.msg);
		}
	}
};

SGSNiE.handler = {
	page: {}
};

SGSNiE.state = {
	page: null,
	uri: null,
	params: null,
	user: null,
	hrefs: [],
	access: true,
	error: false,
	action: {
		show: null,
		hide: null,
		page: []
	}
};

SGSNiE.stack = {
	actions: [],
	lvl: 0,
	push: function(action) {
		var e = {action: action ? action : null};
		SGSNiE.stack.actions.push(e);
		SGSNiE.stack.lvl++;
		return function(action) {
			e.action = action;
		};
	},
	pop: function() {
		SGSNiE.stack.lvl--;
		if(SGSNiE.stack.lvl == 0) {
			var a = SGSNiE.stack.actions;
			SGSNiE.stack.actions = [];
			for(var i=0; i < a.length; i++) {
				if(a[i].action != null) {
					a[i].action();
				}
			}
		}
	},
	reset: function() {
		SGSNiE.stack.lvl = 0;
		SGSNiE.stack.actions = [];
	}
};

SGSNiE.openPage = function(page,refresh) {
	var func = SGSNiE.handler.page[page];
	if(func) {
		func(page,refresh);
	} else {
		window.location.href = '#' + page;
		SGSNiE.action.page(page,refresh);
	}
};

SGSNiE.util = {
	parseAnchor: function(anchor) {
		var d = anchor.split(":");
		var result = {uri: anchor,
				page: d.length > 0 ? d[0] : SGSNiE.consts.PAGE_DEFAULT,
				params: d.length > 1 ? {} : null};
		for(var i=1; i < d.length; i++) {
			result.params["p" + i] = d[i];
		}
		return result;
	},
	parseState: function() {
		if(SGSNiE.state.user != null) {
			var u = SGSNiE.state.user;
			return {userId: u.id, userClass: u.javaClass.substring(u.javaClass.lastIndexOf(".") + 1)};
		}
		return null;
	},
	mergeQuery: function(q1,q2) {
		if(q1 == null) {
			return q2;
		} else if(q2 != null) {
			var r = {};
			for(var m in q1) {
				r[m] = q1[m];
			}
			for(var m in q2) {
				r[m] = q2[m];
			}
			return r;
		}
		return q1;
	}
};

SGSNiE.action = {};

SGSNiE.action.processState = function() {
	if(SGSNiE.state.page == null) {
		SGSNiE.action.page($.url.attr("anchor"));
	}
};

SGSNiE.action.proccessHref = function(p,node) {
	if(SGSNiE.user.action && SGSNiE.user.action.proccessHref) {
		SGSNiE.user.action.proccessHref(p,node);
	}
	var init = SGSNiE.state.hrefs.length == 0;
	$(SGSNiE.state.hrefs).each(function() {
		this[1].fadeOut(SGSNiE.consts.PAGE_SLIDE_TIME);
	});
	SGSNiE.state.hrefs = [];
	$("a[href^=#]",node).each(function() {
		var a = $(this);
		var img = $("img",a);
		if(img.length == 2) {
			var img1 = $(img[0]);
			var img2 = $(img[1]);
			var imgParent = img1.parent();
			imgParent.unbind("mouseenter").unbind("mouseleave");

			var page = a.attr("href").substring(1);
			if(!p || p.uri == page) {
				if(init) {
					img2.show();
				} else {
					img2.fadeTo(SGSNiE.consts.PAGE_SLIDE_TIME,1);
				}
				SGSNiE.state.hrefs.push([img1,img2]);
			} else {
				imgParent
					.mouseenter(function() {
						img2.clearQueue().fadeTo(SGSNiE.consts.PAGE_FADE_TIME,0.5);
					}).mouseleave(function() {
						img2.clearQueue().fadeOut(SGSNiE.consts.PAGE_FADE_TIME,function() {
							img2.css("opacity","1");
						});
					});
			}
		}
	});
};

SGSNiE.action.page = function(page,refresh) {
	if(typeof(page) == "undefined" || page == null || page == "") {
		page = SGSNiE.consts.PAGE_DEFAULT;
	}
	var params = SGSNiE.util.parseState();
	var p = SGSNiE.util.parseAnchor(page);
	params = SGSNiE.util.mergeQuery(params, p.params);
	params = SGSNiE.util.mergeQuery(params, {page: p.page});
	if(SGSNiE.state.uri != p.uri || refresh) {
		var scriptUri = "scripts/page/" + p.page + ".js";

		SGSNiE.action.proccessHref(p);

		var node = $("#content");
		var nodes = $("#content,#content2");

		var newNode = $("<div>").attr("id","content").addClass(node.attr("class")).hide();
		SGSNiE.stack.push(function() {
			nodes.empty();
		});
		SGSNiE.stack.push(function() {
			node.replaceWith(newNode);
			node = newNode;
			SGSNiE.state.uri = p.uri;
			SGSNiE.state.page = p.page;
			SGSNiE.state.params = p.params;
			SGSNiE.navigate.capture(node);
			SGSNiE.state.access = true;
			for(var i=1; i < nodes.length; i++) {
				var addNode = $("#contAdd" + 1,node);
				$(nodes[i]).append(addNode.contents()).hide();
				addNode.remove();
			}
		});
		var scrAction = SGSNiE.stack.push();

		if(SGSNiE.state.page != null) {
			if(SGSNiE.state.action.hide == null || SGSNiE.state.action.hide.length == 0) {
				SGSNiE.state.action.hide = [];
				SGSNiE.state.action.hide.push(function(nodes,cf) {
					for(var i=0; i < nodes.length; i++) {
						$(nodes[i]).fadeOut(SGSNiE.state.page == null ? 0 : SGSNiE.consts.PAGE_FADE_TIME,
								i == 0 ? cf : undefined);
					}
				});
			}
			for(var i=0; i < SGSNiE.state.action.show.length; i++) {
				SGSNiE.state.action.hide[i](nodes,SGSNiE.stack.pop);
			}
			SGSNiE.state.action.hide = [];
		} else {
			SGSNiE.stack.pop();
		}
		if(SGSNiE.user.action && SGSNiE.user.action.hide) {
			SGSNiE.user.action.hide(p.page);
		}

		$(SGSNiE.state.action.page).each(function() {
			this(p);
		});

		newNode.load("page/" + p.page + ".jsp", params, SGSNiE.stack.pop);
		SGSNiE.state.action.show = [];
		var prevPage = SGSNiE.state.page;
		SGSNiE.state.action.show.push(function(node) {
			SGSNiE.action.state();
			$("#content,#content2").fadeIn(prevPage == null && false ? 0 : SGSNiE.consts.PAGE_FADE_TIME);
		});
		$.ajax({url: scriptUri, dataType: "text",
			complete: function() {
				SGSNiE.stack.push(function() {
					SGSNiE.stack.push(function() {
						if(SGSNiE.state.access) {
							for(var i=0; i < SGSNiE.state.action.show.length; i++) {
								SGSNiE.state.action.show[i](newNode);
							}
							if(SGSNiE.user.action && SGSNiE.user.action.show) {
								SGSNiE.user.action.show(newNode);
							}
						}
					});
					SGSNiE.stack.pop();
				});
				SGSNiE.stack.pop();
				SGSNiE.stack.pop();
			},
			success: function(data, textStatus, XMLHttpRequest) {
				scrAction(function() {
					$.globalEval(data);
				});
			}
		});
	}
};

SGSNiE.action.state = function() {
	var state = SGSNiE.util.parseState();
	/*
	var wm = $("#weekModa");
	var wmCls = wm.attr("class");
	if(!SGSNiE.state.page || SGSNiE.state.page == SGSNiE.consts.PAGE_DEFAULT || SGSNiE.state.page == "super") {
		if(wmCls != "week") {
			wm.attr("class","week");
			$("img",wm).fadeIn(SGSNiE.consts.PAGE_FADE_TIME);
		}
	} else if(wmCls != "h50") {
		wm.attr("class","h50");
		$("img",wm).hide();
	}
	*/
};

SGSNiE.login = {
	form: {
		toggle: function() {
			if(SGSNiE.state.user != null) {
				if(SGSNiE.state.page == "private") {
					SGSNiE.handle.call(function() {
						SGSNiE.jsonrpc.registrationservice.logout(SGSNiE.handle.cb(function(result) {
							if(result.hasErrors) {
								alert("Не удалось выполнить выход.");
							} else {
								SGSNiE.connect();
								SGSNiE.openPage("main");
							}
						}));
					});
				} else {
					SGSNiE.openPage("private");
				}
			} else {
				$(".enter").fadeToggle(SGSNiE.consts.PAGE_FADE_TIME);
			}
		},
		hide: function() {
			$(".enter").fadeOut(SGSNiE.consts.PAGE_FADE_TIME,function() {
				$(".enter input").val("");
			});
		}
	}
};

SGSNiE.action.login = function() {
	/*
	var state = $("#lTitle").css("display") == "none";
	var flag = false;
	if(SGSNiE.state.user != null && state) {
		$("#lTitle").text(SGSNiE.state.user.title).show();
		$(".lkform").hide();
		$("#lLinks a:nth(0)").attr("href","#edit_info").text("Поменять данные");
		$("#lLinks a:nth(1)").attr("href","logout.htm").text("Выход");
		var u = SGSNiE.util.parseState();
		if(u.userClass == "Specialist") {
			$("#navMenu tbody:nth(0)").hide();
			$("#navMenu tbody:nth(1)").show();
		} else {
			$("#navMenu tbody:nth(0)").show();
			$("#navMenu tbody:nth(1)").hide();
		}
		$("#navMenu tbody:nth(2)").hide();
		flag = true;
	} else if (!state) {
		$("#lTitle").hide();
		$(".lkform").show();
		$("#lLinks a:nth(0)").attr("href","#restore_password").text("Забыли пароль?");
		$("#lLinks a:nth(1)").attr("href","#registration").text("Регистрация");
		$("#navMenu tbody:nth(0)").hide();
		$("#navMenu tbody:nth(1)").hide();
		$("#navMenu tbody:nth(2)").show();
		flag = true;
	}
	$("#navLogin").fadeOut($("#navLogin").css("display") == "none" ? 0 : SGSNiE.consts.PAGE_FADE_TIME, function() {
		$(this).fadeIn(SGSNiE.consts.PAGE_FADE_TIME);
	});
	$("#navMenu").fadeOut($("#navMenu").css("display") == "none" ? 0 : SGSNiE.consts.PAGE_FADE_TIME, function() {
		$(this).fadeIn(SGSNiE.consts.PAGE_FADE_TIME);
	});
	*/
};

SGSNiE.action.click = function(event) {
	var href = $(this).attr("href");
	var page = href.substring(href.indexOf("#") + 1);
	var func = SGSNiE.handler.page[page];
	if(func) {
		func(page);
		event.preventDefault();
	} else {
		SGSNiE.action.page(page);
	}
};

SGSNiE.list = {
	state: {
		filter: null,
		sort: null,
		pagelist: null
	},
	makeHref: function(srt,list) {
		return SGSNiE.state.page;// + ":" + srt.fieldName + ":" + (srt.desc ? 0 : 1) + (list == 1 ? "" : ":" + list);
	},
	sort: {
		imgMap: {
			0: {
				0: "img/st1.png",
				1: "img/st2.png"
			},
			1: {
				0: "img/sb1.png",
				1: "img/sb2.png"
			}
		},
		fill: function(items,map) {
			items.each(function(i) {
				if(map[i]) {
					var c = $(this);
					var txt = c.html();
					if(txt.indexOf("<") != 0) {
						var idPrefix = "sort:" + map[i];
						var tbl = $("<table/>").addClass("sort2");
						var up = $("<img/>").attr("src",SGSNiE.list.sort.imgMap[0][0]).attr("alt",txt + ", по возрастанию");
						up.attr("title",up.attr("alt")).attr("id",idPrefix + ":0");
						var down = $("<img/>").attr("src",SGSNiE.list.sort.imgMap[1][0]).attr("alt",txt + ", по убыванию");
						down.attr("title",up.attr("alt")).attr("id",idPrefix + ":1");
						tbl.append($("<td/>").append(txt)).append($("<td/>")
							.append($("<div/>").append(up).append("<br/>").append(down)));
						c.empty().append(tbl);
						c.html(c.html());
					}
				}
			});
		}
	},
	process: function(srt,pi,click) {
		SGSNiE.list.state.sort = srt;
		SGSNiE.list.state.pagelist = pi;
		SGSNiE.list.processPL(srt, pi, click);
		SGSNiE.list.processSort(srt, pi, click);
	},
	processPL: function(srt,pi,click) {
		var po = $("#pagelist");
		po.empty();
		if(pi != null && pi.pagesCount > 1) {
			var poi;
			var cur;
			for(var i=0; i < pi.pagesCount; i++) {
				cur = pi.currentPage == i;
				if(i == 0) {
					poi = $("<a/>").html("<img src=\"images/buttons/prev.png\" alt=\"prev\" />");
					poi.attr("href","#" + SGSNiE.list.makeHref(srt, i + 1)).click(function(event) {
						event.preventDefault();
						if(pi.currentPage > 0) {
							pi.currentPage--;
							click(srt,pi);
						}
					});
					if(cur) poi.css("cursor","default").css("opacity","0.4");
					po.append(poi);
				}
				poi = $(cur ? "<strong/>" : "<a/>").text(i + 1);
				if(!cur) {
					poi.attr("href","#" + SGSNiE.list.makeHref(srt, i + 1)).click(function(event) {
						event.preventDefault();
						var list = parseInt($(this).text());
						pi.currentPage = list - 1;
						click(srt,pi);
					});
				}
				po.append(" ");
				po.append(poi);
				po.append(" ");
				if(i == pi.pagesCount - 1) {
					poi = $("<a/>").html("<img src=\"images/buttons/next.png\" alt=\"next\" />");
					poi.attr("href","#" + SGSNiE.list.makeHref(srt, i + 1)).click(function(event) {
						if(pi.currentPage < pi.pagesCount - 1) {
							pi.currentPage++;
							click(srt,pi);
						}
					});
					if(cur) poi.css("cursor","default").css("opacity","0.4");
					po.append(poi);
				}
			}
		}
	},
	processSort: function(srt,pi,click) {
		var parseId = function(id) {
			var fd = id.substring(5);
			var pos = fd.indexOf(":");
			return {fieldName:  fd.substring(0,pos), desc: parseInt(fd.substring(pos + 1)) == 1 ? true : false};
		};
		$("[id^=sort]",$("#sort")).unbind().css("text-decoration","underline").css("cursor","pointer").click(function(event) {
			var fd = parseId($(this).attr("id"));
			srt.fieldName = fd.fieldName;
			srt.desc = fd.desc;
			click(srt,pi);
		});
		var d = srt.desc ? 1 : 0;
		$("[id=\"sort:" + srt.fieldName + ":" + d + "\"]",$("#sort")).unbind().css("text-decoration","none").css("cursor","");
	},
	init: {
		filters: function(handleSubmit, handleSuccess) {
			SGSNiE.form.init(
				function(cb,data) {
					var m = data.map;
					for(var key in m) {
						if(!m[key] || m[key] == "") {
							delete m[key];
						}
					}
					SGSNiE.list.state.filter = data;
					if(data.map.pageSize && data.map.pageSize > -1) {
						SGSNiE.list.state.pagelist.pageSize = data.map.pageSize;
						delete data.map.pageSize;
					}
					handleSubmit(cb);
				},
				handleSuccess,
				$("#filters")
			);
		}
	}
};

SGSNiE.form = {
	handle: {
		validate: function(result) {
			if(result.notValidFields != null) {
				var list = result.notValidFields.list;
				var map = {};
				for(var i=0; i < list.length; i++) {
					map[list[i].name] = list[i];
					if(list[i].jobId) {
						map["job" + list[i].jobId] = list[i];
					}
				}
				SGSNiE.form.iterate(function() {
					var item = $(this).parent().prev("td");
					if(item.length == 0) {
						item = $(this).prev("p");
					}
					item.css("color",map[$(this).attr("name")] ? "red" : "");
				});
				SGSNiE.form.jobs.iterate(function(name,txt) {
					txt.css("color",map[name] ? "red" : "");
				});
			}
		},
		message: function(result,textHtml,node) {
			var msg = result.message ? result.message : "";
			var i = $("#info",node);
			var c = $("#infoCont",node);
			if(i.length == 0) {
				 i = $("#info");
				 c = $("#infoCont");
			}
			if(c.length == 0) {
				c = i;
			}
			if(i.length > 0) {
				c.fadeOut(i.text() ? SGSNiE.consts.PAGE_FADE_TIME : 0, function() {
					i.text(msg).css("color", result.hasErrors ? "" : "white");
					c.fadeIn(SGSNiE.consts.PAGE_FADE_TIME);
				});
				var t = $("#infoText",node);
				if(t.length == 0) {
					 t = $("#infoText");
				}
				t.fadeOut(t.html() ? SGSNiE.consts.PAGE_FADE_TIME : 0, function() {
					t.html(textHtml ? textHtml : "").fadeIn(SGSNiE.consts.PAGE_FADE_TIME);
					if(t.html()) {
						SGSNiE.navigate.capture(t);
					}
				});
				if(msg != "") {
					//$("html").animate({scrollTop:i.position().top - 10}, SGSNiE.consts.PAGE_SCROLL_TIME);
				}
			}
		},
		all: function(result,node) {
			SGSNiE.form.handle.message(result,null,node);
			SGSNiE.form.handle.validate(result);
		}
	},
	findNodes: function() {
		return $("table.data,#form,.uform");
	},
	findAndIerate: function(node,func,all) {
		$(node).find(":input[name]" + (all ? "" : ":enabled")).each(func);
	},
	iterate: function(func,all) {
		SGSNiE.form.findAndIerate(SGSNiE.form.findNodes(),func,all);
	},
	toJSON: function(selector) {
	    var form = {};
	    SGSNiE.form.findAndIerate(selector,function() {
	        var self = $(this);
	        var name = self.attr('name');
	        var val = self.attr("type") == "radio" ? (self.is(":checked") ? self.val().trim() : "")
	        		: (self.val() == self.attr("defaultValue") ? "" : self.val().trim());
	        if (form[name]) {
	        	if(val) {
	        		form[name] = form[name] + ',' + val;
	        	}
	        }
	        else {
	           form[name] = val;
	        }
	    });
	    return form;
	},
	toJSONMap: function(selector) {
	    var map = SGSNiE.form.toJSON(selector);
	    return {javaClass: "java.util.HashMap", map: map};
	},
	initChecks: function() {
		$("#loginCheck").unbind().click(function(event) {
			var val = $("input[name=login]",SGSNiE.form.findNodes()).val();
			if(val == null || val == "") {
				SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Вы не указали логин"});
			} else {
				SGSNiE.handle.call(function() {
					SGSNiE.jsonrpc.registrationservice.isUserExist(SGSNiE.handle.cb(function(result){
						result.hasErrors = result.result;
						result.message = result.result ? "Логин уже используется" : "Логин свободен";
						SGSNiE.form.handle.message(result);
					}),val);
				});
			}
			event.preventDefault();
		});
	},
	format: {
		data: {
			inn10: [2,4,10,3,5,9,4,6,8],
			inn121: [7,2,4,10,3,5,9,4,6,8],
			inn122: [3,7,2,4,10,3,5,9,4,6,8]
		},
		checkInt: function(v,l,t,node) {
			var r = true;
			if(v != null && (v = v.trim()) != "") {
				r &= v.match(/^\d+$/) != null;
				if(r && l) {
					if(typeof(l.length) != "undefined") {
						var rl = false;
						for(var i=0; i < l.length && !rl; i++) {
							rl |= v.length == l[i];
						}
						r &= rl;
					} else {
						r &= v.length == l;
					}
				}
			}
			if(!r) {
				SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Не правильный формат " + t},null,node);
			}
			return r;
		},
		checkCRC: function(v,c) {
			var r = 0;
			var i;
			if(c) {
				for(i=0, r=0; i < c.length; i++) {
					r += parseInt(v.charAt(i))*c[i];
				}
				return parseInt(v.charAt(i)) == r%11%10;
			} else {
				var off = 1;
				for(var off=1;off <= 3;off += 2) {
					for(i=0, r=0; i < v.length - 1; i++) {
						r += parseInt(v.charAt(i))*(i+off);
					}
					if(off == 1 && r%11 == 10) {
						continue;
					}
					return parseInt(v.charAt(i)) == r%11%10;
				}
			}
		},
		checkers: {
			inn: function(v,node) {
				if(v != null && (v = v.trim()) != "") {
					if(!SGSNiE.form.format.checkInt(v, [10,12], "ИНН", node)) {
						return false;
					} else if(v.length == 10) {
						if(!SGSNiE.form.format.checkCRC(v, SGSNiE.form.format.data.inn10)) {
							SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Не совпадает проверочный код ИНН"},null,node);
							return false;
						}
					} else if(v.length == 12) {
						var r = 0;
						var i;
						var cs = [SGSNiE.form.format.data.inn121,SGSNiE.form.format.data.inn122];
						for(var j=0; j < cs.length; j++) {
							if(!SGSNiE.form.format.checkCRC(v, cs[j])) {
								SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Не совпадает проверочный код ИНН"},null,node);
								return false;
							}
						}
					}
				}
				return true;
			},
			okpo: function(v,node) {
				if(v != null && (v = v.trim()) != "") {
					if(!SGSNiE.form.format.checkInt(v, null, "ОКПО", node)) {
						return false;
					} else {
						if(!SGSNiE.form.format.checkCRC(v)) {
							SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Не совпадает проверочный код ОКПО"},null,node);
							return false;
						}
					}
				}
				return true;
			},
			kpp: function(v,node) {
				if(v != null && (v = v.trim()) != "") {
					if(!SGSNiE.form.format.checkInt(v, 9, "КПП", node)) {
						return false;
					}
				}
				return true;
			},
			email: function(v,node) {
				if(v != null && (v = v.trim()) != "") {
					if(!v.match(/^[0-9a-zA-Z._\-]+@[0-9a-zA-Z_\-]+(\.\w+)+$/)) {
						SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Не правильно указан E-Mail"},null,node);
						return false;
					}
				}
				return true;
			}
		}

	},
	check: function(data,node) {
		var m = data.map;
		if(typeof(m.login) != "undefined" && m.login == "") {
			SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Вы не указали логин"},null,node);
			return false;
		}
		if(typeof(m.pass) != "undefined" && typeof(m.pass2) != "undefined" && m.pass != m.pass2) {
			SGSNiE.form.handle.message({result: false, hasErrors: true, message:"Указанные пароли не совпадают"},null,node);
			return false;
		}
		for(var f in m) {
			var ch = SGSNiE.form.format.checkers[f];
			if(ch) {
				if(!ch(m[f],node)) {
					return false;
				}
			}
		}
		return true;
	},
	initDefaults: function(node) {
		var node = typeof(node) == "undefined" ? SGSNiE.form.findNodes() : node;
		var inpts = $(node).find(":input[type=text]:enabled, textarea:enabled");
		inpts.focus(function(event) {
			var inp = $(this);
			if(inp.attr("defaultValue") == inp.val()) {
				if(inp.attr("name").indexOf("pass") == 0) {
					//inp.attr("type","password");
				}
				inp.val("");
			}
		});
		inpts.blur(function(event) {
			var inp = $(this);
			if(!inp.val()) {
				if(inp.attr("name").indexOf("pass") == 0) {
					//inp.attr("type","text");
				}
				inp.val(inp.attr("defaultValue"));
			}
		});
	},
	init: function(handleSubmit, handleSuccess, handleError, node) {
		var node = typeof(node) == "undefined" ? (typeof(handleError) == "function" || typeof(handleError) == "undefined" ? SGSNiE.form.findNodes() : handleError) : node;
		var handleError = typeof(handleError) == "function" ? handleError : function(result,node) {
			SGSNiE.captcha.next(node);
			SGSNiE.form.handle.all(result,node);
		};
		var form = node.is("form") ? node : $("form",node);
		form.submit(function(event) {
			event.preventDefault();
			event.stopPropagation();
		});

		var btns = $("input:submit, input:image",node);
		var submitFunc = function(event) {
			var data = node.formToJSONMap();
			var extData = {
				jobs: SGSNiE.form.jobs.getJSONList()
			};
			if(SGSNiE.form.check(data, node)) {
				btns.attr("disabled", "disabled").css("color","grey").fadeTo("fast",0.4);
				var afterCall = function() {
					btns.css("color","").removeAttr("disabled").fadeTo("fast",1);
				};
				SGSNiE.handle.call(function() {
					var r = handleSubmit(SGSNiE.handle.cb(function(result) {
						if(result.hasErrors) {
							handleError(result,node);
						} else {
							handleSuccess(result,node);
						}
						afterCall();
					}),data,extData);
					if(typeof(r) != "undefined" && r) {
						afterCall();
					}
				});
			}
			event.preventDefault();
		};
		btns.click(submitFunc);
		if(node.is("form")) {
			node.submit(submitFunc);
		}
		SGSNiE.form.upload.init();
	},
	fill: function(formData, readOnly) {
		SGSNiE.form.iterate(function() {
			var self = $(this);
			var attrName = self.attr("name");
			var attrNameSub = null;
			var pos = self.attr("name").indexOf(":");
			if(pos > -1) {
				attrNameSub = attrName.substring(pos + 1);
				attrName = attrName.substring(0,pos);
			}

			var v = formData[attrName];
			if(v && attrNameSub) {
				v = v[attrNameSub];
			}
			if(typeof(v) == "undefined" || v == null) {
				v = "";
			}
			if(typeof(v.javaClass) != "undefined") {
				switch(v.javaClass) {
					case "java.util.Date":
						v = new Date(v.time).format("d.m.Y");
					break;
					default:
						v = v.name ? v.name : "";
					break;
				}
			}
			if(readOnly) {
				self.replaceWith("<pre>" + v + "</pre>");
			} else {
				if(self.attr("type") == "select-one") {
					if(v) {
						$("option",self).removeAttr("selected");
						$("option[value='" + v + "']",self).attr("selected","selected");
					}
				} else if(self.attr("type") == "radio") {
					if(self.val() == v) {
						self.attr("checked","checked");
					} else {
						self.removeAttr("checked");
					}
				} else if(self.attr("type") != "password" && self.attr("name").indexOf("pass") != 0) {
					self.val(v);
				}
			}
		},true);
	},
	upload: {
		id: null,
		action: {
			remove: function(guid, queueID, event) {
				event.preventDefault();
				SGSNiE.handle.call(function() {
					SGSNiE.jsonrpc.documentservice.deleteFile(SGSNiE.handle.cb(function(result) {
						SGSNiE.form.handle.message(result);
						if(!result.hasErrors) {
							SGSNiE.form.handle.message(result);
							$("#uploadify" + queueID).fadeOut(SGSNiE.consts.PAGE_FADE_TIME).remove();
						}
					}),guid,SGSNiE.form.upload.id);
				});
			}
		},
		errors: {
			"File Size": "Превышен максимальный размер файла"
		},
		fill: function(data,readOnly) {
			var l = $("#fileQueue");
			$(data).each(function() {
				var f = this;
				var item = $("<div/>").attr("id","uploadify" + f.id).addClass("uploadifyQueueItem");
				if(!readOnly) {
					item.append($("<div/>").addClass("cancel")
						.append($("<a><img src=\"upload/cancel.png\" border=\"0\"/></a>").attr("href","").click(function(event) {
							SGSNiE.form.upload.action.remove(f.guid, f.id, event);
						})));
				}
				item.append($("<span/>").addClass("fileName").text(f.fileName + " (" + Math.round(f.size/1024) + "Кб)"));
				l.append(item);
			});
		},
		init: function() {
			var upl = $("#uploadify");
			if(upl.length == 0) {
				return;
			}
			SGSNiE.form.upload.id = Math.uuid();
			upl.uploadify({
				uploader		: 'scripts/upload/uploadify.swf',
				expressInstall 	: 'scripts/upload/expressInstall.swf',
				script			: 'upload-file.htm?jsessionid=' + $.cookie.get("JSESSIONID"),
				cancelImg		: 'upload/cancel.png',
				queueID			: 'fileQueue',
				scriptData		: {uploadId: SGSNiE.form.upload.id},
				auto			: true,
				multi			: true,
				buttonImg		: 'upload/upload.png',
				width			: 140,
				height			: 26,
				wmode			: 'transparent',
				fileExt     	: '*.txt;*.doc;*.docx;*.rtf;*.pdf;*.xls;*.xlsx;*.cad;*.jpg;*.png;*.vsd',
				fileDesc    	: 'Документы и изображения',
				onComplete		: function(event, queueID, fileObj, response, data) {
					var res = $.parseJSON(response);
					$("#uploadify" + queueID + " .cancel a").click(function(event) {
						SGSNiE.form.upload.action.remove(res.guid, queueID, event);
					});
					return false;
				},
				onError			: function(event, queueID, fileObj, errorObj) {
					if(SGSNiE.form.upload.errors[errorObj.type]) {
						errorObj.type = errors[errorObj.type];
					}
				}
			});
		}
	},
	dynamic: {
		clean: function() {
			SGSNiE.form.dynamic.state.clients = [];
		},
		fill: function(fields,data,readOnly) {
			SGSNiE.form.dynamic.clean();
			var p = $("#props");
			var l = fields;
			for(var i=0; i < l.length; i++) {
				var v = data && data[l[i].codeName] ? data[l[i].codeName].value : null;
				if(readOnly) {
					SGSNiE.form.dynamic.handle.base.show(p,l[i],v);
				} else {
					var f = SGSNiE.form.dynamic.handle.type[l[i].type.name.toLowerCase()];
					if(f) {
						f(p,l[i],v);
					} else {
						alert("Не найден обработчик для поля '" + l[i].name + "'(" + l[i].type.name.toLowerCase() + ")");
					}
				}
			}
			SGSNiE.form.dynamic.init();
		},
		init: function() {
			if(SGSNiE.form.dynamic.state.clients.length > 0) {
				SGSNiE.jsonrpc.userservice.getClients(SGSNiE.handle.cb(function(result) {
                    var l = result.result.list;
                    var c = SGSNiE.form.dynamic.state.clients;

                    var txt = "<option/>";
                    for(var i=0; i < l.length; i++) {
                    	txt = txt + "<option value=\""+ l[i].id + "\">" + l[i].title + "</option>";
                    }

                    var esel = $("<select/>").html(txt);
                    for(var j=0; j < c.length; j++) {
                    	var sel = c[j];
                    	var nsel = esel.clone()
	                    	.attr("name",sel.attr("name"))
	                    	.attr("id",sel.attr("id"))
	                    	.addClass(sel.attr("class"))
	                    	.val(sel.val());
                    	sel.unbind().replaceWith(nsel);
                    	c[j] = nsel;
                    }
				},false));

				var o = $("#addOrg");
				$("input:button:nth(0)",o).click(function(event) {
					o.hide();
				});
				$("input:button:nth(1)",o).click(function(event) {
					SGSNiE.handle.call(function() {
						var name = $("input[name=org:name]",o).val();
						var inn = $("input[name=org:inn]",o).val();
						SGSNiE.jsonrpc.userservice.createLegalPersonUser(SGSNiE.handle.cb(function(result) {
							if(!result.hasErrors && result.result) {
								var u = result.result;
								o.hide();
								var l = SGSNiE.form.dynamic.state.clients;
								for(var i=0; i < l.length; i++) {
									l[i].append($("<option/>").val(u.id).text(u.title));
								}
							}
							SGSNiE.form.handle.message(result);
						}),name,inn);
					});
				});
			}
		},
		state: {
			clients: []
		},
		handle: {
			base: {
				title: function(p,f) {
					p.append($("<p>" + f.name + (f.comment ? " <span>(" + f.comment + ")</span>" : "") + ":</p>"));
				},
				show: function(p,f,v) {
					SGSNiE.form.dynamic.handle.base.title(p,f);
					if(v && f.fieldEnums != null) {
						var l = f.fieldEnums.list;
						for(var i=0; i < l.length; i++) {
							if(v && v == l[i].id) {
								v = l[i].value;
							}
						}
					}
					if(v == null) {
						v = "";
					} else if(v.time) {
						v = new Date(v.time).format("d.m.Y");
					}
					p.append($("<div/>").append($("<pre/>").text(v)));
				},
				simple: function(p,f,v,cls) {
					SGSNiE.form.dynamic.handle.base.title(p,f);
					var inp = $("<input/>").addClass(cls).attr("type","text").attr("name",f.codeName);
					if(v) {
						inp.attr("value",v);
					}
					p.append(inp);
					return inp;
				},
				select: function(p,f,v,cls) {
					SGSNiE.form.dynamic.handle.base.title(p,f);
					var sel = $("<select/>").addClass(cls).attr("name",f.codeName);
					if(f.fieldEnums != null) {
						var l = f.fieldEnums.list;
						sel.append("<option/>");
						for(var i=0; i < l.length; i++) {
							sel.append($("<option/>").attr("value",l[i].id).text(l[i].value));
						}
						if(v) {
							sel.val(v);
						}
					}
					p.append(sel);
					return sel;
				},
				choose: function(p,f,v,cls) {
					if(f.fieldEnums != null && f.fieldEnums.list.length > 0) {
						SGSNiE.form.dynamic.handle.base.select(p,f,v,cls);
					} else {
						SGSNiE.form.dynamic.handle.base.simple(p,f,v,cls);
					}
				}
			},
			type: {
				float: function(p,f,v) {
					SGSNiE.form.dynamic.handle.base.choose(p,f,v,"inp4");
				},
				integer: function(p,f,v) {
					SGSNiE.form.dynamic.handle.base.choose(p,f,v,"inp4");
				},
				string: function(p,f,v) {
					SGSNiE.form.dynamic.handle.base.choose(p,f,v,"inp5");
				},
				date: function(p,f,v) {
					if(v) {
						v = new Date(v.time).format("d.m.Y");
					}
					SGSNiE.form.dynamic.handle.base.simple(p,f,v,"inp4").datepicker({
						changeMonth: true,
						changeYear: true
					});
				},
				text: function(p,f,v) {
					SGSNiE.form.dynamic.handle.base.title(p,f);
					var inp = $("<textarea/>").addClass("prich").attr("rows","6").attr("name",f.codeName);
					if(v) {
						inp.text(v);
					}
					p.append(inp);
					return inp;
				},
				link_to_client: function(p,f,v) {
					if(v) {
						f.fieldEnums = {list: [{
							id: v.id,
							value: v.title
						}]};
						v = v.id;
					}
					var sel = SGSNiE.form.dynamic.handle.base.select(p,f,v,"s1");
					SGSNiE.form.dynamic.state.clients.push(sel);
					sel.click(function(event) {
						alert("Перечень организаций загружается.\r\nПожалуста подождите.");
						event.preventDefault();
						return false;
					});
					p.append($("<br />"));
					p.append($("<a/>").attr("href","").text("Отсутствует в списке.").click(function(event) {
						$("#addOrg").insertAfter(this).show();
						event.preventDefault();
					}));
				}
			}
		}
	},
	jobs: {
		iterate: function(func) {
			var tbl = $("#jobs tbody");
			$("tr",tbl).each(function() {
				func($(this).attr("id"),$("td:nth(0)",this),$("select",this),$("input",this));
			});
		},
		fill: function(jobs, data, readOnly) {
			if(jobs.length > 0) {
				var tbl = $("#jobs tbody");
				var l = jobs;
				var pers = $("<select/>").addClass("s2");//.attr("name","persent");
				for(var i=0; i <= 100; i++) {
					pers.append($("<option/>").val(i).text(i));
				}
				for(var i=0; i < l.length; i++) {
					var v = data && data[l[i].id] ? data[l[i].id] : null;
					var inpPers = readOnly ? $("<pre/>") : pers.clone();
					var inpCmt = readOnly ? $("<pre/>") : $("<input/>").addClass("inp5");
					if(v) {
						if(readOnly) {
							inpCmt.text(v.comment == null ? "" : v.comment);
							inpPers.text(v.percent);
						} else {
							inpCmt.val(v.comment == null ? "" : v.comment);
							inpPers.val(v.percent);
						}
					}
					tbl.append($("<tr>").attr("id","job" + l[i].id).append($("<td/>").addClass("f").text(l[i].name))
						.append($("<td/>").append(inpPers))
						.append($("<td/>").append(inpCmt))
					);

				}
				pers.remove();
				$("#jobs").show();
			}
		},
		getJSONList: function() {
			var r = {
				javaClass: "java.util.ArrayList",
				list: []
			};
			$("#jobs tbody tr").each(function() {
				var self = $(this);
				r.list.push({
					javaClass: "com.sastasoft.sgsnie.jpa.model.SimpleJobValue",
					jobId: self.attr("id").substring(3),
					percent: $("select",self).val(),
					comment: $("input",self).val()
				});
			});
			return r.list.length == 0 ? null : r;
		}

	}
};

SGSNiE.captcha = {
	next: function(node) {
		$("input[name=captcha]", node).val("");
		$("#captcha", node).fadeTo(SGSNiE.consts.PAGE_FADE_TIME,0,function() {
			$(this).attr("src","img/captcha.jpg?" + new Date().getTime()).unbind().load(function() {
				$(this).fadeTo(SGSNiE.consts.PAGE_FADE_TIME,1);
			});
		});
	},
	init: function(node) {
		$("#captchaNext").unbind().click(function(event) {
			SGSNiE.captcha.next(node);
			event.preventDefault();
		});
	}
};

SGSNiE.navigate = {
	captureMenu: function() {
		$(".b-menu a > img").each(function(i) {
			var img1 = $(this);
			var src1 = img1.attr("src");
			var src2 = src1.substring(0,src1.length - 4) + "-a" + src1.substring(src1.length - 4);
			if(src1 != src2) {
				img1.parent().parent().css("position","relative");
				var pos = img1.position();
				var img2 = img1.clone();
				img2.attr("src",src2).css("position","absolute").css("display","none");
				img2.css("top",pos.top + (jQuery.browser.webkit ? -12 : 0)).css("left",pos.left);
				img2.insertAfter(img1);
			}
		});
	},
	capruteHref: function(node) {
		$("a[href*=#]",node).unbind().click(SGSNiE.action.click);
	},
	capture: function(node) {
		SGSNiE.navigate.capruteHref(node);
		if(!node) {
			SGSNiE.navigate.captureMenu();
		}
	}
};

$.fn.formToJSON = function() {
	return SGSNiE.form.toJSON(this);
};

$.fn.formToJSONMap = function() {
	return SGSNiE.form.toJSONMap(this);
};

//$.datepicker.setDefaults($.extend($.datepicker.regional["ru"]));



SGSNiE.user = {
	animate: {
		func: null,
		delay: 3500,
		state:  {
			alive: false,
			interupt: false
		},
		start: function() {
			if(SGSNiE.user.animate.state.alive) {
				SGSNiE.user.animate.state.interupt = false;
			} else {
				var whileFunc = function() {
					if(SGSNiE.user.animate.state.interupt) {
						SGSNiE.user.animate.state.alive = false;
						SGSNiE.user.animate.state.interupt = false;
					} else {
						if(SGSNiE.user.animate.func != null) {
							SGSNiE.user.animate.func();
						}
						setTimeout(whileFunc,SGSNiE.user.animate.delay);
					}
				};
				SGSNiE.user.animate.state.alive = true;
				setTimeout(whileFunc,SGSNiE.user.animate.delay);
			}

		},
		stop: function() {
			if(SGSNiE.user.animate.state.alive) {
				SGSNiE.user.animate.state.interupt = true;
			}
		}
	},
	makeUserHtml: function(user) {
		var html = user.name + " " + user.surname;
		if(user.city) {
			html = html + ", " + user.city.name;
		} else if(user.otherCity) {
			html = html + ", " + user.otherCity;
		}
		return html.toString();
	},

	fillUserData: function(user) {
		if(!user) {
			user = SGSNiE.state.user;
		}
		$("#udata").html(SGSNiE.user.makeUserHtml(user));
/*
		var comps = $(".b-comp-link");

		if(user.availableAttempts <= 0) {
			comps.unbind().css("opacity","0.4").attr("disabled","disabled").css("cursor","none").click(function(event) {
				event.preventDefault();
				alert("Вы уже создали историю");
			});
		}
*/
	},
	action: {
		init: function(user) {
			$(".b-welcome").text(user != null ? "Привет, " + user.name + "!" : "");
		},
		_hide: function(page) {
			var main = $(".b-main");
			if(page != "add_story" && page != "gallary" && page != "story")
				main.removeClass("b-gallery");
			if(page != "costs")
				main.removeClass("b-superceny");
		},
		show: function(node) {
			this._hide(SGSNiE.state.page);
			$(".scroll-pane,.scroll-panel,.b-scroll_panel",node).jScrollPane({showArrows:true,scrollbarWidth:18});
		},
		proccessHref: function() {
			var reg = $(".b-reg_link");
			var enter = $(".b-enter_link");
			if(SGSNiE.state.user == null) {
				reg.attr("href","#registration").html("Регистрация");
				enter.attr("href","#enter").html("вход <img src=\"./images/icons/enter.gif\" alt=\"\"/>");
			} else {
				reg.attr("href","#private").html("Личный кабинет");
				enter.attr("href","#exit").html("Выйти");
			}
		}

	},
	registration: function(node) {
		var cardHint = $("#hint-card");
		var chh = cardHint.css("height");
		var chp = cardHint.css("padding");
		$(".b-label-hint a").click(function(event) {
			event.preventDefault();
			cardHint.clearQueue().slideDown();
		}).mouseenter(function() {
			cardHint.clearQueue().slideDown();
		}).mouseleave(function() {
			cardHint.clearQueue().slideUp(function() {
				cardHint.css("height",chh).css("padding",chp);
			});
		});

		SGSNiE.handle.call(function() {
			SGSNiE.jsonrpc.registrationservice.isActionActive(SGSNiE.handle.cb(function(result) {
				if(result.hasErrors) {
					SGSNiE.action.state();
					$(".b-popup-content .clearfix",node).css("opacity","0.1");
					$("input,button",node).attr("disabled","disabled").css("cursor","default");
					var posNode = $(".b-popup-title",node);
					var pos = posNode.position();
					posNode.parent().append($("<h1 style=\"white-space: nowrap;\">Регистрация закрыта.<br/>" + result.message + ".</h1>").css("position","absolute")
						.css("z-index","100").css("top","150px").css("left",(pos.left + 210) + "px")
						.css("font-size","230%"));
				} else {
					var regNode = node;

					SGSNiE.captcha.init();
					SGSNiE.form.initChecks(regNode);
					SGSNiE.form.initDefaults(regNode);
					SGSNiE.form.init(
						function(cb,data) {
							SGSNiE.jsonrpc.registrationservice.createUser(cb,data,data.map.captcha);
						},
						function(result) {
							$(".b-popup-content .clearfix",regNode).fadeOut(SGSNiE.consts.PAGE_FADE_TIME, function() {
								var node = $(".b-popup-end",regNode);
								$("h2",node).text("Спасибо, " + $("input[name=name]",regNode).val() + "!");
								node.fadeIn(SGSNiE.consts.PAGE_FADE_TIME);

							});
						},
						null,
						regNode
					);

					var regBtn = $("input:image, input:submit",regNode);
					regBtn.attr("disabled","disabled").css("opacity","0.4").css("cursor","default");

					$("#accept").change(function() {
						if($(this).is(':checked')) {
							regBtn.css("cursor","pointer").removeAttr("disabled").fadeTo(SGSNiE.consts.PAGE_FADE_TIME,1);
						} else {
							regBtn.css("cursor","default").attr("disabled","disabled").fadeTo(SGSNiE.consts.PAGE_FADE_TIME,0.4);
						}
					});

					SGSNiE.jsonrpc.registrationservice.getCities(SGSNiE.handle.cb(function(result) {
						var inp = $("select[name='city:id']");
						var l = result.list;
				        var txt = "<option value=\"\">Ваш город</option>";
				        for(var i=0; i < l.length; i++) {
				        	txt = txt + "<option value=\""+ l[i].id + "\">" + l[i].name + "</option>";
				        }
				        inp.html(txt);
					}));

				}
			}));

		});
	},
	btns: new Object()
};


$(document).ready(function() {
	SGSNiE.connect();
	SGSNiE.navigate.capture();
	SGSNiE.action.processState();

	var regNode = $(".b-popup--reg");
	$(".b-close",regNode).click(function() {
		regNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
	});
	SGSNiE.handler.page["registration"] = function() {
		regNode.fadeToggle(SGSNiE.consts.PAGE_FADE_TIME);
		loginNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
		forgotNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
	};
	SGSNiE.user.registration(regNode);

	var loginNode = $("#loginForm");
	SGSNiE.handler.page["exit"] = function() {
		SGSNiE.handle.call(function() {
			SGSNiE.jsonrpc.registrationservice.logout(SGSNiE.handle.cb(function(result) {
				if(result.hasErrors) {
					alert("Ошибка выхода");
				} else {
					SGSNiE.connect();
					SGSNiE.openPage("main",true);
				}
			}));
		});

	};
	SGSNiE.handler.page["enter"] = function() {
		if(SGSNiE.state.user != null) {
			if(SGSNiE.state.page == "private") {
				SGSNiE.handle.call(function() {
					SGSNiE.jsonrpc.registrationservice.logout(SGSNiE.handle.cb(function(result) {
						if(result.hasErrors) {
							alert("Ошибка выхода");
						} else {
							SGSNiE.connect();
							SGSNiE.openPage("main");
						}
					}));
				});
			} else {
				SGSNiE.openPage("private");
			}
		} else {
			loginNode.fadeToggle(SGSNiE.consts.PAGE_FADE_TIME);
			regNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
			forgotNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
		}
	};

	var forgotNode = $("#forgotForm");
	SGSNiE.handler.page["restore_password"] = function() {
		forgotNode.fadeToggle(SGSNiE.consts.PAGE_FADE_TIME);
		regNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
		loginNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
	};

//	var privacyNode = $("#privacy_agreement");
//	var privacyFunc = function() {
//		privacyNode.fadeToggle(SGSNiE.consts.PAGE_FADE_TIME);
//	};
//	SGSNiE.handler.page["privacy_agreement"] = privacyFunc;
//	privacyNode.click(privacyFunc);
	SGSNiE.state.action.page.push(function(node) {
		regNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
		loginNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
		forgotNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
	});
	$(".b-close",loginNode).click(function() {
		loginNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
	});
	$(".b-close",forgotNode).click(function() {
		forgotNode.fadeOut(SGSNiE.consts.PAGE_FADE_TIME);
	});

	var loginForm = $("form.b-reg",loginNode);
	SGSNiE.form.init(
		function(cb,data) {
			SGSNiE.jsonrpc.registrationservice.login(cb,data.map.login,data.map.pass);
		},
		function(result) {
			if(SGSNiE.connect()) {
				loginForm.resetForm();
				SGSNiE.openPage("private",true);
			}
		},
		null,
		loginForm
	);
	SGSNiE.form.initDefaults(loginForm);

	var forgotForm = $("form.b-reg",forgotNode);
	SGSNiE.form.init(
		function(cb,data) {
			SGSNiE.jsonrpc.registrationservice.restorePassword(cb,data.map.email,null);
		},
		function(result,node) {
			SGSNiE.form.handle.message(result, null, node);
			$("#infoCont",node).hide();
			$("input",node).each(function() {
				var self = $(this);
				self.val(self.attr("defaultValue"));
			});
		},
		null,
		forgotNode
	);
	SGSNiE.form.initDefaults(forgotForm);
});
