var dbg = false;

screen.bufferDepth = -1;

/*if (!window.console || !console.firebug) {
	var names = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'];
	window.console = {};
	for (var i in names) window.console[names[i]] = function() {}
}*/

function $(id) {
	return document.getElementById(id);
}

function Int(str) {
	return (parseInt(str) + 0);
}

function Rnd(len) {
	return (Math.random() + '').substr(2, len ? len : 6);
}

function Log(str) {
	if (dbg) console.log(str);
}

function Dump(obj) {
	if (dbg) console.dir(obj);
}

var Is = {
	Set: function(v){return typeof(v) != 'undefined';},
	Str: function(v){return typeof(v) == 'string';},
	Num: function(v){return typeof(v) == 'number';},
	Obj: function(v){return typeof(v) == 'object' && v != null;},
	Func: function(v){return typeof(v) == 'function';}
}

function hasClass(obj, cName)
{
	if (!Is.Obj(obj) && !Is.Obj(obj = $(obj)))
		return false;
	var myregexp = new RegExp('([^\\w]{1,}?|^)' + cName + '([^\\w]{1,}?|$)', 'g');
	if (myregexp.exec(obj.className))
		return true;
	return false;
}

function addClass(obj, cName)
{
	//if (obj.className != cName && obj.className.indexOf(' ' + cName) == -1 && obj.className.indexOf(cName + ' ') == -1)
	if (!Is.Obj(obj) && !Is.Obj(obj = $(obj)))
		return false;
	if (!hasClass(obj, cName))
		obj.className += (' ' + cName);
}

function removeClass(obj, cName)
{
	if (!Is.Obj(obj) && !Is.Obj(obj = $(obj)))
		return false;
	var myregexp = new RegExp('([^\\w]{1,}?|^)' + cName + '([^\\w]{1,}?|$)', 'g');
	obj.className = obj.className.replace(myregexp, ' ');
	/*if (obj.className == cName || obj.className.indexOf(' ' + cName) > -1 || obj.className.indexOf(cName + ' ') > -1)
		widg.className = widg.className.replace(/ open/, '');*/
}

/**
 * функция по названию класса находит объекты внутри объекта parentObj или в переданном массиве объектов objs_array
*/
function findObjWithClassName(cName, parentObj, objs_array)
{
	if (!cName || cName == '' || (!objs_array && !parentObj) || (parentObj && !Is.Obj(parentObj) && !Is.Obj(parentObj = $(parentObj))))
		return null;
	var elements = [];
	var obj;
	var len;
	if (objs_array)
		len = objs_array.length;
	else
		len = parentObj.childNodes.length;
	for (var i = 0; i < len; i++)
	{
		if (objs_array)
			obj = objs_array[i];
		else
			obj = parentObj.childNodes[i];
		if (hasClass(obj, cName))
		{
			elements.push(obj);
		}
	}
	return elements;
}

function Redir(url) {
	location.href = url;
	if (url.indexOf('#') > -1) location.reload();
}

function FindId(el, of_class) {
	if (!el) return null;
	if (!el.tagName) return null;
	switch (el.tagName.toLowerCase()) {
		case 'body':
		case 'html':
			el = null;
			break;
		default:
			if (!el.id) el = FindId(el.parentNode, of_class);
			else if (of_class && el.className != of_class) el = FindId(el.parentNode, of_class);
			break;
	}
	return el;
}

function GetDiv(cls, id, styles, events) {
	var d = document.createElement('div');
	if (id && Is.Str(id)) d.id = id;
	if (cls && Is.Str(cls)) d.className = cls;
	if (Is.Obj(styles)) for (var i in styles) d.style[i] = styles[i];
	if (Is.Obj(events)) for (var i in events) E.Add(d, i, events[i]);
	return d;
}

function Eval(val, arg) {
	if (Is.Func(val)) return val(arg);
	if (Is.Str(val)) return eval(val);
	return false;
}

function GetLeftTop(el) {
	var l = el.offsetLeft;
	var t = el.offsetTop;
	for (var p = el.offsetParent; p; p = p.offsetParent) {
		l += p.offsetLeft;
		t += p.offsetTop;
	}
	return [l, t];
}

function GetValue(el) {
	if (!Is.Obj(el)) return null;
	switch (el.type.toLowerCase()) {
		case 'checkbox':
		case 'radio': return el.checked ? el.value : null;
		case 'select-one':
			var k = el.selectedIndex;
			return k >= 0 ? el.options[k].value : null;
		case 'select-multiple':
			var len = el.length;
			if (!len) return null;
			var vals = [];
			for (var i = 0; i < len; i++) {
				var opt = el.options[i];
				if (opt.selected) vals.push(opt.value);
			}
			return vals;
		default: return el.value;
	}
}

function Serialize(obj) {
	if (Is.Str(obj)) obj = $(obj);
	if (!Is.Obj(obj)) return null;
	var a = [];
	if (obj.tagName && obj.tagName.toLowerCase() == 'form') {
		for (var i = 0; i < obj.length; i++) {
			var v = GetValue(obj.elements[i]);
			if (v == null) continue;
			else a.push(encodeURIComponent(obj.elements[i].name) + '=' + encodeURIComponent(v));
		}
	} else
		for (var k in obj) a.push(encodeURIComponent(k) + '=' + encodeURIComponent(obj[k]));
	return a.join('&');
}

function Serialize2array(obj) {
	if (Is.Str(obj)) obj = $(obj);
	if (!Is.Obj(obj)) return null;
	var a = [];
	if (obj.tagName && obj.tagName.toLowerCase() == 'form') {
		for (var i = 0; i < obj.length; i++) {
			var v = GetValue(obj.elements[i]);
			if (v == null) continue;
			else a[obj.elements[i].name] = v;
		}
	} else
		for (var k in obj) a[k] = obj[k];
	return a;
}

