﻿/*
 *	vFramework v0.1
 *	A collection of useful cross-browser JavaScript procedures.
 *	 
 */
 
var vFramework = {
	Debug : {
		timeProfiler : {}
	}
};

vFramework.propertyExists = function(obj, property) {
	if (obj == undefined || property == undefined)
		return false;
	
	var parts = property.split('.');
	var ppath = obj;
	for(var i = 0; i < parts.length; i++)
		if ((ppath = ppath[parts[i]]) == undefined)
			return false;
	
	return true;
}

vFramework.getCursorPos = function(node) {
	if (vFramework.propertyExists(document, "selection.createRange"))
		return -document.selection.createRange().moveStart("character", -100);
	else if (node && node.selectionStart)
		return node.selectionStart;
	else if (!document.selection)
		return 0;
		
	return -1;
}

vFramework.getSrcElement = function(ev) {
	if (ev == undefined) ev = event;
	return ev.srcElement != undefined ? ev.srcElement :  ev.target;
}

vFramework.getOrCreateHidden = function(name) {
	var hiddens = document.getElementsByTagName('INPUT');
	
	if (hiddens) {	// hidden uses name not id, so loop is required.
		for(var i = 0; i < hiddens.length; i++)
			if (hiddens[i].type == 'hidden' && hiddens[i].name == name)
				return hiddens[i];
	}
	
	var obj = document.createElement('INPUT');
	obj.setAttribute('name', name);
	obj.setAttribute('type', 'hidden');
	document.body.appendChild(obj);
	
	return obj;
}

/*	timeProfiler is a stopwatch for measuring execution speed of
 	various parts of code. stop() alerts timestamps of the last run.
 	
 	aka vfw.dbg.tprof
*/

vFramework.Debug.timeProfiler.start = function() {
	this._splits = [];
	this._msec = new Date;
}

vFramework.Debug.timeProfiler.split = function() {
	this._splits.push(new Date - this._msec);
	this._msec = new Date;
}

vFramework.Debug.timeProfiler.stop = function() {
	this.split();
	alert(this._splits);
}

// aka vfw.dbg.btrace
vFramework.Debug.callStack = function() {
	if (arguments.caller == undefined) {	// Firefox
		var err = new Error;
		if (err.stack) alert(err.stack);
		return;
	}

	var callStack = 'Stack of Calls (last call is at the top):\n\n';	
	var strCaller = arguments.caller.callee;
	
	for(strCaller; strCaller != null; strCaller = strCaller.caller) {
		var s = strCaller.toString();
		callStack += s.substring(s.indexOf(' ')+1, s.indexOf('(')) + '(';
		for(var i = 0; i < strCaller.arguments.length; i++) {
			if (i == strCaller.arguments.length-1)
				callStack += strCaller.arguments[i] + '';
			else
				callStack += strCaller.arguments[i] + ', ';
		}
		callStack += ')\n';
			
	}
	alert(callStack);
}
