/*global window, document */

/*
 * This file is called jquery.js because the index file on webspace includes jquery.js.
 * Rather than updating the index file (risky), we will just put a standalone version
 * of onReady here to keep it working.
 */

function onReady(f) {
	// Attach the listeners
	onReady.bindReady();

	// If the DOM is already ready
	if (onReady.isReady) {
		// Execute the function immediately
		f.call(window);
		// Otherwise, remember the function for later
	} else {
		// Add the function to the wait list
		onReady.readyList.push(function () {
		    return f.call(window);
	    });

		return this;
	}
}

onReady.isReady = false;
onReady.readyList = [];
onReady.ready = function () { // Handle when the DOM is ready
	// Make sure that the DOM is not already loaded
	if (!onReady.isReady) {
		// Remember that the DOM is ready
		onReady.isReady = true;

		// If there are functions bound, to execute
		if (onReady.readyList) {
			// Execute all of them
		    var numCalls = onReady.readyList.length,
		        i = 0;

		    for (; i < numCalls; i += 1) {
				onReady.readyList[i].call(window);
			}

			// Reset the list of functions
			onReady.readyList = null;
		}
	}
};

onReady.readyBound = false;

onReady.bindReady = function () {
	if (onReady.readyBound) {
		return;
	}
	onReady.readyBound = true;

	// Most browsers support this
	if (document.addEventListener) {
		// Use the handy event callback
		document.addEventListener("DOMContentLoaded", onReady.ready, false);
	}

	// A fallback to window.onload, that will always work
	if (window.addEventListener) {
		window.addEventListener('load', onReady.ready, false);
	} else if (window.attachEvent) {
		window.attachEvent("onload", onReady.ready);
	} else {
		var oldonload = window.onload;
		window.onload = function () {
			if (oldonload) {
				oldonload.call(window);
			}
			onReady.ready();
		};
	}
};

onReady.addEventHandler = function (element, event, fn, scope) {
    scope = scope || window;

    if (element.addEventListener) {
        element.addEventListener(event, function () {
            fn.apply(scope, arguments);
        }, false);
    } else if (element.attachEvent) {
        element.attachEvent('on' + event, function () {
            fn.apply(scope, arguments);
        });
    }
};