var P = {
	w: 0,
	h: 0,
	sw: 0,
	sh: 0,
	sx: 0,
	sy: 0,
	Init: function() {
		if (Is.Num(window.innerWidth)) {
			P.w = window.innerWidth;
			P.h = window.innerHeight;
		} else if (document.documentElement && document.documentElement.clientWidth) {
			P.w = document.documentElement.clientWidth;
			P.h = document.documentElement.clientHeight;
		} else if (document.body && document.body.clientWidth) {
			P.w = document.body.clientWidth;
			P.h = document.body.clientHeight;
		}
		var f = $('footer');
		var flt = GetLeftTop(f);
		P.sw = flt[0] + f.offsetWidth;
		P.sh = flt[1] + f.offsetHeight;
		if (Is.Num(window.pageXOffset)) {
			P.sx = window.pageXOffset;
			P.sy = window.pageYOffset;
		} else if (document.body && document.body.scrollTop) {
			P.sx = document.body.scrollLeft;
			P.sy = document.body.scrollTop;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			P.sx = document.documentElement.scrollLeft;
			P.sy = document.documentElement.scrollTop;
		}
	}
}

var E = {
	dx: 0,
	dy: 0,
	el: null,
	Add: function(el, ev, fn) {
		if (el.addEventListener) el.addEventListener(ev, fn, false);
		else if (el.attachEvent) el.attachEvent('on' + ev, fn);
		else el['on' + ev] = fn;
	},
	Del: function(el, ev, fn) {
		if (el.removeEventListener) el.removeEventListener(ev, fn, false);
		else if (el.detachEvent) el.detachEvent('on' + ev, fn);
		else el['on' + ev] = null;
	},
	Get: function(ev) {
		if (!ev) var ev = window.event;
		return ev;
	},
	PreventDefault: function(ev) {
		ev.returnValue = false;
		if (ev.preventDefault) ev.preventDefault();
		return ev;
	},
	StopPropagation: function(ev) {
		ev.cancelBubble = true;
		if (ev.stopPropagation) ev.stopPropagation();
		return ev;
	},
	GetTarget: function(ev) {
		return (ev.target) ? ev.target : ev.srcElement;
	}
}

var Opacity = {prop:false};
E.Add(window, 'load', function(){for (var i in {opacity:'', MozOpacity:'', KhtmlOpacity:''}) if (Is.Str(document.body.style[i])) Opacity.prop = i; if (!Opacity.prop && document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1]>=5.5) Opacity.prop = 'filter';});

Opacity.Get = function(el) {
	if (!Is.Obj(el)) return;
	var op = 1;
	if (this.prop == 'filter') {
		var a = false;
		if (el.filters) a = el.filters['DXImageTransform.Microsoft.Alpha'] || el.filters.alpha;
		op = a.opacity * 100;
	} else
		op = el.style[this.prop];
	return op;
}

Opacity.Set = function(el, op) {
	if (!Is.Obj(el)) return;
	if (!Is.Set(op)) var op = 0.5;
	if (this.prop == 'filter') {
		op *= 100;
		var a = false;
		if (el.filters) a = el.filters['DXImageTransform.Microsoft.Alpha'] || el.filters.alpha;
		if (a) a.opacity = op;
		else el.style.filter += 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + op + ')';
	} else
		el.style[this.prop] = op;
}

Opacity.Fade = function(el, start, stop, delay) {
	if (Is.Str(el)) el = $(el);
	clearInterval(this.t);
	if (el) {
		this.start = start;
		this.stop = stop;
		this.op = start;
		var sign = stop - start > 0 ? 1 : -1;
		this.t = setInterval(function() {
			Opacity.op = Math.round((Opacity.op + 0.2 * sign) * 10) / 10;
			Opacity.Set(el, Opacity.op);
			if (Opacity.op == Opacity.start || Opacity.op == Opacity.stop) clearInterval(Opacity.t);
		}, delay);
	}
}

Opacity.DimScreen = function(bg, op, zi) {
	if (!Is.Set(bg)) var bg = '#000';
	if (!Is.Set(op)) var op = 0.5;
	if (!Is.Set(zi)) var zi = 0;
	P.Init();
	var d = GetDiv('', 'Dim' + Rnd(), {left:0, top:0, width:'100%', height:(P.sh < screen.availHeight) ? '100%' : P.sh + 'px', position:'absolute', background:bg, zIndex:zi})
	d = document.body.appendChild(d);
	this.Set(d, op);
	return d;
}

function A() {
	A.cnt++;
	var req = {};
	req.id = A.cnt;
	try {
		req.xhr = new XMLHttpRequest();
	} catch(e) {
		return false;
	}
	req.method = 'GET';
	req.url = location.href;
	req.async = true;
	req.data = null;
	req.res = null;
	req.target = null;
	req.timeout = 0;
	req.onStart = null;
	req.onComplete = null;
	req.onTimeout = null;
	req.xhr.onreadystatechange = function() {
		switch (req.xhr.readyState) {
			case XMLHttpRequest.OPENED:
				Eval(req.onStart);
				break;
			case XMLHttpRequest.DONE:
				req.res = req.xhr.responseText;
				if (req.target) req.target.innerHTML = req.res;
				if (req.method == 'POST') {
					if (req.res.indexOf('{') == 0) Eval('(' + req.res + ')');
					else
					{
						try {Eval(req.res);}catch(e){}
					}
				}
				Eval(req.onComplete, req.res);
				A.req[req.id] = null;
				delete A.req[req.id];
			break;
		}
	}
	req.handleTimeout = function() {
		if (req.xhr.readyState == XMLHttpRequest.DONE) return;
		req.xhr.abort();
		Eval(req.onTimeout);
		A.req[req.id] = null;
		delete A.req[req.id];
	}
	req.process = function() {
		req.xhr.open(req.method, req.url, req.async);
		req.xhr.setRequestHeader('Request', 'ajax');
		if (req.method == 'POST') req.xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
		if (req.timeout > 0) setTimeout(req.handleTimeout, req.timeout);
		req.xhr.send(req.data);
	}
	return req;
}

