// Various JavaScript utilities

// set focus to an input field
function setfocus(a_field_id) {
    $(a_field_id).focus();
}

// upper case the first letter in a string of words with remaining characters in lower case
function ucwords( str ) {
	str.toLowerCase();
	return str.replace(/(\w+)/g, function ( $1 ) { return $1.capitalize ( ); } )
}


function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}


// duplicate a plusminus template
function plusminus_duplicate_div(template_div_name, destination_container_name)
{
	var clone = document.getElementById(template_div_name).cloneNode(true);
	clone.setAttribute('id', template_div_name + '_clone'); // change the name of the clone
	clone.setAttribute('class', template_div_name + '_clone'); // change the class of the clone
	clone.style.display = 'block';							// template is always hidden by default so we clear that here in the clone
  	document.getElementById(destination_container_name).appendChild(clone);
	return clone;
}

// delete a plusminus div
function plusminus_delete_div(div)
{
	new Effect.Fade(div);
	div.parentNode.removeChild(div);
}


// return the index of the first fieldname in formname or -1 if not found
function find_first_of(fieldname, formname)
{
	for (i=0; i<document.getElementById(formname).elements.length; i++) {
		if (document.getElementById(formname).elements[i].name == fieldname) {
			return i;
		}
	}
	return -1;
}

// return the index of the last fieldname in formname or -1 if not found
function find_last_of(fieldname, formname)
{
	for (i=document.getElementById(formname).elements.length-1; i>=0; i--) {
		if (document.getElementById(formname).elements[i].name == fieldname) {
			return i;
		}
	}
	return -1;
}

// Return a count of the number of fieldname in the formname
function count_of(fieldname, formname)
{
	var c = 0;
	for (i=0; i<document.getElementById(formname).elements.length; i++) {
		if (document.getElementById(formname).elements[i].name == fieldname) {
			c++;
		}
	}
	return c;
}

// hide or show the selected item (div)
function showhide(layer, show) {
	document.getElementById(layer).style.display = show ? 'block' : 'none'; 
}

// toggle the visibility of a layer item
function toggle(layer) {
	showhide(layer, document.getElementById(layer).style.display == 'none');
}

// add item to select element the less elegant, but compatible way.
function appendOptionGroupToSelect(select, content) {
    var optgroup;
    optgroup = document.createElement('optgroup');
   	if ((navigator.appVersion.toLowerCase().indexOf('safari') != -1) ||	// Safari requires optgroup.label, Firefox shows doubles when it is filled in
   		(navigator.appVersion.toLowerCase().indexOf('msie') != -1))		// IE also requires optgroup.label
   		optgroup.label = content.nodeValue;
    optgroup.appendChild(content);
    select.appendChild(optgroup);
    return optgroup;
}

// add item to select element the less elegant, but compatible way.
function appendOptionToSelect(select, value, content, disabled) {
	var opt;
    opt = document.createElement('option');
    opt.value = value;
    if (disabled)
		opt.disabled = 'disabled';
    opt.appendChild(content);
    select.appendChild(opt);
}

// given a select item (popup menu) and a value, the item will be selected if it exists
function select_item_by_value(select, value)
{
	for (i=0; i<select.options.length; i++) {
		if (select.options[i].value == value) {
			select.selectedIndex = i;
			break;
		}
	}
}

// see if an item exists in a select
function select_item_exists_by_value(select, value)
{
	for (i=0; i<select.options.length; i++) {
		if (select.options[i].value == value) {
			return true;
		}
	}
	return false;
}

function is_email(sText)
{
	var at = sText.indexOf('@');
	var dot = sText.indexOf('.', at);
	return ((at != -1) && (dot != -1));
}

function is_numeric(sText, fWhole)
{
   var ValidChars = "0123456789";
	if (!fWhole)
		ValidChars = ValidChars + '.';
   var IsNumber=true;
   var Char;
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
}

/* This is much faster than using (el.innerHTML = str) when there are many
existing descendants, because in some browsers, innerHTML spends much longer
removing existing elements than it does creating new ones. 
http://ajaxian.com/archives/replacehtml-for-when-innerhtml-dogs-you-down
http://stevenlevithan.com/demo/replaceHtml.html
*/
function replaceHtml(el, html) {
        var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
        var newEl = document.createElement(oldEl.nodeName);
        // Preserve the element's id and class (other properties are lost)
        newEl.id = oldEl.id;
        newEl.className = oldEl.className;
        // Replace the old with the new
        newEl.innerHTML = html;
        oldEl.parentNode.replaceChild(newEl, oldEl);
        /* Since we just removed the old element from the DOM, return a reference
        to the new element, which can be used to restore variable references. */
        return newEl;
};

// backlink object initializer
function backlink() {
	this.text = 'Back to Previous Page';
	this.type = 'button'; // button, link
	this.write = backlink_write;
	this.form = true;
}


// write method
function backlink_write() {
	if (! window.history) return;
	if (window.history.length == 0)return;

	this.type = this.type.toLowerCase();
	if (this.type == 'button') {
		if (this.form)
			document.write('<form>');
		document.write('<input type="button" onClick="history.back(-1)" VALUE="', this.text, '"');
		if (this.otheratts) document.write(' ', this.otheratts);
		document.write('>');
		if (this.form)document.write('<\/form>');
	} else {
		document.write('<a href="javascript:history.back(-1)">' + this.text + '<\/a>');
	}
}
