/**
 * 
 * @version $Id: XLibrary.js,v 1.1 2007/09/26 14:51:13 Andrew Exp $
 */

// Обработчик ошибок и функция на все случаи - В реальной работе следует возвратить null
window.onerror = function (e) {
	alert('Ошибка: ' + arguments[0] + '\r\nСтрока: ' + arguments[2] + '\r\nФайл: ' + arguments[1])
}

// Краткая версия document.getElementById
// oiv: Убрал, чтобы с jquery не конфликтовала
/*$  = function (id) { 
	if (typeof(id) == 'object') {
		return id;
	} else {
		return document.getElementById(id);
	}
}*/


/**
 * Библиотека часто используемых функций
 * last modified: 6.07.2007 19-00
 * 
 * + XLibraryExt
 * + XLTable
 * + XLForm
 */
function XLibrary() {

	// MOUSE

	// Координта мышки в данный момент
	this.mouse = function (e) {
		var compat  = (document.compatMode && document.compatMode == "CSS1Compat");
		var oCanvas = document.getElementsByTagName(compat ? "HTML" : "BODY")[0];
		x = window.event ? event.clientX + oCanvas.scrollLeft : e.pageX;
		y = window.event ? event.clientY + oCanvas.scrollTop : e.pageY;
		return {x:x, y:y}
	}
	
	// ELEMENT
	
	// Положение и размеры объекта
	this.bounds = function (obj) { 
		this.x = 0;
		this.y = 0;
		this.w = obj.offsetWidth;
		this.h = obj.offsetHeight;
		while (obj) {
			this.x += Number(obj.offsetLeft);
			this.y += obj.offsetTop;
			obj = obj.offsetParent;		
		}
		return {x:this.x, y:this.y, w:this.w, h:this.h};
	}	
	
	// Показать / скрыть элемент (с учётом разных display)
	this.showhide = function (id, displ) {	
		if ($(id).style.display == 'none') {
			$(id).style.display = displ;
		} else {			
			$(id).style.display = 'none';
		}
	}
	
	// deletes an element
	this.remove = function(objElement)	{
		if (objElement && objElement.parentNode && objElement.parentNode.removeChild)	{
			objElement.parentNode.removeChild(objElement);
		}
	}
	
	// xajax.create creates a new child node under a parent
	this.create = function(sParentId, sTag, sId) {
		var objParent = $(sParentId);
		objElement = document.createElement(sTag);
		objElement.setAttribute('id',sId);
		if (objParent)
			objParent.appendChild(objElement);
	}
	
	// xajax.insert inserts a new node before another node
	this.insert = function(sBeforeId, sTag, sId) {
		var objSibling = $(sBeforeId);
		objElement = document.createElement(sTag);
		objElement.setAttribute('id',sId);
		objSibling.parentNode.insertBefore(objElement, objSibling);
	}

	// xajax.insertAfter inserts a new node after another node
	this.insertAfter = function(sAfterId, sTag, sId) {
		var objSibling = $(sAfterId);
		objElement = document.createElement(sTag);
		objElement.setAttribute('id',sId);
		objSibling.parentNode.insertBefore(objElement, objSibling.nextSibling);
	}
	
	// EVENTS
	
	this.addEvent = function(o, e, a) {
		if (o.addEventListener) {
			o.addEventListener(e, a, false);
		}	else if (o.attachEvent) {
			o.attachEvent("on" + e, a);
		}	else {
			return null;
		}
	}	
	this.removeEvent = function(o, e, a){
		if (o.removeEventListener) {
			o.removeEventListener(e, a, false);
		} else if (o.detachEvent) {
			o.detachEvent("on" + e, a);	
		}	else {
			return null;
		}
	}	
	
	// WINDOW
	
	// текущий скролл
	this.getPageScroll = function () {
		if (document.all) {
			this.x = document.body.scrollLeft
			this.y = document.body.scrollTop
		} else {
			this.x = window.scrollX
			this.y = window.scrollY	
		}
		return {x:this.x, y:this.y};
	}
	
	// Размеры окна
	this.pageBounds = function () {
		var compat = (document.compatMode && document.compatMode == "CSS1Compat");
		var oCanvas = document.getElementsByTagName(compat ? "HTML" : "BODY")[0];
		if (oCanvas.clientWidth) {
			var w  = oCanvas.clientWidth + oCanvas.scrollLeft;
			var h = oCanvas.clientHeight + oCanvas.scrollTop;
		} else {
			var w  = window.innerWidth + window.pageXOffset;
			var h = window.innerHeight + window.pageYOffset;
		}
		return {w:w, h:h};
	}
	
	// открыть окно
	this.open = function (url, w, h, x, y) {
		if (x == undefined) {
			x = (screen.width - w)  / 2;
			y = (screen.height - h) / 2;
		}
		var w = window.open(url, 'wind', 
		"width=" + w + ", height=" + h + ", "+
		"resizable=no, scrollbars=no, menubar=no, status=no, location=no, fullscreen=no, directories=no, "+
		"screenX=" + x + ", screenY=" + y + ", left=" + x + ", top=" + y)	
		return w
	}
	
	// MISC
	
	// xajax.include(sFileName) dynamically includes an external javascript file
	this.include = function(sFileName) {
		var objHead = document.getElementsByTagName('head');
		var objScript = document.createElement('script');
		objScript.type = 'text/javascript';
		objScript.src = sFileName;
		objHead[0].appendChild(objScript);
	}
	
	// Подтверждение перехода по ссылке
	// обязательно передавать this, т.к. без него нельзя передать message
	this.check = function (obj, message) {
		if (is_null(message)) {
			message = 'текущее действие';
		}
		if (confirm('Подтвердите: ' + message)) {
			window.location.href = obj.href
		} else {
			return false
		}
	}
}