A.cnt = 0;
A.req = {};
A.wnd = {};

A.Send = function(url, data, target, cb) {
	var r = new A();
	if (Is.Obj(r)) {
		r.url = url;
		if (data) {
			r.method = 'POST';
			r.data = Serialize(data);
		}
		if (target) r.target = Is.Str(target) ? $(target) : target;
		if (Is.Obj(cb)) {
			if (Is.Func(cb.onStart)) r.onStart = cb.onStart;
			if (Is.Func(cb.onComplete)) r.onComplete = cb.onComplete;
			if (Is.Func(cb.onTimeout)) {
				r.onTimeout = cb.onTimeout;
				r.timeout = (Is.Num(cb.timeout)) ? cb.timeout : 10000;
			}
		}
		r.process();
	}
	A.req[r.id] = r;
	return r;
}

A.Get = function(url, target, cb) {
	return A.Send(url, null, target, cb);
}

A.Post = function(url, data, cb) {
	return A.Send(url, data, null, cb);
}

A.StartWait = function(id) {
	A.wnd[id] = {};
	A.wnd[id].time = new Date();
	A.wnd[id].back = Opacity.DimScreen('#fff', 0, 99999);
	A.wnd[id].back.style.cursor = 'wait';
}

A.StopWait = function(id) {
	var d = new Date();
	var x = d - A.wnd[id].time;
	if (x < 750) {
		setTimeout(function(){A.StopWait(id);}, 800 - x);
		return;
	}
	A.wnd[id].back.style.cursor = 'default';
	document.body.removeChild(A.wnd[id].back);
	A.wnd[id].back = null;
	A.wnd[id].time = null;
	delete A.wnd[id];
}

var F = {
	Upload: function(frm, cb) {
		if (Is.Str(frm)) frm = $(frm);
		if (!frm) return false;
		var id = 'F' + Rnd();
		var d = document.createElement('div');
		d.innerHTML = '<iframe id="' + id + '" name="' + id + '" style="display:none" src="about:blank" onload="F.onLoad(event, this);"></iframe>';
		document.body.appendChild(d);
		if (cb) {
			$(id).onComplete = cb.onComplete;
			Eval(cb.onStart);
		}
		frm.setAttribute('target', id);
		frm.submit();
		return false;
	},
	onLoad: function(ev, f) {
		if (Is.Str(f)) f = $(f);
		if (!f) return;
		var r;
		if (f.contentDocument) r = f.contentDocument;
		else if (f.contentWindow) r = f.contentWindow.document;
		else r = window.frames[f.id].document;
		if (r.location.href == 'about:blank') return;
		Eval(f.onComplete, r);
		f.onload = null;
		//setTimeout(function(){document.body.removeChild(f.parentNode);}, 2000);
	}
}

