/* Miscellaneous functions */
var isIE = document.all;
var isNN = !document.all && document.getElementById;
var isN4 = document.layers;

function windowLoaded(evt) {
    // prevent IE text selection while dragging!!! Little-known trick!
    document.body.ondrag = function () { return false; };
    document.body.onselectstart = function () { return false; };
}

function nodeOf() {
    var a = arguments;
    var r = new Array();
    for (var i=0; i<a.length; i++) {
	var o = a[i];
	if (typeof(o) == 'string') r.push(document.getElementById(o));
	else r.push(o);
    }
    if (r.length == 1) return r[0];
    return r;
}

function tags() {
    var a = arguments;
    var r = new Array();
    for (var i=1; i<a.length; i++)
	r[a[i]] = a[0].getElementsByTagName(a[i]);
    
    if (i == 2) return r[a[1]];
    return r;
}

function tagValue(node, tag) {
    return tags(node, tag)[0].firstChild.nodeValue;
}

function elementize() {
    var type = arguments[0];
    var nel;
    nel = document.createElement(type);
    for (var i=1; i<arguments.length; i++) {
	var attr = arguments[i].split(/=/);
	eval("nel." + attr[0] + " = '" + attr[1] + "';");
    }  
    return nel;
}

function texit(node, tex) {
    var texel = document.createTextNode(tex);
    foster(node, texel);
}

function foster() {
    var parent = arguments[0];
    for (var i=1; i<arguments.length; i++) {
	parent.appendChild(arguments[i]);
    }
    return parent;
}

function addZero(num) {
    if (num < 10)
	return "0" + num;
    else
	return num;
}

function createClient() {
    var client;
    try {
        client = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e) {
        alert("Sorry, your browser is not AJAX-enabled!");
    }
    return client;
}

function eventer (target,type,func,bubbles) {
    if (document.addEventListener) {
        target.addEventListener(type,func,bubbles);
    } else if (document.attachEvent) {
        target.attachEvent("on"+type,func,bubbles);
    } else {
        target["on"+type] = func;
    }
}

function reventer (target,type,func,bubbles) {
    if (document.removeEventListener) {
        target.removeEventListener(type,func,bubbles);
    } else if (document.detachEvent) {
        target.detachEvent("on"+type,func,bubbles);
    } else {
        target["on"+type] = null;
    }
}

function getX(node) { return parseInt(node.style.left, 10);   }
function getOX(node) { return parseInt(node.offsetLeft, 10);   }
function getY(node) { return parseInt(node.style.top, 10);    }
function getOY(node) { return parseInt(node.offsetTop, 10);    }
function getW(node) { return parseInt(node.style.width, 10);  }
function getOW(node) { return parseInt(node.offsetWidth, 10); }
function getH(node) { return parseInt(node.style.height, 10); }
function getOH(node) { return parseInt(node.offsetHeight, 10); }

function setX(node, x) { node.style.left = x + "px";   }
function setY(node, y) { node.style.top = y + "px";    }
function setW(node, w) { node.style.width = w + "px";  }
function setH(node, h) { node.style.height = h + "px"; }
function setPos(node, x, y) { 
    setX(node, x); 
    setY(node, y); 
}
function setSize(node, w, h) {
    setW(node, w);
    setH(node, h);
}

// From: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function browserSize() {
    var width = 0, height = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
	width = window.innerWidth;
	height = window.innerHeight;
    } else if( document.documentElement && 
	       ( document.documentElement.clientWidth || 
		 document.documentElement.clientHeight ) ) {
	//IE 6+ in 'standards compliant mode'
	width = document.documentElement.clientWidth;
	height = document.documentElement.clientHeight;
    } else if( document.body && 
	       ( document.body.clientWidth || document.body.clientHeight ) ) {
	//IE 4 compatible
	width = document.body.clientWidth;
	height = document.body.clientHeight;
    }
    return new Array(width, height);
}

function clearInfo() {
    info.innerHTML = '';
}

function report(msg, cr) {
    cr = cr ? cr : '<br>';
    info.innerHTML += msg + cr;
}

