// base.js
// a base set of utility methods
// to extend the window.TAP object with page-specific utilities, use $.extend
if (!window.console || !console.firebug)
{
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
	"group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

	window.console = {};
	for (var i = 0; i < names.length; ++i)
		window.console[names[i]] = function(){};
}

window.TAP = {

	// extend js objects to have Perl-like capabilities
	Hash: function(obj)
	{
		this.hash = obj;
		this.keys = function(){
			var keys = [];
			for (var i in this.hash)
				if (this.hash.hasOwnProperty(i))
					keys.push(i);
			return keys;
		};
		this.values = function(){
			var keys = this.keys();
			var values = [];
			for (var i in keys)
				values.push(this.hash[i]);
			return values;
		};
		this.get = function(key){
			return this.hash[key];
		};
		this.length = function(){
			return this.keys().length;
		};

		return this;
	},

	// fill out a form with a js object
	fillForm: function(record)
	{
		console.log('fillForm invoked');
		for (var field in record )
		{
			//find input
			//we may augment the record to include namespace for forms
			//var $obj = $(':input[name=' + field + ']');
			field_selector = '#' + field.replace(/\./g, '\\.');
			var $obj = $(field_selector);
			if ( $obj.size() )
			{
				//determine what it is and what to do
				switch ( $obj.get(0).type )
				{
					case 'hidden' :
					case 'text' :
					case 'textarea' :
						$obj.val( record[field] );
						break;

					case 'radio' :
						var $temp = $obj.filter('input[value=' + record[field] + ']')
						if ( $temp.size() )
                                                        $temp.get(0).checked = true;
						else if ( window.console )
                                              ;      //console.warn(field, 'found, but no matching value found');
						break;

					case 'checkbox' :
						if ( record[field] == 't' )
							$obj.get(0).checked = true;
						break;

					case 'select-multiple' :
					case 'select-one' :
						var $temp = $obj.find('option[value=' + record[field] + ']');
						if ( $temp.size() )
							$temp.get(0).selected = true;
						else if ( window.console )
							; //console.warn(field, 'found, but no matching option');
						break;

					default:
						if (window.console)
							; //console.warn(field, 'found, but did not match any known input type');
				}
			}
			else if ( window.console )
				; //console.warn('WARNING: Input not found for ' + field);
		}

	}

};
