/* This function is used to change the style class of an element */
function swapClass(obj, newStyle) {
    obj.className = newStyle;
}

function isUndefined(value) {   
    var undef;   
    return value == undef; 
}

function checkAll(theForm, value) { // check all the checkboxes in the list
  for (var i=0;i<theForm.elements.length;i++) {
    var e = theForm.elements[i];
		var eName = e.name;
    	if (eName != 'allbox' && 
            (e.type.indexOf("checkbox") == 0)) {
        	e.checked = (typeof value != 'undefined') ? value : theForm.allbox.checked;		
		}
	}
  return false;
}

/* Function to clear a form of all it's values */
function clearForm(frmObj) {
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
		if(element.type.indexOf("text") == 0 || 
				element.type.indexOf("password") == 0) {
					element.value="";
		} else if (element.type.indexOf("radio") == 0) {
			element.checked=false;
		} else if (element.type.indexOf("checkbox") == 0) {
			element.checked = false;
		} else if (element.type.indexOf("select") == 0) {
			for(var j = 0; j < element.length ; j++) {
				element.options[j].selected=false;
			}
            element.options[0].selected=true;
		}
	} 
}

/* Function to get a form's values in a string */
function getFormAsString(frmObj) {
    var query = "";
	for (var i = 0; i < frmObj.length; i++) {
        var element = frmObj.elements[i];
        if (element.type.indexOf("checkbox") == 0 || 
            element.type.indexOf("radio") == 0) { 
            if (element.checked) {
                query += element.name + '=' + escape(element.value) + "&";
            }
		} else if (element.type.indexOf("select") == 0) {
			for (var j = 0; j < element.length ; j++) {
				if (element.options[j].selected) {
                    query += element.name + '=' + escape(element.value) + "&";
                }
			}
        } else {
            query += element.name + '=' 
                  + escape(element.value) + "&"; 
        }
    } 
    return query;
}

/* Function to hide form elements that show through
   the search form when it is visible */
function toggleForm(frmObj, iState) // 1 visible, 0 hidden 
{
	for(var i = 0; i < frmObj.length; i++) {
		if (frmObj.elements[i].type.indexOf("select") == 0 || frmObj.elements[i].type.indexOf("checkbox") == 0) {
            frmObj.elements[i].style.visibility = iState ? "visible" : "hidden";
		}
	} 
}

/* Helper function for re-ordering options in a select */
function opt(txt,val,sel) {
    this.txt=txt;
    this.val=val;
    this.sel=sel;
}

/* Function for re-ordering <option>'s in a <select> */
function move(list,to) {     
    var total=list.options.length;
    index = list.selectedIndex;
    if (index == -1) return false;
    if (to == +1 && index == total-1) return false;
    if (to == -1 && index == 0) return false;
    to = index+to;
    var opts = new Array();
    for (i=0; i<total; i++) {
        opts[i]=new opt(list.options[i].text,list.options[i].value,list.options[i].selected);
    }
    tempOpt = opts[to];
    opts[to] = opts[index];
    opts[index] = tempOpt
    list.options.length=0; // clear
    
    for (i=0;i<opts.length;i++) {
        list.options[i] = new Option(opts[i].txt,opts[i].val);
        list.options[i].selected = opts[i].sel;
    }
    
    list.focus();
} 

/*  This function is to select all options in a multi-valued <select> */
function selectAll(elementId) {
    var element = document.getElementById(elementId);
	len = element.length;
	if (len != 0) {
		for (i = 0; i < len; i++) {
			element.options[i].selected = true;
		}
	}
}

/* This function is used to select a checkbox by passing
 * in the checkbox id
 */
function toggleChoice(elementId) {
    var element = document.getElementById(elementId);
    if (element.checked) {
        element.checked = false;
    } else {
        element.checked = true;
    }
}

/* This function is used to select a radio button by passing
 * in the radio button id and index you want to select
 */
function toggleRadio(elementId, index) {
    var element = document.getElementsByName(elementId)[index];
    element.checked = true;
}

/* This function is used to open a pop-up window */
function openWindow(url, winTitle, winParams) {
	winName = window.open(url, winTitle, winParams);
    winName.focus();
}