function W() {
	W.cnt++;
	var w = {};
	w.id = W.cnt;
	w.cont = null;
	w.cont_c = 'w-cont';
	w.head_c = 'w-head';
	w.body_c = 'w-body';
	w.foot_c = 'w-foot';
	w.load_c = 'w-load';
	w.cont_id = w.cont_c + w.id;
	w.body_id = w.body_c + w.id;
	w.close_id = 'w-close' + w.id;
	w.submit_id = 'w-submit' + w.id;
	w.url = '';
	w.title = '';
	w.redir = '';
	w.form = '';
	w.loadTimeout = 5000;
	w.sendTimeout = 15000;
	w.cb = null;
	w.no_fade = null;
	w.no_foot = null;
	w.GetHead = function() {
		return '<div class="' + w.head_c + '" onmousedown="W[' + w.id + '].Drag(event);"><div class="move"></div><a href="javascript:void(0);" onclick="W[' + w.id + '].Close();" class="close">Закрыть</a><h3>' + w.title + '</h3></div>';
	}
	w.GetBody = function(h) {
		return '<div class="' + w.body_c + '" id="' + w.body_id + '" style="height:' + h + 'px;"></div>';
	}
	w.GetFoot = function(sbm_text) {
		if (!sbm_text) var sbm_text = 'Ок';
		var d = '<div class="' + w.foot_c + '">';
		if (w.form) d += w.GetSubmitBtn(sbm_text);
		d += w.GetCloseBtn((w.form ? 'Отмена' : 'Ок'));
		d += '</div>';
		return d;
	}
	w.GetSubmitBtn = function(text) {
		return '<input type="button" value="' + text + '" onclick="W[' + w.id + '].Submit();" id="' + w.submit_id + '" />';
	}
	w.GetCloseBtn = function(text) {
		return '<input type="button" value="' + text + '" onclick="W[' + w.id + '].Close();" id="' + w.close_id + '" />';
	}
	w.Load = function() {
		A.Get(w.url, $(w.body_id), {
			onStart:function() {
				$(w.body_id).className += ' ' + w.load_c;
				A.StartWait(w.id);
				var b = $(w.submit_id) || $(w.close_id);
				if (!w.no_foot) b.setAttribute('disabled', 'disabled');
				if (w.cb && Is.Func(w.cb.onStart)) w.cb.onStart();
			},
			onComplete:function() {
				$(w.body_id).className = w.body_c;
				A.StopWait(w.id);
				var b = $(w.submit_id) || $(w.close_id);
				if (!w.no_foot) b.removeAttribute('disabled');
				if (w.cb && Is.Func(w.cb.onLoadComplete)) w.cb.onLoadComplete();
			},
			onTimeout:function() {
				$(w.body_id).className = w.body_c;
				A.StopWait(w.id);
				w.onLoadTimeout();
				if (w.cb && Is.Func(w.cb.onTimeout)) w.cb.onTimeout();
			},
			timeout:w.loadTimeout
		});
	}
	w.onLoadTimeout = function() {
		$(w.body_id).innerHTML = '<p>Произошла ошибка при загрузке данных!<br />Для того чтобы попытаться еще раз, нажмите на кнопку "Загрузить", если нет, то закройте это окно.</p><input type="button" value="Загрузить" onclick="W[' + w.id + '].Load();" />';
	}
	w.onSendTimeout = function() {
		var wnd = W.Create('', 'Ошибка', '', '', 400, 80);
		$(wnd.body_id).innerHTML = '<p>Произошла ошибка при отправке данных!</p>';
	}
	w.Close = function() {
		if (!w.no_fade)
		{
			Opacity.Fade(w.cont, 1, 0.6, 50);
			setTimeout(function() {
				if (W[w.id].dim) document.body.removeChild(W[w.id].dim);
				document.body.removeChild(w.cont);
				delete W[w.id];
				if (w.redir) Redir(w.redir);
			}, 200);
		}
		else
		{
			if (W[w.id].dim) document.body.removeChild(W[w.id].dim);
			document.body.removeChild(w.cont);
			delete W[w.id];
			if (w.redir) Redir(w.redir);
		}
	}
	w.Submit = function() {
		var form = $(w.form);
		if (!form) return;
		var cb = {
			onStart:function() {
				A.StartWait(w.id);
				if ($(w.submit_id))
					$(w.submit_id).setAttribute('disabled', 'disabled');
			},
			onComplete:function(res) {
				A.StopWait(w.id);
				if ($(w.submit_id))
					$(w.submit_id).removeAttribute('disabled');
				if (w.cb && Is.Func(w.cb.onComplete)){ w.cb.onComplete(res);}
			},
			onTimeout:function() {
				A.StopWait(w.id);
				if ($(w.submit_id))
					$(w.submit_id).removeAttribute('disabled');
				w.onSendTimeout();
			},
			timeout:w.sendTimeout
		}
		if (form.tagName && form.tagName.toLowerCase() == 'form') {
			if (form.enctype == 'multipart/form-data' || form.encoding == 'multipart/form-data') {
				form.onsubmit = null;
				return F.Upload(form, cb); // TODO
			}
			for (var i = 0; i < form.length; i++)
				if (form.elements[i].name == '_ajax_')
					return A.Post(form.action, form, cb);
			return form.submit();
		}
	}
	w.Drag = function(ev) {
		ev = E.Get(ev);
		E.PreventDefault(ev);
		E.StopPropagation(ev);
		w.Up();
		P.Init();
		E.el = w.cont;
		E.dx = ev.clientX - Int(E.el.style.left);
		E.dy = ev.clientY - Int(E.el.style.top);
		document.onmousemove = function(ev) {
			var el, w, h, l, t, k, sw, sh;
			ev = E.Get(ev);
			E.PreventDefault(ev);
			E.StopPropagation(ev);
			E.el.style.left = (ev.clientX - E.dx) + 'px';
			E.el.style.top = (ev.clientY - E.dy) + 'px';
			l = Int(E.el.offsetLeft);
			t = Int(E.el.offsetTop);
			w = Int(E.el.offsetWidth);
			h = Int(E.el.offsetHeight);
			k = 50;
			if (w < k) k = w;
			if (h < k) k = h;
			if (l < 0) E.el.style.left = 0;
			if (t < 0) E.el.style.top = 0;
			sw = P.sw;
			sh = P.sh;
			if (sw < screen.availWidth) sw = screen.availWidth;
			if (sh < screen.availHeight) sh = screen.availHeight;
			if (l + k >= sw) E.el.style.left = (sw - k) + 'px';
			if (t + k >= sh) E.el.style.top = (sh - k) + 'px'; // FIX sh
		};
		document.onmouseup = function(ev) {
			ev = E.Get(ev);
			E.StopPropagation(ev);
			document.onmousemove = null;
			document.onmouseup   = null;
		};
	}
	w.Up = function() {
		var wn = 0;
		var cz = 0;
		var mz = 0;
		for (var i in W)
			if (W[i].cont) {
				wn++;
				cz = Int(W[i].cont.style.zIndex);
				if (cz > mz) mz = cz;
			}
		if (wn > 1) {
			mz++;
			w.cont.style.zIndex = mz;
		}
	}
	return w;
}

W.cnt = 0;

W.Create = function(url, title, redir, form, w, h, x, y, cb, sbm_text, no_fade, no_foot) {
	var wnd = new W();
	if (url) wnd.url = url;
	if (title) wnd.title = title;
	if (redir) wnd.redir = redir;
	if (form) wnd.form = form;
	if (cb) wnd.cb = cb;
	P.Init();
	if (!Is.Num(w)) w = Int(P.w / 2);
	if (!Is.Num(h)) h = Int(P.h / 2);
	if (!Is.Num(x)) x = Int(P.w / 2 - w / 2 + P.sx);
	if (!Is.Num(y)) y = Int(P.h / 2.5 - h / 2 + P.sy);
	if (x < 0) x = 0;
	if (y < 0) y = Int(P.h / 2 - h / 2 + P.sy);
	if (y < 0) y = 0;
	if (no_fade) wnd.no_fade = 1;
	if (no_foot) wnd.no_foot = 1;
	wnd.cont = GetDiv(wnd.cont_c, wnd.cont_id, {width:w + 'px', left:x + 'px', top:y + 'px'});
	wnd.cont.innerHTML = wnd.GetHead() + wnd.GetBody(h);
	if (!wnd.no_foot)
		wnd.cont.innerHTML += wnd.GetFoot(sbm_text);
	wnd.cont.style.zIndex = wnd.id;
	wnd.cont = document.body.appendChild(wnd.cont);
	if (!wnd.no_fade)
		Opacity.Set(wnd.cont, 0.4);
	W[wnd.id] = wnd;
	wnd.Up();
	if (url) wnd.Load();
	//$(wnd.close_id).focus();
	if (!wnd.no_fade)
		Opacity.Fade(wnd.cont, 0.6, 1, 50);
	return wnd;
}

