/*
Replaces text with by in string
*/
function replace(string, text, by) {
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}


/*
Trim a string from leading and trailing spaces
*/
function Trim(iString) {
  iString = iString.replace( /^\s+/g, "" );
  return iString.replace( /\s+$/g, "" );
}


/*
Find an object on the page
*/
function findObj(objName) {
	var theObj = document.getElementById(objName);
	
	if (!theObj) {
		//theObj = document.all[objName];
	}
	
	return theObj;
}


/*
Set the form element and display label to show an error
*/
function setFormError(iErrorName) {
	var tmpName = replace(iErrorName, '_error', '');
	
	if (!tmpName) { return false; }
	
	var tmpFormElem = findObj(tmpName);
	var tmpErrorLabel = findObj(tmpName + '_label');
	var tmpDisplayElem = findObj(tmpName + '_display');
	var tmpErrorTip = findObj(tmpName + '_tip');
	
	if (tmpDisplayElem) { tmpFormElem = tmpDisplayElem; }
	
	if (tmpFormElem) { tmpFormElem.className = tmpFormElem.className + ' errorElem'; }
	if (tmpErrorLabel) { tmpErrorLabel.className = tmpErrorLabel.className + ' errorCell'; }
	if (tmpErrorTip) { tmpErrorTip.style.display = ''; }
}


/*
The error element has been focuses so clear any error objects
*/
function cleanFormError(iErrorObj) {
	var tmpName = iErrorObj.name || iErrorObj.id;
	
	if (!tmpName) { return false; }
	
	var tmpFormElem = findObj(tmpName);
	var tmpErrorLabel = findObj(tmpName + '_label');
	var tmpErrorTip = findObj(tmpName + '_tip');
	
	if (tmpFormElem) { 
		if (tmpFormElem.className.indexOf('errorElem') > -1) {
			tmpFormElem.className = Trim(replace(tmpFormElem.className, 'errorElem', ''));
		}
	}
	
	if (tmpErrorLabel) { 
		if (tmpErrorLabel.className.indexOf('errorCell') > -1) {
			tmpErrorLabel.className = Trim(replace(tmpErrorLabel.className, 'errorCell', ''));
		}
	}
	
	if (tmpErrorTip) { tmpErrorTip.style.display = 'none'; }
}