/* This function is to open search results in a pop-up window */
function openSearch(url, winTitle) {
    var screenWidth = parseInt(screen.availWidth);
    var screenHeight = parseInt(screen.availHeight);

    var winParams = "width=" + screenWidth + ",height=" + screenHeight;
        winParams += ",left=0,top=0,toolbar,scrollbars,resizable,status=yes";

    openWindow(url, winTitle, winParams);
}

/* This function is used to set cookies */
function setCookie(name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

/* This function is used to get cookies */
function getCookie(name) {
	var prefix = name + "=" 
	var start = document.cookie.indexOf(prefix) 

	if (start==-1) {
		return null;
	}
	
	var end = document.cookie.indexOf(";", start+prefix.length) 
	if (end==-1) {
		end=document.cookie.length;
	}

	var value=document.cookie.substring(start+prefix.length, end) 
	return unescape(value);
}

/* This function is used to delete cookies */
function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// This function is for stripping leading and trailing spaces
function trim(str) { 
    if (str != null) {
        var i; 
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length); 
                break;
            } 
        } 
    
        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1); 
                break;
            } 
        } 
        
        if (str.charAt(0)==" ") {
            return ""; 
        } else {
            return str; 
        }
    }
} 

// This function is a generic function to create form elements
function createFormElement(element, type, name, id, value, parent) {
    var e = document.createElement(element);
    e.setAttribute("name", name);
    e.setAttribute("type", type);
    e.setAttribute("id", id);
    e.setAttribute("value", value);
    parent.appendChild(e);
}

function confirmDelete(obj) {   
    var msg = "Are you sure you want to delete this " + obj + "?";
    ans = confirm(msg);
    if (ans) {
        return true;
    } else {
        return false;
    }
}

function highlightTableRows(tableId, col) {
    var previousClass = null;
    var table = document.getElementById(tableId);
    if (table == null) return;
    var tbody = table.getElementsByTagName("tbody")[0];
    var rows;
    if (tbody == null) {
        rows = table.getElementsByTagName("tr");
    } else {
        rows = tbody.getElementsByTagName("tr");
    }
    // add event handlers so rows light up and are clickable
    for (i=0; i < rows.length; i++) {
        rows[i].onmouseover = function() { previousClass=this.className;this.className+=' over' };
        rows[i].onmouseout = function() { this.className=previousClass };
        if (typeof col != 'undefined') {
          rows[i].onclick = function() {
            var cell = this.getElementsByTagName("td")[col];
            var link = cell.getElementsByTagName("a")[0];
            if (link == null) {
                return false;
            }
            if (link.onclick) {
                var onclick = link.getAttribute("onclick");
                var exec = true;
                if (typeof onclick == 'function') {
                    onclick = onclick.toString();
                    exec = eval(onclick.substring(onclick.indexOf('{') + 1, onclick.lastIndexOf('}')).replace('return',''));
                } else if (typeof onclick == 'string') {
                    exec = eval(onclick.replace('return',''));
                }
                if (!exec) {
                    this.style.cursor="wait";
                    return false;
                }
                return false;
            }
            location.href = link.getAttribute("href");
            this.style.cursor="wait";
          }
        }
    }
}

function findLink(row) {
    var cells = row.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++) {
        var link = cells[i].getElementsByTagName("a")[0];
        if (typeof link != 'undefined') {
            return link;
        }
    }
    return null;
}

function highlightFormElements() {
    // add input box highlighting
    addFocusHandlers(document.getElementsByTagName("input"));
    addFocusHandlers(document.getElementsByTagName("textarea"));
}

function addFocusHandlers(elements) {
    for (i=0; i < elements.length; i++) {
        if (elements[i].type != "button" && elements[i].type != "submit" &&
            elements[i].type != "reset" && elements[i].type != "checkbox" &&
            elements[i].type != "radio" && elements[i].type != "image") {
            if (elements[i].getAttribute('readonly') != "readonly" && elements[i].getAttribute('readonly') != "disabled") {
                elements[i].onfocus=function() {this.style.backgroundColor='#ffd';this.select()};
                elements[i].onmouseover=function() {this.style.backgroundColor='#ffd'};
                elements[i].onblur=function() {this.style.backgroundColor='';}
                elements[i].onmouseout=function() {this.style.backgroundColor='';}
            }
        }
    }
}