W.Switch_form = function (new_form_id) {
    var id = W.cnt;
    W[id].form = new_form_id;
}

W.Close = function(id, redir) {
	if (!id) var id = W.cnt;
	if (redir) W[id].redir = redir;
	if (W[id]) W[id].Close();
}

W.OpenNoBtns = function(url, title, w, h, x, y, cb) {
	var d = Opacity.DimScreen();
	var w = W.Create(url, title, '', '', w, h, x, y, cb, null, null, 1);
	W[w.id].dim = d;
	return false;
}

W.OpenSimple = function(url, title, redir, w, h, x, y, cb) {
	var d = Opacity.DimScreen();
	var w = W.Create(url, title, redir, '', w, h, x, y, cb);
	W[w.id].dim = d;
	return false;
}

W.OpenDialog = function(url, title, form, w, h, x, y, cb, sbm_text, no_foot) {
	var d = Opacity.DimScreen();
	var w = W.Create(url, title, '', form, w, h, x, y, cb, sbm_text, null, no_foot);
	W[w.id].dim = d;
	return false;
}

W.OpenSimpleNoAJAX = function(title, msg, w, h, x, y, cb, no_fade) {
	var d = Opacity.DimScreen();
	var w = W.Create('', title, '', '', w, h, x, y, null, null, no_fade);
	$(w.body_id).innerHTML = msg;
	W[w.id].dim = d;
	if (cb)
		$(w.close_id).onclick = function()
		{
			Eval(cb);
			W[w.id].Close();
			W.cnt --;
		};
	else
		$(w.close_id).onclick = function()
		{
			W[w.id].Close();
			W.cnt --;
		};
	return false;
}

W.OpenResizer = function(url, title, form, w, h, x, y) {
	var cb = {onLoadComplete:function(){I.Prepare(form);}};
	var d = Opacity.DimScreen();
	var w = W.Create(url, title, null, null, w, h, x, y, cb);
	W[w.id].dim = d;
	return w;
}

var I = {
	dst: null,
	frame: null,
	canvas: null,
	select: null,
	resize: null,
	form: '',
	Prepare: function(frm) {
		if (Is.Str(frm)) frm = $(frm);
		if (!frm) return false;
		I.form = frm;
		I.dst = $('img_dst');
		I.frame = $('img_frame');
		I.canvas = $('img_canvas');
		I.select = $('img_select');
		I.resize = $('img_resize');
		I.dst.style.width = 'auto';
		I.dst.style.height = 'auto';
		I.dst.style.top = 0;
		I.dst.style.left = 0;
	},
	Select: function(ev) {
		ev = E.Get(ev);
		el = E.GetTarget(ev);
		P.Init();
		E.StopPropagation(ev);
		E.dx = ev.clientX - Int(el.style.left);
		E.dy = ev.clientY - Int(el.style.top);
		E.el = el;
		document.onmousemove = function(ev) {
			var el, l, t, w, h, x, y, icw, ich;
			ev = E.Get(ev);
			el = E.el;
			E.PreventDefault(ev);
			E.StopPropagation(ev);
			l = Int(el.style.left);
			t = Int(el.style.top);
			w = Int(el.style.width);
			h = Int(el.style.height);
			x = ev.clientX - E.dx;
			y = ev.clientY - E.dy;
			icw = Int(I.canvas.style.width);
			ich = Int(I.canvas.style.height);
			if (x > 0 && x + w <= icw)
				el.style.left = x + 'px';
			else
				el.style.left = (x + w > icw) ? (icw - w) + 'px' : 0;
			I.dst.style.clip = 'rect(' + t + 'px, ' + l + 'px, ' + t + 'px, ' + l + 'px)';
			I.dst.style.left = '-' + l + 'px';
			I.form['img_x'].value = l;
			if (y > 0 && y + h <= ich)
				el.style.top = y + 'px';
			else
				el.style.top = (y + h > ich) ? (ich - h) + 'px' : 0;
			I.dst.style.clip = 'rect(' + t + 'px, ' + l + 'px, ' + t + 'px, ' + l + 'px)';
			I.dst.style.top = '-' + t + 'px';
			I.form['img_y'].value = t;
		}
		document.onmouseup = I.Stop;
	},
	Resize: function(ev) {
		ev = E.Get(ev);
		el = E.GetTarget(ev);
		P.Init();
		E.StopPropagation(ev);
		E.dx = ev.clientX - Int(el.style.left);
		E.dy = ev.clientY - Int(el.style.top);
		E.el = el;
		var pc = FindId(I.resize, 'w-cont');
		document.onmousemove = function(ev) {
			ev = E.Get(ev);
			el = E.el;
			E.PreventDefault(ev);
			E.StopPropagation(ev);
			var origW = Int(I.frame.style.width);
			var origH = Int(I.frame.style.height);
			var minX = Int(I.select.style.left) + Int(I.select.style.width);
			var minY = Int(I.select.style.top) + Int(I.select.style.height);
			if (ev.clientX - 4 < origW + Int(pc.style.left)) {
				var newX = ev.clientX - E.dx;
				var newY = Int(newX * origH / origW);
				if (newX > minX && newY > minY) {
					I.canvas.style.width = newX + 'px';
					I.canvas.style.height = newY + 'px';
					I.resize.style.left = newX + 'px';
					I.resize.style.top = newY + 'px';
					I.dst.style.height = newY + 'px';
					I.dst.style.width = newX + 'px';
					I.form['img_h'].value = newY;
					I.form['img_w'].value = newX;
				}
			}
		}
		document.onmouseup = I.Stop;
	},
	Stop: function(ev) {
		ev = E.Get(ev);
		E.StopPropagation(ev);
		document.onmousemove = null;
		document.onmouseup   = null;
	}
}

