// Wrap element
Element.addMethods({
  wrap: function(element, wrapper) {
    element = $(element);
    element.parentNode.replaceChild(wrapper, element);
    wrapper.appendChild(element);
    return Element.extend(wrapper);
  }
});
//---------------------------------------------------------------------------

// Unwrap element
Element.addMethods({
  unwrap: function(element, wraperTag, wraperClass) {
    element = $(element);
	if( (wraperTag.length? element.parentNode.tagName.toLowerCase==wraperTag.toLowerCase : 0) && (wraperClass.length? element.parentNode.className==wraperClass : 0) )
	{
		element.parentNode.parentNode.replaceChild(element, element.parentNode);
	} 
	return Element.extend(element);
  }
});
//---------------------------------------------------------------------------

// create new element
function crElem(name, attrs, style, text) {
    var e = document.createElement(name);
    if (attrs) {
        for (key in attrs) {
            if (key == 'class') {
                e.className = attrs[key];
            } else if (key == 'id') {
                e.id = attrs[key];
            } else {
                e.setAttribute(key, attrs[key]);
            }
        }
    }
    if (style) {
        for (key in style) {
            e.style[key] = style[key];
        }
    }
    if (text) {
		if(e.tagName=='INPUT') e.value = text;
		else if(typeof(text)=='object') {
			var i, N;
			for(i=0, N=text.size(); i<N; i++) {
				if(typeof(text[i])=='string') e.appendChild(document.createTextNode(text[i]));
				else e.appendChild(text[i]);
			}
		}
        else e.appendChild(document.createTextNode(text));
    }
    return Element.extend(e);
}
//---------------------------------------------------------------------------

function pageLocation(o, t){
	var x = 0

	while(o.offsetParent){
		x += o['offset' + t]
		o = o.offsetParent
	}
	x += o['offset' + t]

	return x
}
//---------------------------------------------------------------------------



var	_TBL_ACT_ADD_ = 0x01,
	_TBL_ACT_EDT_ = 0x02,
	_TBL_ACT_DEL_ = 0x03,
	_TBL_ACT_MOVE_UP_ = 0x08,
	_TBL_ACT_MOVE_DOWN_ = 0x09,
	_TBL_ACT_LEVEL_UP_ = 0x0A,
	_TBL_ACT_LEVEL_DOWN_ = 0x0B;