function setStyle() {
    var styles = arguments;
    var node = styles[0];
    for (var i=1; i<styles.length; i++) {
	var style = styles[i].split('=');
	eval ("node.style." + style[0] + " = '" + style[1] + "';"); 
    }
}

function setSelect(node, value) {
    for (var i=0; i<node.options.length; i++) {
	if (node.options[i].value == value) {
	    node.selectedIndex = i;
	    break;
	}
    }
}

function getSelectText(node) {
    if (node.selectedIndex < 0) {
	return false;
    }
    return node.options[node.selectedIndex].text;
}

function getSelectVal(node) {
    if (node.selectedIndex < 0) {
	return false;
    }
    return node.options[node.selectedIndex].value;
}

function describe(obj, cr) {
    if (typeof(obj) != 'object') return;
    var txt = '';
    cr = cr ? cr : "\n";
    for (var i in obj) {
	txt += i + ': '
	    + (typeof(obj[i]) == 'object' ? cr + describe(obj[i], cr) : obj[i]) 
	    + cr;
    }
    return txt;
}

function fit(node, holder) {
    setSize(node, getOW(holder), getOH(holder));
}


function Evt(evt) {
    this.evt = evt ? evt : window.event; 
    this.source = evt.target ? evt.target : evt.srcElement;
    this.x = evt.pageX ? evt.pageX : evt.clientX;    
    this.y = evt.pageY ? evt.pageY : evt.clientY;
    this.b = (this.evt.button != 'undefined') ? this.evt.button : this.evt.which;
    this.t = evt.type;
}

Evt.prototype.toString = function () {
    return "Evt [ x = " + this.x + ", y = " + this.y + " ]";
};

Evt.prototype.consume = function () {
    this.evt.cancelBubble = true;
    if (this.evt.stopPropagation) {
	this.evt.stopPropagation();
	this.evt.preventDefault();
    }
    /*
    if (this.evt.cancelBubble) {
	this.evt.cancelBubble = true;
	this.evt.cancel = true;
	this.evt.returnValue  = false;
    }
    */
};

Evt.addEventListener = function (target,type,func,bubbles) {
    if (document.addEventListener) {
	target.addEventListener(type,func,bubbles);
    } else if (document.attachEvent) {
	target.attachEvent("on"+type,func,bubbles);
    } else {
	target["on"+type] = func;
    }
};

Evt.removeEventListener = function (target,type,func,bubbles) {
    if (document.removeEventListener) {
	target.removeEventListener(type,func,bubbles);
    } else if (document.detachEvent) {
	target.detachEvent("on"+type,func,bubbles);
    } else {
	target["on"+type] = null;
    }
};

function getOpacity(node) {
    var o;
    if (node.filters) {
	try {
	    o = node.filters["alpha"].opacity/100;
	} catch (e) { }
    } else if (node.style.opacity) {
	o = node.style.opacity;
    }
    
    return parseFloat(o);
}

function setOpacity(node,val) {
    if (isIE) {
	try {
	    node.filters["alpha"].opacity = val*100;
	} catch (e) { 
	    node.style.filter = "alpha(opacity=" + val*100 + ")";
	}
    } else {
	node.style.opacity = val;
    }
}

function blink(id, by, to, rate, brake) {
    
}

// runs with setTimeout
function fadeIn_TO(id, to, by, rate, brake) {
    var arr = new Array("'" + id + "'", "'" + to + "'", by, rate+brake, brake);
    var node = nodeOf(id);
    var o = getOpacity(node) + by;
    if (o < 1) {
	setOpacity(node, o);
	eval(to + " = setTimeout(\"fadeIn(" + arr.join(', ') + ")\", " + rate + ")");
    } else {
	eval("clearTimeout(" + to + ")");
	setOpacity(node, 1);
    }
}