// custom funcs
function switch_fav(obj, cid, _short) {
	if (obj.className == 'outfav') {
		A.Get('/compas/' + cid + '/del_fav');
		obj.className = '';
		if (_short == null)
			obj.innerHTML = 'в избранное';
		obj.title = 'добавить в избранное';
		obj.href = '/compas/' + cid + '/add_fav';
	} else {
		A.Get('/compas/' + cid + '/add_fav');
		obj.className = 'outfav';
		if (_short == null)
			obj.innerHTML = 'в избранном';
		obj.title = 'удалить из избранного';
		obj.href = '/compas/' + cid + '/del_fav';
	}
	return false;
}

function switch_fun(obj, uid) {
	if (obj.id == 'on_'+uid) {
		A.Get('/cmaster/' + uid + '/add_fun');
		$j('#on_'+uid).toggle();
		$j('#off_'+uid).toggle();
	} else {
		A.Get('/cmaster/' + uid + '/del_fun');
		obj.id = 'on'+uid;
		obj.innerHTML = 'Вступить в фанклуб';
		obj.href = '/cmaster/' + uid + '/add_fun';
	}
	return false;
}

function create_compas() {
	A.Post('/create', 'create_compas_frm');
}

function create_group() {
	A.Post('/groups/create_group', 'create_group');
}

function create_theme() {
	if (Wysiwyg && Wysiwyg.mode == 'wysiwyg')
		Wysiwyg.CopyContent('2bb');
	A.Post('/groups/create_theme', 'create_theme_frm');
}

function save_profile_info() {
	A.Post('/my/save_profile_info', 'profile_frm');
}

function getLeftTop(element) {
	var left = element.offsetLeft;
	var top = element.offsetTop;
	for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
		left += parent.offsetLeft;
		top += parent.offsetTop;
	}
	return [left, top];
}

function pageSize() {
	var pageWidth = getLeftTop($('footer'))[0] + $('footer').offsetWidth;
	var pageHeight = getLeftTop($('footer'))[1] + $('footer').offsetHeight;
	return [pageWidth, pageHeight];
}

var dft_sec = 1;
var max_sec = 3600;
var cur_sec = 30;
var last_res = 0;
function new_msg_updater(sec) {
	setTimeout('new_msg()', (!sec ? dft_sec : sec) * 1000);
}

function new_msg() {
	A.Get('/my/mailbox/msgs', null, {onComplete:function(r){
		var mb = $('new_msgs');
		//если messagebox-а нету, то не продолжаем
		if (!mb) return false;
		if (r == '') return false;
		var res = Int(r);
		if (res != last_res)
		{
			last_res = res;
			mb.className = mb.className.replace(/ hidden/, '');
			new_msg_updater();
		}
		else
		{
			if (res == 0)
				if (mb.className.indexOf(' hidden') == -1)
					mb.className += ' hidden';
			cur_sec = Int(cur_sec * 2);
			if (cur_sec > max_sec)
				cur_sec = max_sec;
			new_msg_updater(cur_sec);
		}
	}})
}

function limit_input_str (id, id_cnt, limit)
{
	var obj = $(id);
	var str = obj.value;
	var len = str.length;
	var txt;
	if (len > limit)
	{
		txt = 0;
		str = str.substr(0, limit)
		obj.value = str;
	}
	else
		txt = (limit - len);
	$(id_cnt).innerHTML = txt;
}
function del_fun(uid)
{
	A.Get('/cmaster/' + uid + '/del_fun');
	$(uid).style.display = 'none';
}
function del_fav_cm(uid)
{
	A.Get('/cmaster/' + uid + '/del_fun');
	//$('card_' + uid).style.display = 'none';
	window.location = window.location;
}

function widget_anim(id_num, on_off)
{
	var max_widg_num = 7;
	var widg;
	if (id_num == 0)
	{
		$('widg_row_h').style.display = 'block';
		for (var i = 1; i < (max_widg_num + 1); i++)
		{
			widg = $("widget_" + i);
			widg.className = widg.className.replace(/ open/, '');
		}
	}
	else
	{
		if ($('widg_row_h').style.display == 'block')
			$('widg_row_h').style.display = 'none';
		widg = $("widget_" + id_num);
		if (on_off == 'on' && widg.className.indexOf(' open') == -1)
		{
			widg.className += ' open';
			/*if (navigator.userAgent.match(/opera\/9\.5/i))
				$('widget_row_b').innerHTML = $('widget_row_b').innerHTML;*/
		}
		else if (on_off == 'off' && widg.className.indexOf(' open') > -1)
		{
			widg.className = widg.className.replace(/ open/, '');
			if (navigator.userAgent.match(/opera\/9\.5/i))
				$('widget_row_b').innerHTML = $('widget_row_b').innerHTML;
		}
	}
}
function index_switch (type)
{
	if (type == 1)
	{
		$('index_tags').style.display = 'none';
		$('index_cat').style.display = 'block';
		//$('switchdiv').innerHTML = '<h2 class="switch">Категории</h2><h2 class="switch"><a href="javascript:void(0);" onclick="index_switch(2);">Метки</a></h2>';
		$('cat_h').innerHTML = 'Категории';
		$('tag_h').innerHTML = '<a href="javascript:void(0);" onclick="index_switch(2);">Метки</a>';
	}
	else
	{
		$('index_cat').style.display = 'none';
		$('index_tags').style.display = 'block';
		//$('switchdiv').innerHTML = '<h2 class="switch"><a href="javascript:void(0);" onclick="index_switch(1);">Категории</a></h2><h2 class="switch">Метки</h2>';
		$('cat_h').innerHTML = '<a href="javascript:void(0);" onclick="index_switch(1);">Категории</a>';
		$('tag_h').innerHTML = 'Метки';
	}
}