var CSrvConnect = Class.create();
CSrvConnect.prototype = {
	initialize: function(container, root, url, isJson, options) {
		this.root = root;
		this.container = container;
		this.cnt = $(container);
		this.url = url;
		this.isJson = isJson==true;
		this.options = { 'showOkMessage':true, 'showErrMessage':true, 'gotoMsgOnErr':true };
		if(typeof(options)!='undefined') {
			if(typeof(options['showOkMessage'])!='undefined') this.options['showOkMessage'] = options['showOkMessage'];
			if(typeof(options['gotoMsgOnOk'])!='undefined') this.options['gotoMsgOnOk'] = options['gotoMsgOnOk'];
			if(typeof(options['showErrMessage'])!='undefined') this.options['showErrMessage'] = options['showErrMessage'];
			if(typeof(options['gotoMsgOnErr'])!='undefined') this.options['gotoMsgOnErr'] = options['gotoMsgOnErr'];
			if(typeof(options['loadContentInContainer'])!='undefined') this.isLoadContentInContainer = options['loadContentInContainer'];
		}
	},
	
	load: function(params, async){
		this.params = params;
		var url = this.url[1]=='/'? this.url : this.root+this.url;
		
		if(typeof(async)=='undefined') async = false;
		if(this.showHideOnLoad) this.cnt.show();

		new Ajax.Request(url, {
			method: 'post',
			asynchronous: async,
			parameters: params,
			onLoading: function(obj) {
				return function(){
					obj.loadStatus(_t('loading'));
				}
			}(this),
			onSuccess: function(obj) {
				return function(t){
					obj.parseResult(t);
				}
			}(this),
			onFailure: function(obj) {
				return function() {
					obj.loadStatus(_t('server_connection_failure'), 'load-error');
				}
			}(this)
		});
	},//---------------------------------------------------------------------
	
	loadStatus: function(str, className) {
		if (this.cnt) {
			this.cnt.update();
			if(!className) className = 'loading';
			this.cnt.appendChild( crElem('div', { 'class': className }, '', [crElem('p', {}, '', str), crElem('img', {'src':'/img/loader.white.gif'}, '', '')] ) );
			this.insertRefreshButton();
		}
	},//---------------------------------------------------------------------
	
	parseResult: function(t) {
		try { this.onLoad && this.onLoad(t); }
		catch(e) {}
		
		if(this.isJson) {
			if(this.cnt) {
				this.cnt.update();
				this.cnt.appendChild( crElem('div', { 'class': 'loading' }, '', [crElem('p', {}, '', _t('answer_processing'))] ) );
			}

			var json;
			try { json = this.json = eval('(' + t.responseText + ')'); }
			catch(e) { if(this.cnt) this.cnt.update('<div class="msg-err">' + _t('error') + '</div>'+t.responseText); }

			if(json.status) {// Операция выполнена успешно
				if(this.cnt) {
					if (json.message && this.options['showOkMessage']) {
						this.cnt.update('<div class="msg-ok">' + json.message + '</div>');
						if(this.options['gotoMsgOnOk'] && this.cnt.id) document.location = '#' + this.cnt.id;
					}
					else this.cnt.update();
				
					if(this.clearMsgTimer!=null) window.clearTimeout(this.clearMsgTimer);
					this.clearMsgTimer = window.setTimeout( function(obj){
						return function(){
							obj.clearMsg();
						}
					}(this), this.clearMsgTimeout);
				}
				
				this.onJsonDone && this.onJsonDone(json);
			}
			else {// Ошибка
				if(this.options['showErrMessage'] && this.cnt) {
					this.cnt.update();
					var elem,
						div = this.cnt.appendChild( elem = crElem('div', { 'class': 'msg-err' }, '', [crElem('b',null,null, _t('error_'))]) );
					elem.innerHTML += json.error.message;
					if(this.options['gotoMsgOnErr'] && this.cnt.id) document.location = '#' + this.cnt.id;
				}
				this.onJsonError && this.onJsonError(json);
			}
		}
		else if(this.isLoadContentInContainer) this.cnt.innerHTML = t.responseText;
	},//---------------------------------------------------------------------
	
	// Добавление кнопки "обновить" в контент. Используется при ошибках соединения и парсинга ответа 
	insertRefreshButton: function(){
		var btn;
		this.cnt.appendChild( btn = crElem('div', {'class':'buttons'}, '', [crElem('a', { 'href':'#', 'class': 'link-update' }, '', _t('repeat_request'))] ) );
		Event.observe(btn, 'click', function(obj){
			return function(event){
				obj.load(obj.params);
				Event.stop(event);
				return false;
			}
		}(this) );
	},//---------------------------------------------------------------------
	
	params: null,	// параметры используемые при запросе
	onLoad: null,	// функция выполняемая после загрузки контента
	onJsonDone: null,
	onJsonError: null,
	isJson: false, json: null,
	options: null,
	isLoadContentInContainer: false,	// загруженное содержимое будет помещено в контейнер cnt (container)
	clearMsgTimeout: 5000,
	clearMsgTimer: null,
	clearMsg: function() {
		this.cnt.update();
		this.clearMsgTimer = null;
		if(this.showHideOnLoad) this.cnt.hide();
	},//---------------------------------------------------------------------
	showHideOnLoad: false
};
/////////////////////////////////////////////////////////////////////////////



Event.onReady( function(){
	// Переключение языков
	/*$$('#lang-menu a').each( function(elem){
		Event.observe( elem, 'click', function(event){
			var btn = this, url = this.href;
			this.href = 'javascript:;';
			var conn = new CSrvConnect(null, '/srv/lang/get_url/', '', true);
			conn.onLoad = function(t){
				var json;
				try { json = eval('(' + t.responseText + ')'); }
				catch(e) { return; }
				if(typeof(json)!='undefined' && json.url) {
					document.location = json.url;
					Event.stop(event);
					btn.href = 'javascript:;';
					return false;
				}
				else {
					btn.href = url;
				}
			}
			conn.load( {'url':url} );
		} );
	} );*/

	
} );

//---------------------------------------------------------------------------
