// add useful extensions to standard String class

String.prototype.ltrim = function() {
	return this.replace(/^\s+/g,'');
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/g,'');
}

String.prototype.trim = function() {
	return this.ltrim().rtrim();
}

String.prototype.left = function(n) {
	if (n <= 0)
		return '';
	var len = this.length;
	if (n >= len)
		return this;
	return this.substring(0,n);
}

String.prototype.right = function(n) {
	if (n <= 0)
		return '';
	var len = this.length;
	if (n >= len)
		return this;
	return this.substring(len - n, len);
}

// set state of all checkboxes with given name (e.g. setCheck('user_ids[]', true))
function setCheck(name, check) {
	var els = document.getElementsByName(name);
	for (var i = 0; i < els.length; i++) {
		var el = els[i];
		if (el.type == 'checkbox')
			el.checked = check;
	}
}

// check all checkboxes with given name
function checkAll(name) {
	setCheck(name, true);
}

// uncheck all checkboxes with given name
function checkNone(name) {
	setCheck(name, false);
}

// toggle checkbox with the given id
function toggleCheck(id) {
	var e = document.getElementById(id);
	if (e && e.type == 'checkbox')
		e.checked = !e.checked;
	return false;
}

// return if variable is a function
// note: this and other is..() functions are from http://www.crockford.com/javascript/remedial.html
function isFunction(a) {
	return typeof a == 'function';
}

// return if variable is an object
function isObject(a) {
	return (a && typeof a == 'object') || isFunction(a);
}

// return if variable is an array
function isArray(a) {
	return isObject(a) && a.constructor == Array;
}

// set visibility of an element / array of elements
function setVisibilities(ids, show) {
	if (!isArray(ids))
		setVisibility(id);
	for (var i = 0; i < ids.length; i++)
		setVisibility(ids[i], show);
}

// set visibility of an element / array of elements
function setVisibility(id, show) {
	if (isArray(id))
		setVisibilities(id, show);
	else {
		var el = document.getElementById(id);
		if (el) {
			var tagName = el.tagName.toLowerCase();
			if (navigator.appName != 'Microsoft Internet Explorer' && (tagName == 'tr' || tagName == 'td' || tagName == 'th')) {
				if (show)
					el.style.visibility = 'visible';
				else
					el.style.visibility = 'collapse';
			}
			else {
				if (show)
					el.style.display = 'block';
				else
					el.style.display = 'none';
			}
		}
	}
}

// switch focus to specified element
function setFocus(id) {
	var el = document.getElementById(id);
	if (el)
		el.focus();
}