function switch_login(type)
{
	if (type == 'openid')
	{
		$('usual_login').style.display = 'none';
		$('openid_login').style.display = 'block';
		W.Switch_form('signin_openid_frm');
	}
	else
	{
		$('openid_login').style.display = 'none';
		$('usual_login').style.display = 'block';
		W.Switch_form('signin_frm');
	}
}

function switch_g_invites(a_obj)
{
	var obj = $('g_invites');
	if (obj.style.display == 'none')
	{
		obj.style.display = 'block';
		a_obj.innerHTML = 'Скрыть приглашения';
	}
	else
	{
		$('g_invites').style.display = 'none';
		a_obj.innerHTML = 'Пригласить в группу';
	}

}

function get_invites_g_list(uid)
{
	W.OpenDialog('/cmaster/get_invites_g_list/' + uid + '/', 'Пригласить в группу', 'form_invites_g', 600, 435, null, null, {onComplete:send_invites_onc}, 'Пригласить');
}
function send_invites_onc(res)
{
	var ray = Eval('(' + res + ')');
	if (ray.s == 1)
	{
		W.Close();
		if (ray.have_more_invites == 0)
			$('invites_g_sect').style.display = 'none';
	}
	else
		W.OpenSimpleNoAJAX('Ошибка', 'Приглашение не было отправлено. Пожалуйста, повторите.', 350, 50);
}

function acc_rej_invite(gid, type)
{
	var data=[];
	data['gid'] = gid;
	A.Post('/my/mailbox/' + type + '_g_invite/', data, {onComplete:acc_rej_invite_onc});
}

function acc_rej_invite_onc(res)
{
	var ray = Eval('(' + res + ')');
	if (ray.s == 1)
		window.location = window.location;
	else
	{
		W.OpenSimpleNoAJAX('Ошибка', 'Произошла ошибка. Пожалуйста, повторите.', 350, 50);
	}
}

function set_img_size(obj, max_w)
{
	if (!max_w) max_w = 500;
	if (obj.width > max_w)
	{
		if (obj.width && obj.height)
		{
			var max_h = max_w * obj.height / obj.width;
			obj.style.height = max_h + 'px';
		}
		obj.style.width = max_w + 'px';
	}
}

function survey_send() {
	A.Post('/survey', 'survey_frm', {onComplete:survey_onc, onTimeout: function(){W.OpenSimpleNoAJAX('Ошибка', 'Произошла ошибка. Пожалуйста, повторите.', 350, 50);}});
}

function survey_onc(res)
{
	var ray = Eval('(' + res + ')');
	if (ray.s == 1)
	{
		W.OpenSimple('/msg/i/survey_success', 'Спасибо', '/survey', 100, 50);
		//window.location = window.location;
	}
	else
	{
		W.OpenSimpleNoAJAX('Ошибка', 'Произошла ошибка. Пожалуйста, повторите.', 350, 50);
	}
}

function survey2_send() {
	A.Post('/survey2', 'survey_frm', {onComplete:survey2_onc, onTimeout: function(){W.OpenSimpleNoAJAX('Ошибка', 'Произошла ошибка. Пожалуйста, повторите.', 350, 50);}});
}

function survey2_onc(res)
{
	var ray = Eval('(' + res + ')');
	if (ray.s == 1)
	{
		W.OpenSimple('/msg/i/survey_success', 'Спасибо', '/survey2', 100, 50);
		//window.location = window.location;
	}
	else
	{
		W.OpenSimpleNoAJAX('Ошибка', 'Произошла ошибка. Пожалуйста, повторите.', 350, 50);
	}
}

//раскрытие-скрытие списка категорий
function toggle_list(action)
{
	var list_id = 'categories_list';
	var show_button_id = 'categories_list_switcher_s';
	var hide_button_id = 'categories_list_switcher_h';
	action = (action == 'hide') ? 'hide' : 'show';
	$j('#' + list_id)
		//.animate({height: action});
		//.hide('fast', function(){after_toggle_list(action, show_button_id, hide_button_id);});//не работает, т.к. не задана высота
		[action]();//show/hide)
	after_toggle_list(action, show_button_id, hide_button_id);
}

function after_toggle_list(action, show_button_id, hide_button_id)
{
	var hide_button = $j('#' + hide_button_id);
	var show_button = $j('#' + show_button_id);
	if (action == 'show')
	{
		hide_button.show();
		show_button.hide()
	}
	else
	{
		hide_button.hide();
		show_button.show()
	}
}

/**
 * скрытие одного дива/открытие другого и наоборот
 * @param {string} id1
 * @param {string} id2
 * @param {string} action если "open", то скрываем id1/открываем id2, "close" - наоборот
 */
function toggle_divs(id1, id2, action)
{
	var div1 = $j('#' + id1);
	var div2 = $j('#' + id2);
	var div2open = div2, div2close = div1;
	action = (action == 'close') ? 'close' : 'open';
	if (action == 'close')
	{
		div2open = div1;
		div2close = div2;
	}
	div2close.hide();
	div2open.show();
}

