// InBusiness - Web Solutions for Business
// Copyright (C) 1999-2005 InsourceUA
//
// For further information go to http://www.inbusiness.com.ua
// or contact info@insource.com.ua
//
// Config
//
// $Id

// Функции:
// Настройки библиотеки скриптов
// Дополнительные настройки
// Загрузчик скриптов

// Настройки библиотеки скриптов
//
config = {
	loader: {
		// управление структурой
		//scripts: [ '+core', '+dom', '+form', '+http', 'layer', '+tab', '+table', '+w3c', 'misc' ],
		// tab - используется где есть табики
		// http - отображение баннера - pack/cBanner/js/get-img-banner.xsl
		scripts: [ 'core', 'dom', 'form', 'http', 'tab'],
		root: '/js/classes/'
	},
	
	debug: {
		type: '',	// { 'all', 'ie', 'moz', '' }
		font: 'lucida console',
		windowHeight: 600,
		windowWidth: 800,
		classes: {
			core: false, dom: false, form: true, http: true, layer: true,
			tab: true, table: true, w3c: true, misc: true
		},
		debugflag: false,
		errorhandler: true
	},
	
	classes: {
		tab: {
			autoevents: true
		}
	}
}

// Дополнительные настройки
// Описание:
// На странице можно определить дополнительные настройки для библиотеки скриптов,
// для этого необходимо создать объект с именем libconf и занести туда настройки.
if (typeof(libconf) == 'object') {
	mergeObject(libconf, config);
}
// mergeObject - сливание объектов
function mergeObject(src, dst) {
	for (var name in src) {
		switch (typeof dst[name]) {
			case 'object':
				mergeObject(src[name], dst[name]);
				break;
			case 'array':
				dst[name] = dst[name].concat(src[name]);
				break;
			default:
				dst[name] = src[name];
		}
	}
}

// defined - определен ли объект
function defined(o) {
	return Boolean(typeof(o) != 'undefined');
}

function isObject(o) {
	return Boolean(typeof(o) == 'object');
}

function isString(o) {
	return Boolean(typeof(o) == 'string');
}

function isNumber(o) {
	return Boolean(typeof(o) == 'number');
}

function isFunction(o) {
	return Boolean(typeof(o) == 'function');
}

function isEmpty(s) {
	return Boolean(s == '');
}

function isNull(o) {
	return Boolean(o == null);
}

// eventMultiplexer - одно событие - несколько обработчиков
//
var eventMultiplexer = {
	add: function (eventName, func) {
		if (isString(eventName) && isFunction(func)) {
			this.setEvent(eventName, func);
		}
	},

	getObjEvent: function (obj, name) {
		return (function(e) {
			e = e || window.event;
			return obj[name](e, this);
		});
	},

	setEvent: function (name, func) {
		if(isFunction(window.addEventListener)) {
			return window.addEventListener(name, func, true);
		}
		if(isObject(window.attachEvent)) {
			return window.attachEvent('on' + name, func);
		}
	}
};

var __host = '';
// getHost - возвращает текущий хост вида http://example.com
//           результат кэшируется
function getHost() {
	if (__host == '') {
		var endOfProtocol = document.location.href.indexOf('/') + 2;
		var base = document.location.href.substring(0, endOfProtocol);
		var minusBase = document.location.href.substring(endOfProtocol, document.location.href.length);
		var hostName = minusBase.substring(0, minusBase.indexOf('/'));
		__host = base + hostName;
	}
	return __host;
}

// Загрузчик скриптов
//
var loader = {
	isLoading: false,
	queue: [],
	onEmpty: null,

	// addScript - добавить скрипт в очередь загрузки
	addScript: function (name) {
		if(isString(name)) {
			this.queue[this.queue.length] = name;
		}
	},

	// loadQueue - загрузить готовый список скриптов
	loadQueue: function (queue) {
		if (isObject(queue)) {
			this.queue = null;
			this.queue = queue;
			this.load();
		}
	},

	// loadScript - добавление скрипта в DOM (внутренняя)
	loadScript: function (uri) {
		// создадим новый элемент в DOM
		var e = document.createElement('script');
		e.type = 'text/javascript';
		
		// добавим созданный элемент в тэг head
		document.getElementsByTagName('head')[0].appendChild(e);
		
		// начало загрузки
		e.src = uri;
	},

	// checkQueue - проверка и загрузка очереди
	checkQueue: function () {
		// если очередь не пуста то установим флаг загрузки
		if(this.queue.length > 0) {
			this.isLoading = true;

			// сформируем пути
			/*var endOfProtocol = document.location.href.indexOf('/') + 2;
			var base = document.location.href.substring(0, endOfProtocol);
			var minusBase = document.location.href.substring(endOfProtocol, document.location.href.length);
			var hostName = minusBase.substring(0, minusBase.indexOf('/'));*/
			var name = this.queue[0];
			var scriptPath = getHost() + config.loader.root + name + '/' + name + '.js';
			//var scriptPath = base + hostName + config.loader.root + name + '/' + name + '.js';
			
			this.loadScript(scriptPath);
			
			// удалим первый элемент из очереди
			var newQueue = new Array();
			for(i = 1; i < this.queue.length; i++) {
			  newQueue[i - 1] = this.queue[i];
			}
			this.queue = null; this.queue = newQueue;

			// проверка очереди
			this.checkQueue();
		}
		else {
			// если нет скриптов в очереди, то сбросим флаг загрузки
			this.isLoading = false;
			this.queue = null;
			// вызов функции когда нет скриптов для загрузки
			if(isFunction(this.onEmpty)) {
				this.onEmpty();
			}
		}
	},

	// load - загрузка очереди
	load: function () {
		if(!this.isLoading) {
			this.checkQueue();
		}
	}
}

// Загрузка скриптов
loader.loadQueue(config.loader.scripts);

document.insource = new Object();