// VARIABLE

is_null = function (v) {
	return (typeof(v) == 'undefined');
}

// STRING	

trim = function (s) {
	s = s.replace(/[\s\t\r\n]+$/, '')
	return s.replace(/^[\s\t\r\n]+/, '')
}	
str_replace = function (srch, repl, str) {
	while (str.indexOf(srch) != -1) {
		str = str.replace(srch, repl)
	}
	return str
}


/**
 * Возврвщает простой блок для создания диалогового окна - т.е. тег DIV
 * @param string ID существующего или создаваемого блока
 */
function createFlyBlock (id, style) {
	var xl = new XLibrary();
	if (!(element = document.getElementById(id))) {
		var element = document.createElement('div');
		document.body.appendChild(element);
		if (!is_null(style)) {
			for (var i in style) {
				element.style[i] = style[i];
			}
		} else {
			with (element.style) {
				padding = '10px';
				font = '12px Arial';
				backgroundColor = '#eeeeee';				
				borderTop    = '1px solid black';
				borderLeft   = '1px solid black';
				borderBottom = '3px solid black';
				borderRight  = '3px solid black';
				color = '#000000';
				position = 'absolute';
				display = 'none';
			}
		}
	}
	element.id = id;
	return element;
}

// ТЕСТ

// отображение свойство объекта
function testObject(obj, output) {
	if (typeof(obj) != 'object') {
		alert('Это не объект');
		return false;
	}
	var s = new Array();
	for (var i in obj) {
		s.push('obj.' + i + ' = ' + obj[i]);
	}
	if (output == 'status') {
		window.status = s.join(' / ');
	} else {
		alert(s.join('\n'));
	}	
}

// трассировка
function trace(s, mode, rpl) {
	if (mode == 'status') {
		window.status += s;
	} else if (mode == 'title') {
		document.title += s;
	} else {
		var d = createFlyBlock('traceBlock', {
			border   : '1px solid black',
			backgroundColor : '#ffffff',
			padding  : '5px',
			fontSize : '10px',
			color    : '#000000',
			position : 'absolute',
			top      : '10px',
			left     : '10px'
		});
		if (rpl) {
			d.innerHTML = s;
		} else {
			d.innerHTML = d.innerHTML + s;
		}		
	}
}


// ЧАСТО ИПОЛЬЗУЕМЫЕ ОБЪЕКТЫ

/**
 * Определение браузеров
 */
var userAgent = navigator.userAgent.toLowerCase();
var is = {
	ie    : document.all,
	ns4   : document.layers,
	ns6   : document.getElementById && !document.all,
	opera : (userAgent.indexOf("opera") != -1) && (userAgent.indexOf("msie") == -1),
	moz   : (userAgent.indexOf("mozilla") != -1) && (userAgent.indexOf("msie") == -1),
	dom   : document.getElementById ? true : false,
  win   : ((userAgent.indexOf("win") != -1) || (userAgent.indexOf("16bit") != -1)),
	mac   : userAgent.indexOf("mac")  != -1,
  nix   : ((userAgent.indexOf("x11") != -1) || (userAgent.indexOf("linux") != -1))
}

/**
 * Работа с cookie
 */
cook = {
	// установить куки name = value на expires (ДНЕЙ)
	set : function(name, value, expires, path, domain, secure) {
		var expl = new Date();
		var expires = expl.getTime() + (expires * 24 * 60 * 60 * 1000);
		expl.setTime(expires);
		expires = expl.toGMTString();
		var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires: "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "")
		document.cookie = curCookie;
		return curCookie;		
	},
	get : function(name) {
		var d = document.cookie; var prefix = name + "="; var s = d.indexOf(prefix); if (s == -1) { return false; } 
		var e = d.indexOf(";", s + prefix.length); if (e == -1) { e = d.length; } 
		return unescape(d.substring(s + prefix.length, e)); 
	}	
}