function fadeOut_TO(id, to, by, rate, brake) {
    var arr = new Array("'" + id + "'", "'" + to + "'", by, rate+brake, brake);
    var node = nodeOf(id);
    var o = getOpacity(node) - by;
    if (o > 0) {
	setOpacity(node, o);
	eval(to + " = setTimeout(\"fadeOut(" + arr.join(', ') + ")\", " + rate + ")");
    } else {
	eval("clearTimeout(" + to + ")");
	setOpacity(node, 0);
    }
}

// runs with setInterval
function fadeIn(id, to, by) {
    var node = nodeOf(id);
    var o = getOpacity(node) + by;
    if (o < 1) {
	setOpacity(node, o);
    } else {
	eval("clearInterval(" + to + "); " + to + " = null;");
	setOpacity(node, 1);
    }
}

function fadeOut(id, to, by) {
    var node = nodeOf(id);
    var o = getOpacity(node) - by;
    if (o > 0) {
	setOpacity(node, o);
    } else {
	eval("clearInterval(" + to + "); " + to + " = null;");
	setOpacity(node, 0);
    }
}

// From quirksmode                                                             
function windowSize() {
    var x,y;
    if (self.innerHeight) // all except Explorer                               
        {
            x = self.innerWidth;
            y = self.innerHeight;
        }
    else if (document.documentElement && document.documentElement.clientHeight)
        // Explorer 6 Strict Mode                                              
        {
            x = document.documentElement.clientWidth;
            y = document.documentElement.clientHeight;
        }
    else if (document.body) // other Explorers                                 
        {
            x = document.body.clientWidth;
            y = document.body.clientHeight;
        }
    return new Array(x, y);
}

function formatDates() {
    var args = formatDates.arguments;
    var dates = args[0];
    for (var i=1; i<arguments.length; i++) {
	dates.push(Date.parse(nodeOf(arguments[i]).value));
    }
}

function padZero(len) {
    var s = this.toString();
    while (s.length < len) {
	s = '0' + s;
    }
    return s;
}

// PHP related
function checkResult(xml) {
    if (tags(xml, 'result').length) {
        if (tagValue(xml, 'result') == 1) {
            if (tags(xml, 'next')) {
                eval (tagValue(xml, 'next'));
            }
        } else {
            alert(tagValue(xml, 'result'));
        }
    }
}

function parseXML(xml, obj, tag) {
    obj.items = {
	length: 0
    };
    if (xml) {
	var items = tags(xml, tag);
	obj.fields = tagValue(xml, 'sql_fields').split(',');
	obj.items.length = items.length;
    }
    if (!items) return false;
    for (var i=0; i<items.length; i++) {
	obj.items[i] = new Object();
	for (var j=0; j<obj.fields.length; j++) {
	    var f = obj.fields[j];
	    obj.items[i][f] = tagValue(items[i], f);
	}
    }
    return true;
}

function fixDateFormat(d) {
    var datetime = d.split(' ');
    var date = datetime[0].split('-');
    var time = datetime[1].split(':');
    datetime[0] = date[1] + '/' + date[2] + '/' + date[0];
    datetime[1] = time.join(':');
    return datetime.join(' ');
}

// PROTOTYPES
String.prototype.reverse = function() {
    splitext = this.split("");
    revertext = splitext.reverse();
    reversed = revertext.join("");
    return reversed;
}

Number.prototype.padZero = padZero;

//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(elt) {
	var len = this.length;

	var from = Number(arguments[1]) || 0;
	from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	if (from < 0) from += len;

	for (; from < len; from++) {
	    if (from in this && this[from] === elt)
		return from;
	}
	return -1;
    };
}

if (!Array.prototype.match) {
    Array.prototype.match = function(re) {
	var len = this.length;

	var from = Number(arguments[1]) || 0;
	from = (from < 0) ? Math.ceil(from) : Math.floor(from);
	if (from < 0) from += len;

	for (; from < len; from++) {
	    if (from in this && this[from].match(re))
		return from;
	}
	return -1;
    };
}

if (!Array.prototype.each) {
    Array.prototype.each = function(f) {
	if (typeof(f) == 'function') {
	    for (var i=0; i<this.length; i++) {
		this[i] = f(this[i]);
	    }
	}
	return this;
    };
}