function radio(clicked){
    var form = clicked.form;
    var checkboxes = form.elements[clicked.name];
    if (!clicked.checked || !checkboxes.length) {
        clicked.parentNode.parentNode.className="";
        return false;
    }

    for (i=0; i<checkboxes.length; i++) {
        if (checkboxes[i] != clicked) {
            checkboxes[i].checked=false;
            checkboxes[i].parentNode.parentNode.className="";
        }
    }

    // highlight the row    
    clicked.parentNode.parentNode.className="over";
}

function stopPropagation(event) {
    event.cancelBubble = true;
    return false;
}

function toggleDisplay(objId) {
    var obj = document.layers ? document.layers[objId] :
      document.getElementById ? document.getElementById(objId).style :
        document.all[objId].style;
    obj.display = (obj.display == "none") ? "" : "none";
    return obj.display;
}

function reverse(fldObj, idx) {
    if (fldObj.type == "checkbox") {
        fldObj.checked = (fldObj.checked) ? false : true;
    } else if (fldObj.length) {
        fldObj[idx].checked = (fldObj[idx].checked) ? false : true;
    }
}

function executeScripts(content, remote) {
    // handle <script src="foo"> first
    var src = new RegExp('<script.*?src=".*?"');
    var repl = new RegExp('<script.*?src="');
    var matches = src.exec(content);
    var semaphore = 0;

    if (remote && matches != null)
    {
        for (i = 0; i < matches.length; i++)
        {
            // get the src of the script
            var scriptSrc = matches[i].replace(repl, '');
            scriptSrc = scriptSrc.substring(0, scriptSrc.length-1);

            // this evals remote scripts
            dojo.io.bind({
                url:      scriptSrc,
                load:     function(type, evaldObj) {/* do nothing */ },
                error:    function(type, error) {alert(type); alert(error);
/* do nothing */ },
                mimetype: "text/javascript",
                sync:     true
            });
        }
    }

    // Remove the script tags we matched
    repl = new RegExp('<script.*?src=".*?".*?</script>');
    content = content.replace(repl, '');

    // Next, handle inline scripts

    // Clean up content: remove inline script  comments
    repl = new RegExp('//.*?$', 'gm');
    content = content.replace(repl, '\n');

    // Clean up content: remove carraige returns
    repl = new RegExp('[\n\r]', 'g');
    content = content.replace(repl, ' ');

    // Match anything inside <script> tags
    src = new RegExp('<script.*?</script>', 'gi');
    matches = content.match(src);

    // For each match that is found...
    if (matches != null)
    {
        for (i = 0; i < matches.length; i++)
        {
            // Remove begin tag
            var repl = new RegExp('<script.*?>', 'gim');
            var script = matches[i].replace(repl, '');

            // Remove end tag
            repl = new RegExp('</script>', 'gim');
            script = script.replace(repl, '');

            // Execute commands
            setTimeout(script, 250);
        }
    }
    
    // Execute dojo
    dojo.hostenv.makeWidgets();
    dojo.hostenv.modulesLoaded();
}

function getSelected(opt) {
    if (!opt) return null;
    var selected = new Array();
    var index = 0;
    if (opt.length) {
        for (var i = 0; i < opt.length; i++) {
            if ((opt[i].selected) ||
                (opt[i].checked)) {
                index = selected.length;
                selected[index] = opt[i].value;
            }
        }
    } else if (opt.selected || opt.checked) {
        selected[0] = opt.value;
    }
    return selected;
}
function setSelected(opt, sel) {
    if (!opt || !sel || sel.length == 0) return;
    if (opt.length) {
        for (var i = 0; i < opt.length; i++) {
            if (search(opt[i].value, sel)) {
                opt[i].checked = true;
            }
        }
    } else {
        if (search(opt.value, sel)) {
            opt.checked = true;
        }
    }
}
function search(val, arr) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            return true;
        }
    }
    return false;
}
function getTarget(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    return targ;
}
/*
window.onload = function() {
    highlightFormElements();
    if ($('successMessages')) {
        new Effect.Highlight('successMessages');
        // causes webtest exception on OS X : http://lists.canoo.com/pipermail/webtest/2006q1/005214.html
        // window.setTimeout("Effect.DropOut('successMessages')", 3000);
    }
    if ($('errorMessages')) {
        new Effect.Highlight('errorMessages');
    }
}
*/

// Show the document's title on the status bar
//window.defaultStatus=document.title;

