/* js.phyp // 20080807 */

function phyp(root) {

    /// Init
    this.core = [ 'debug', 'timers', 'events',
		  'xml', 'asp' ];

    /// Library handler
    this.preload = function() {
	
	// Set root
	this.root = '/';

	// Load core modules
	this.loaded = new Object();
	this.loading = this.core.length;
	for (var i in this.core)
	    if (isKey(i))
		this.load(this.core[i]);

	// Start checker
	this.check();

    }

    /// Check
    this.check = function() {

	var ready = true;
	for (var i in p.core)
	    if (isKey(i))
		ready &= (p[p.core[i]] != null);

	// Ready?
	if (ready) p.init();
	else setTimeout("p.check()", 50);

    }

    /// Load
    this.load = function(js) {

	// Already loaded?
	if (this.loaded[js])
	    return false;

	// Create DOM node
	this.loaded[js] = true;
	var src = "/js/core/" + js + ".js";
	var js = DOM('script',
                     { src: src,
		       type: "text/javascript" });

	// Append to header
	d.getByTag('head')[0].appendChild(js);
	return true;

    }

    /// Empty debugger
    this.dbg = function() { return false; }

    /// Init core
    this.init = function() {

	// Start core modules
	for (var i in this.core) {
	    if (!isKey(i)) continue;
	    if (!this[this.core[i]])
		return p.dbg('js', 'error', 'phyp',
			     "Error parsing core module " + this.core[i]);
	    if (this[this.core[i]].init)
		this[this.core[i]].init();
	}

	// Ready!
	p.dbg('js', 'info', 'phyp', "core ready!");

    }

    /// Quit core
    this.quit = function(reboot) {

	// Quit core modules (reverse order)
	var shutdown = [ ];
	for (var i in this.core)
	    if (isKey(i) && this[this.core[i]].quit)
		shutdown.unshift(this.core[i]);
	for (var i = 0; i < shutdown.length; i++)
	    this[shutdown[i]].quit();

	// Reboot?
	if (reboot)
	    this.init();
	return false;

    }

    /// Reboot
    this.reboot = function() {
	this.quit(true);
	return false;
    }

    /// Launch
    this.launch = function(url, pid, data) {
	if (pid == null) pid = -1;
	this.xml.request({ url: '/xml/' + url,
		           data: data || { },
		           obj: this.X,
		           func: 'build',
		           params: pid });
	return true;
    }

}

var p = new phyp();
window.onload = phypInit;
function phypInit() { p.preload(); }