function add_comment()
{

	var comments_context = $('comments_context').value;
	var qid = $('qid').value;
	var q_is_only_author = $('q_is_only_author').value;
	
	// cid/gtid
	var cid_gtid = $('cid_gtid').value;
	var comment_msg = $('comment_msg').value;
	var is_only_author = qid > 0 ? q_is_only_author : ($('only_author').checked ? 1 : 0);

	//console.log(comments_context, qid, cid_gtid, comment_msg);
	var data=[];
	//data['comments_context'] = comments_context;
	data['qid'] = qid;
	//data['cid_gtid'] = cid_gtid;
	data['msg'] = comment_msg;
	data['is_only_author'] = is_only_author;

	add_comment_toggle_loader('show_loader');
	//alert(data);
	if (comments_context == 'compas')
		A.Post('/compas/' + cid_gtid + '/comments/add', data, {onComplete: add_comment_onc, onTimeout: add_comment_ontimeout});
	else if (comments_context == 'group_theme')
		A.Post('/groups/add_cmt2theme/' + cid_gtid, data, {onComplete: add_comment_onc, onTimeout: add_comment_ontimeout});

}

function add_comment_onc()
{
	add_comment_toggle_loader('hide_loader');
}

function add_comment_ontimeout()
{
	add_comment_toggle_loader('hide_loader');
}

function add_comment_toggle_loader(mode)
{
	if (mode != 'hide_loader') mode = 'show_loader';
	var loaderId = 'add_comment_loader';
	var buttonId = 'add_comment_button';
	var loader = button = null;
	if ((loader = $(loaderId)) && (button = $(buttonId)))
	{
		if (mode == 'show_loader')
		{
			button.style.display = 'none';
			loader.style.display = 'block';
			button.blur();
		}
		else
		{
			loader.style.display = 'none';
			button.style.display = 'block';
		}
	}
}

function hide_about()
{
    $j('#main_about').toggle();
    $j('#agree_main').toggle();
    $j('#return_main').toggle();
    $j('#o_about').toggle();
    $j('#x_about').toggle();
}

function select_whatsnew(select_id)
{
    Redir(select_id.options[select_id.selectedIndex].value);
}

function show_answer_comment_form(cid_gtid, qid)
{
	var comments_context = $('comments_context').value;
	if (comments_context == 'compas')
		A.Get('/compas/' + cid_gtid + '/comments/add/' + qid, 'add_comment_form');
	if (comments_context == 'group_theme')
		A.Get('/groups/add_cmt2theme/' + cid_gtid + '/' + qid, 'add_comment_form');
}

var UriId =
{
	transliterationArray:
    {
        'а' : 'a',
        'б' : 'b',
        'в' : 'v',
        'г' : 'g',
        'д' : 'd',
        'е' : 'e',
        'ё' : 'yo',
        'ж' : 'zh',
        'з' : 'z',
        'и' : 'i',
        'й' : 'y',
        'к' : 'k',
        'л' : 'l',
        'м' : 'm',
        'н' : 'n',
        'о' : 'o',
        'п' : 'p',
        'р' : 'r',
        'с' : 's',
        'т' : 't',
        'у' : 'u',
        'ф' : 'f',
        'х' : 'h',
        'ц' : 'c',
        'ч' : 'ch',
        'ш' : 'sh',
        'щ' : 'sch',
        'ъ' : '',
        'ы' : 'y',
        'ь' : '',
        'э' : 'e',
        'ю' : 'yu',
        'я' : 'ya'
    },

    /**
     * Переводит символы в соответствии с @link this.transliterationArray
     * @param {String} str "грязная" строка для транслитерации
     * @return {String}
     */
    translitString: function(str)
    {
		if (!str)
			return '';
		if (!Is.Str(str))
			str = str.toString();
	    var re = new RegExp('[a-z0-9_\\-]');
	    str = str.toLowerCase();
	    str = str.replace(/ /g, '_');
	    var newStrChars = [];
	    var currentChar = '';
	    for (var i = 0; i < str.length; i ++)
	    {
	    	currentChar = str.charAt(i);
	    	if (this.transliterationArray[currentChar])
	    		newStrChars.push(this.transliterationArray[currentChar]);
	    	else if (re.test(currentChar))
	    		newStrChars.push(currentChar);
	    }
	    return newStrChars.join('');
    },

    /**
     * обрезает строку
     * @param {String} str
     * @param {int} maxChars[OPTIONAL] сколько символов
     * @return {String}
     */
	cut: function(str, maxChars)
	{
		if (!maxChars)
			maxChars = 32;
		if (str.length > maxChars)
			str = str.substr(0, maxChars);
		return str;
	},

    /**
     * Генерирует элемент URI (фактически, id компаса/группы, т.е. без "/")
     * @param {String} str
     * @param {int} maxChars[OPTIONAL] сколько символов
     * @return {String}
     */
	generate: function(inputString, maxChars)
	{
		if (!maxChars)
			maxChars = 32;
		var uri = this.translitString(inputString);
		return this.cut(uri);
	},

	setFromName: function(nameId, uriId)
	{
		var nameObj = $(nameId);
		var uriObj = $(uriId);
		uriObj.value = this.generate(nameObj.value);
	},

	clear: function(obj)
	{
		obj.value = this.generate(obj.value);
	}
}

//ставим обработчик нажатия на кнопку в окне регистрации
function set_register_link_onclick(w_id)
{
	//теоретически, надо бы писать w.id
	//console.log(w_id);
	var register_link_id = 'register_link_id';
	$j('#' + register_link_id).click(function(){W[w_id].Submit();});
}