/**
 * POPUP & DIV HANDLING
 */
 
var AJAX_RESULT_SEPERATOR ='&^';
 window.onscroll = scrolling;

 //replace DIV elements of class 'popup' and 'ajaxprogress' in the window
 //when scrolling. this function is a hack for lack of the functionality 
 //'position: fixed;" in internet explorer
 function scrolling() {
  var sY;
  var sX;
  if (window.scrollY) {
   sY = window.scrollY;
   sX = window.scrollX;
  } else {
   sY = window.document.body.scrollTop;
   sX = window.document.body.scrollLeft;
  }
  var divs = document.getElementsByTagName("div");
  for (i=0;i<divs.length;i++) {
   var div = divs[i];
   //if (div.className=="popup" || div.className=="ajaxprogress") {
   if (div.className=="popup") {
    if (!div.origTop) {
      div.origTop = div.offsetTop;
      div.origLeft = div.offsetLeft;
    }
    div.style.top = eval(div.origTop + sY) + "px";
    div.style.left = eval(div.origLeft + sX) + "px";
   }
  }
 }

function ajaxLoginForm(formName) {
    args = "username=" + formName.username.value + "&password=" + formName.password.value + "&loginattempt=" + formName.loginattempt.value;
    makeAjaxCall('DisplayUserName', 'ajaxLoginFormCallback', args);
}
function ajaxLoginFormCallback(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    document.getElementById('loginformid').innerHTML = content;
}

 //show a DIV with a particular ID attribute
 function showDiv(id) {
  var popup = document.getElementById(id);
    if (popup) {
  popup.style.visibility = 'visible';
  popup.style.display = 'block';
 }
 }

 //hide a DIV with a particular ID attribute
 function hideDiv(id) {
  var popup = document.getElementById(id);
    if (popup) {
  popup.style.visibility = 'hidden';
  popup.style.display = 'none';
 }
 }
 
 function switchDiv(id) {
  var popup = document.getElementById(id);
  var v = popup.style.visibility;
  if (v=='hidden' || v=="") {
   showDiv(id);
  } else {
   hideDiv(id);
  }
 }

 function swapDiv(id1, id2) {
    switchDiv(id1);
    switchDiv(id2);
 }
 
 function showErrorPopup(message) {
  //var content = document.getElementById('generic_error_content');
  //content.innerHTML = message;
  //showDiv('generic_error');
  alert(message);
 }
 
 function dynamicFieldToggleText(linkId) {
    var link = document.getElementById(linkId);
    var text = link.innerHTML;
    if (text=="click to edit") {
        link.innerHTML = "click to hide";
    } else {
        link.innerHTML = "click to edit";
    }
    
}

 
 function dynamicFieldToggleTextPrompt(linkId, onText, offText) {
    var link = document.getElementById(linkId);
    var text = link.innerHTML;
    if (text == offText) {
        link.innerHTML = onText;
    } else {
        link.innerHTML = offText;
    }
 }

 
function showHelpHint(url) {
    helpWindow = window.open("/webfiles/html/help/" + url, "helpWindow",
                        "width=488, height=500, scrollbars=yes, resizable=yes");
    helpWindow.focus();
}

function progressOn(progressMessage) {
    displayMessagePopupNoButton(progressMessage);
    var progressId = 'ajaxprogress';
    showDiv(progressId);
    var popup = document.getElementById(progressId);
//    alert("progresson:" + popup.innerHTML);
    if (popup && progressMessage) {
        popup.innerHTML = progressMessage;
    }
}

function progressOff() {
    messageOff('progressDialog');
}

/**
 * AJAX HANDLING
 */
var AJAX_CALL_TIMEOUT = 30000; //30 seconds
var ajaxXmlHttp = null;
var ajaxIsBusy = 0;
var ajaxTimeOutFunctionID = 0;
var ajaxModuleInProgress= '';
var pendingHitsUpdate = 0;
var retry_ajaxModule;
var retry_callbackFunctionName;
var retry_parameters;
var retry_checkBusy;
var cancelClicked = 0;
var times=0; 
 
function makeAjaxCall(ajaxModule, callbackFunctionName, parameters, checkBusy, progressMessage, useHistory) {
    if (ajaxModule=='GetHitCount' && ajaxIsBusy==1) {
        pendingHitsUpdate=0;
        return;
    }
	times++;
	if (ajaxModule=="GetRecordFromSearchResult") {
		if (times>=1) {
			times=0;
			checkBusy = false;
			useHistory=false;
		}
	} else {
		times = 0;
	}
    
    if (cancelClicked == 1) {
    	cancelClicked = 0;
        makeAjaxCall(ajaxModule, callbackFunctionName, parameters, checkBusy, progressMessage);
    }
    if (ajaxModuleInProgress=='GetHitCount') {
        pendingHitsUpdate=0;
        cancelAjaxCall();
        ajaxModuleInProgress='';
        ajaxIsBusy=0;
    }
    if (useHistory==true) {
        var state = "makeAjaxCall('" + ajaxModule + "', '" + callbackFunctionName + "', '" + parameters
         + "', " + checkBusy;
        if (progressMessage!=null) {
            state += ", '" + progressMessage + "', false);";
        } else {
            state += ", null, false);";
        }
        // alert("new history state = " + state); //for debug
        try {
            YAHOO.util.History.navigate("ajax", state);
        } catch (e) {
            alert(e);
        }
        return;
    }
    if (checkBusy==false || ajaxIsBusy==0) {
        retry_ajaxModule = ajaxModule;
        retry_callbackFunctionName = callbackFunctionName;
        retry_parameters = parameters;
        retry_checkBusy = checkBusy;
        ajaxIsBusy = 1;
        ajaxModuleInProgress = ajaxModule;
		if (progressMessage==null) {
			progressMessage = "Loading...";
		}
		if (ajaxModule!="EmtreeTool" && callbackFunctionName != "ajaxExecuteAbstractDataCallback") {
			progressOn(progressMessage);
		}
        hideDiv('generic_message');
        var random = Math.floor(Math.random() * 999999); //use a random number in the url to avoid internet explorer caching problems
        var uAjax = "module=" + escape(ajaxModule) + "&callback=" + escape(callbackFunctionName)
                + "&rand=" + random;
        if (parameters) {
            uAjax += "&" + parameters;
        }
        var url = "/ajax";
        if (window.XMLHttpRequest) {
            ajaxXmlHttp = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            ajaxXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            ajaxIsBusy = 0;
            progressOff();
            ajaxModuleInProgress='';
            showErrorPopup("Sorry, your browser does not support AJAX technology.");
            return;
        }
        if(ajaxXmlHttp) {
            if (useHistory==true) {
                var state = "makeAjaxCall('" + ajaxModule + "', '" + callbackFunctionName + "', '" + parameters
                 + "', " + checkBusy;
                if (progressMessage!=null) {
                    state += ", '" + progressMessage + "', " + useHistory + ");";
                } else {
                    state += ", null, " + useHistory + ");";
                }
                // alert("new history state = " + state); //for debug
                try {
                    YAHOO.util.History.navigate("ajax", state);
                } catch (e) {
                    alert(e);
                }
            }
            ajaxTimeOutFunctionID = window.setTimeout('processAjaxTimeout()', AJAX_CALL_TIMEOUT);
            ajaxXmlHttp.onreadystatechange = processAjaxCallback;
            ajaxXmlHttp.open("POST", url, true);
            ajaxXmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
            ajaxXmlHttp.send(uAjax);
            //document.location.hash = uAjax; //for back button support in the future
        }
    } else {
        //display error message
        var questionresult = window.confirm("The browser is already loading some dynamic data from the web server. Click OK to perform the new action, or Cancel to keep waiting.");
        if (questionresult) {
        	cancelAjaxCall();
            ajaxIsBusy = 0;
            cancelClicked =  0;
    		if (ajaxModule!="EmtreeTool") {
    			progressOff();
    		}
            makeAjaxCall(ajaxModule, callbackFunctionName, parameters, checkBusy, progressMessage);
            return;
        } else {
            cancelClicked =  1;
            return;
        }
    }
}
 
function processAjaxCallback() {
    if (ajaxXmlHttp.readyState==4) {
        ajaxIsBusy = 0;
        ajaxModuleInProgress='';
        progressOff();
        cancelAjaxCall();
        if (ajaxXmlHttp.status==200) {
            var result = ajaxXmlHttp.responseText ; //this can either be a function or an object! when it is a function it is called directly
            var resultObj = eval(result);
            if (resultObj) {
            if(resultObj.error) {
            	if (resultObj.error=="") {
            		showErrorPopup("Error:\n" + result);
            	} else {
            		showErrorPopup("Error:\n" + resultObj.error);
            	}
            } else {
                eval(resultObj.callback)(resultObj);
            }
        } else {
                // network problem, retry 
                makeAjaxCall(retry_ajaxModule,retry_callbackFunctionName,retry_parameters,retry_checkBusy);
            }
        } else {
            if (ajaxXmlHttp.status!=0) {
                //showErrorPopup("There was a problem retrieving information from the web server:\n" + ajaxXmlHttp.status + " " + ajaxXmlHttp.statusText);
                // network problem, retry 
                makeAjaxCall(retry_ajaxModule,retry_callbackFunctionName,retry_parameters,retry_checkBusy);
            }
        }
    }
}

function processAjaxTimeout() {
    if (ajaxIsBusy!=0) {
        cancelAjaxCall();
        showErrorPopup("Call to the webserver timed out.");
    }
}

function cancelAjaxCall() {
    if (ajaxXmlHttp!=null) {
        if (ajaxXmlHttp.readyState==0 || ajaxXmlHttp.readyState==4) {
            //do nothing, just reset the timer
        } else {
            ajaxXmlHttp.abort();
        }
    }
    window.clearTimeout(ajaxTimeOutFunctionID); //always clear the timeout
    ajaxIsBusy = 0;
    progressOff();
    ajaxModuleInProgress='';
}

/** AJAX history begin */

function ajaxStateChangeHandler(state) {
    //Update the UI according to the state parameter
    var result = eval(state); //execute the state as Javascript
    //alert(result); //for debug
}

function initAjaxHistory() {
    var ajaxHistoryBookmarkedState = YAHOO.util.History.getBookmarkedState("ajax");
    var ajaxHistoryInitialState = ajaxHistoryBookmarkedState || "resultsBrowse(0,25);";
    YAHOO.util.History.register("ajax", ajaxHistoryInitialState, ajaxStateChangeHandler);
    YAHOO.util.History.onReady(function () {
        var ajaxCurrentState = YAHOO.util.History.getCurrentState("ajax");
        ajaxStateChangeHandler(ajaxCurrentState);
    });
    try {
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");
    } catch (e) {
        alert(e); //for debug
    }
}

/** AJAX history end */

function getFormData(form) {
    var parameters = "";
    var elements = form.elements;
    for(i = 0;i<elements.length;i++) {
        var e = elements[i];
        if ((e.type=="checkbox" || e.type=="radio")) {
            //only selected and not disabled checkboxes
            if (e.checked && !e.disabled) {
                if (parameters.length>0) {
                    parameters += "&";
                }
                parameters += e.name + "=" + e.value;
            }
            continue;
        }
        if (e.value.length>0) {
            if (parameters.length>0) {
                parameters += "&";
            }
            parameters += e.name + "=" + escape(e.value);
        }
    }
    return parameters;
}

function submitAjaxForm(ajaxModule, callbackFunctionName, form) {
    var parameters = getFormData(form);
    makeAjaxCall(ajaxModule, callbackFunctionName, parameters, null, null, true);
}

 function testMyAjaxCallBack(jsonResult) {
  var moduleName = jsonResult.moduleName;
  var requestNr = jsonResult.requestNr;
  alert("Retrieved AJAX result:\nmoduleName=" + moduleName + "\nrequestNr=" + requestNr);
 }
 
 function testAjax() {
  makeAjaxCall('test','testMyAjaxCallBack',null);
 }
 
function servletCallbackTest(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    alert("Received AJAX content for servlet " + moduleName + ":\n" + content);
}

/* trim function for strings */
function trim(str) { 
    var ret = str.replace(/^[\s\n\t]+/,'');
    ret = ret.replace(/[\s\n\t]+$/,'');
    return ret;
} 

/* clear all checkboxes with a particular name 
 * @param form Javascript form object
 * @param name Name of checkboxes
 */
function clearCheckBoxes(form, name) {
    var boxes = eval(form.name + "." + name);
    for(i=0;i<boxes.length;i++) {
        var box = boxes[i];
        box.checked = false;
    }
}

/*
 * Gets the value of the selected item in a radio button group
 * @param radio The radio button group
 */
function getRadioSelectedValue(radio) {
    var length = radio.length;
    for (i=0;i<length;i++) {
        var item = radio[i];
        if (item.checked) {
            return item.value;
        }
    }
    return null;
}

/**
 * Build a JSON string of a form object with the values of all elements in it.
 * This function is to avoid browser differences. 
 */
function jsonForm(myform) {
    var postForm = new Object();
    postForm.name = myform.name;
    var nrItems = myform.length;
    for (i=0;i<nrItems;i++) {
        var element = myform[i];
        var item = new Object();
        item.name = element.name;
        item.value = element.value;
        if (element.type=="checkbox" || element.type=="radio") {
            item.checked = element.checked;
            item.type = element.type;
        }
        postForm[i] = item;
    }
    var jsonResult = JSON.stringify(postForm);
    return jsonResult;
}

/**
 * Set form values back from earlier stored form values.
 * @return the form object updated or false.
 */
function fillFormWithJSON(jsonStr) {
    if (jsonStr!=null && jsonStr.length>0) {
        var jsonForm = JSON.parse(jsonStr);
        if (jsonForm==false) {
            showErrorPopup("Cannot parse stored form values. Leaving the form on it's default values.");
        }
        var myform = eval('document.' + jsonForm.name);
        for (var attribute in jsonForm) {
            if (attribute!=null && attribute.length>0) {
                var item = jsonForm[attribute];
                if (item.name=='has_more_limits') {
                    if (item.value=="true") {
                        openMoreLimits(myform);
                    }
                }
                var element = myform[item.name];
                if (element) {
                    if (item.type) {
                        //checkbox or radio button
                        var length = element.length;
                        if (length) {
                            for(var i=0;i<length;i++) {
                                var node = element[i];
                                if (node.value==item.value) {
                                    node.checked = item.checked;
                                    break;
                                }
                            }
                        } else {
                            element.checked = item.checked;
                        }
                    } else {
                        //'normal' form element
                        element.value = item.value;
                    }
                }
            }
        }
        return myform;
    } else {
        return false;
    }
}

/**
 * Function to check if a string is a valid email address.
 */ 
function emailCheck(emailStr, fieldName) {
    /* The following pattern is used to check if the entered e-mail address
       fits the user@domain format.  It also is used to separate the username
       from the domain. */
    var emailPat=/^(.+)@(.+)$/;
    /* The following string represents the pattern for matching all special
       characters.  We don't want to allow special characters in the address. 
       These characters include ( ) < > @ , ; : \ " . [ ]    */
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    /* The following string represents the range of characters allowed in a 
       username or domainname.  It really states which chars aren't allowed. */
    var validChars="\[^\\s" + specialChars + "\]";
    /* The following pattern applies if the "user" is a quoted string (in
       which case, there are no rules about which characters are allowed
       and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
       is a legal e-mail address. */
    var quotedUser="(\"[^\"]*\")";
    /* The following pattern applies for domains that are IP addresses,
       rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
       e-mail address. NOTE: The square brackets are required. */
    var ipDomainPat="/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/";
    /* The following string represents an atom (basically a series of
       non-special characters.) */
    var atom=validChars + '+';
    /* The following string represents one word in the typical username.
       For example, in john.doe@somewhere.com, john and doe are words.
       Basically, a word is either an atom or quoted string. */
    var word="(" + atom + "|" + quotedUser + ")";
    // The following pattern describes the structure of the user
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    /* The following pattern describes the structure of a normal symbolic
       domain, as opposed to ipDomainPat, shown above. */
    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
    /* Finally, let's start trying to figure out if the supplied address is
       valid. */
    /* Begin with the coarse pattern to simply break up user@domain into
       different pieces that are easy to analyze. */
    
    var emailStrArr = emailStr.split(",");
    var iSizeEmailStrArr = emailStrArr.length;
    if (iSizeEmailStrArr <= 1) {
	    emailStrArr = emailStr.split(";");
	    iSizeEmailStrArr = emailStrArr.length;
    }
    for(iTel = 0; iTel < iSizeEmailStrArr; iTel++){
    	emailStr = emailStrArr[iTel]; 
	    var matchArray=emailStr.match(emailPat);
	    if (matchArray==null) {
	      /* Too many/few @'s or something; basically, this address doesn't
	         even fit the general mould of a valid e-mail address. */
	        showErrorPopup("Email address in field " + fieldName + " seems incorrect (check @ and .'s)");
	        return false;
	    }
	    var user=matchArray[1];
	    var domain=matchArray[2];
	    // See if "user" is valid 
	    if (user.match(userPat)==null) {
	        // user is not valid
	        showErrorPopup("The username of the email address in field " + fieldName + " doesn't seem to be valid.");
	        return false;
	    }
	    /* if the e-mail address is at an IP address (as opposed to a symbolic
	       host name) make sure the IP address is valid. */
	    var IPArray=domain.match(ipDomainPat);
	    if (IPArray!=null) {
	        // this is an IP address
	        for (var i=1;i<=4;i++) {
	            if (IPArray[i]>255) {
	                showErrorPopup("Destination IP address in field " + fieldName + " is invalid!");
	                return false;
	            }
	        }
	        return true;
	    }
	    // Domain is symbolic name
	    var domainArray=domain.match(domainPat);
	    if (domainArray==null) {
	        showErrorPopup("The domain name in field " + fieldName + " doesn't seem to be valid.");
	        return false;
	    }
	    /* domain name seems valid, but now make sure that it ends in a
	       three-letter word (like com, edu, gov) or a two-letter word,
	       representing country (uk, nl), and that there's a hostname preceding 
	       the domain or country. */
	    /* Now we need to break up the domain to get a count of how many atoms
	       it consists of. */
	    var atomPat=new RegExp(atom,"g");
	    var domArr=domain.match(atomPat);
	    var len=domArr.length;
	    if (domArr[domArr.length-1].length<2 || 
	        domArr[domArr.length-1].length>3) {
	       // the address must end in a two letter or three letter word.
	       showErrorPopup("The address in field " + fieldName + " must end in a three-letter domain, or two letter country.");
	       return false;
	    }
	    // Make sure there's a host name preceding the domain.
	    if (len<2) {
	       var errStr="The address in field " + fieldName + " is missing a hostname!";
	       showErrorPopup(errStr);
	       return false;
	    }
    }
    // If we've gotten this far, everything's valid!
    return true;
}

/**
 * Function to check if a date is a valid one
 */
function dateValid(aDate) {
    var daysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    var day = parseInt(aDate.substring(0,2),10); if (isNaN(day)) day=0;
    var month = parseInt(aDate.substring(3,5),10); if (isNaN(month)) month=0;
    var year = parseInt(aDate.substring(6,10),10); if (isNaN(year)) year=0;
    var _isLeap = (year % 4 == 0 && (year % 1000 == 0 || year % 100 != 0));
    if (_isLeap) daysInMonth[1]=29;
    var dateOk = true;
    if ((day!=0) && (month!=0) && (year!=0)) {
        if (day>daysInMonth[month-1]) dateOk=false;
        if (day<1) dateOk=false;
        if ((month<1) || (month>12)) dateOk=false;
        if ((year<1950) || (year>2050)) dateOk=false;
    }  else dateOk=false;
    return dateOk;
}

/**
 * Function to remove quotes from an input field
 */
function quoteRemove(e) {
    var keynum;
    var keychar;
    if(window.event) {// IE
        keynum = e.keyCode;
    } else if(e.which) { // Netscape/Firefox/Opera
        keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    //alert("key pressed= " + keychar);
    if (keychar=="\"") {
        return false;
    }
    return true;
}

/*
 * Find the X-position of an element on a page
 */
function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

/*
 * Find the Y-position of an element on a page
 */
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}

/* printing communication this variable is filled by the normal user window and read by 
 * the print preview window
 */
var printContent = null;

/**
 * Functions for Folder selection handling
 */

var tree;
 
function folderselectorReload() {
    makeAjaxCall("GetUserFolders", "folderselectorReloadCallback", "", false, 'Loading your folders...');
}

function folderselectorReloadCallback(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    var jsonFolders = JSON.parse(content);
    var div = document.getElementById("folderselector");
    var searchfolders = jsonFolders.searchfolders;
    if (searchfolders) {
        //there are folders
        tree = new YAHOO.widget.TreeView("folderselector");
        var root = tree.getRoot();
        folderselectorCreateNodeFromSearchfolder(searchfolders, root);
        tree.draw();
    }
    folderselectionResetSelection();
}

function folderselectorCreateNodeFromSearchfolder(searchfolder, parentNode) {
    var newNode;
    if (searchfolder.name) {
        //variable is a folder
        searchfolder.label = searchfolder.name;
        searchfolder.href = "javascript:selectFolder(tree.getNodeByProperty('id','" + searchfolder.id + "').data);";
        newNode = new YAHOO.widget.TextNode(searchfolder, parentNode, false);
    } else {
        newNode = parentNode;
    }
    if (searchfolder.searchfolder) {
        var sub = searchfolder.searchfolder;
        if (sub.length) {
            //more then 1
            for(var i=0;i<sub.length;i++) {
                var subsearchfolder = sub[i];
                folderselectorCreateNodeFromSearchfolder(subsearchfolder, newNode);
            }
        } else {
            //just 1 folder
            folderselectorCreateNodeFromSearchfolder(sub, newNode);
        }
    }
}

function selectFolder(searchFolder) {
    var spanName = document.getElementById("folderselector_selected_name");
    var spanId = document.getElementById("folderselector_selected_id");
    spanName.innerHTML = "Selected folder: " + searchFolder.name;
    spanId.innerHTML = searchFolder.id;
    var divSavedSearchesList = document.getElementById("div_saved_searches_of_folder");
    if (divSavedSearchesList) {
        var parameter = "folder_id=" + searchFolder.id;
        makeAjaxCall("GetSaveSearches", "getSaveSearchesCallback", parameter, true, 'Selecting folder');
    }
}

function getSaveSearchesCallback(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    var divSavedSearches = document.getElementById('div_saved_searches_of_folder');
    divSavedSearches.innerHTML = content;
    var divDest = document.getElementById('div_saved_search_details');
    divDest.innerHTML = "";
}

function folderselectionResetSelection() {
    var spanName = document.getElementById("folderselector_selected_name");
    var spanId = document.getElementById("folderselector_selected_id");
    spanName.innerHTML = "";
    spanId.innerHTML = "";
    var divSavedSearchesList = document.getElementById("div_saved_searches_of_folder");
    if (divSavedSearchesList) {
        divSavedSearchesList.innerHTML = "<b>No folder selected</b>";
        var divDest = document.getElementById('div_saved_search_details');
        divDest.innerHTML = "";
    }
}

function folderselectionSubmitAdd() {
    hideDiv('generic_message');
    var newName = trim(document.getElementById("f_add_newName").value);
    if (newName==null || newName=="") {
        showErrorPopup("Please type in a new folder name.");
        return false;
    }
    var parameter = "newname=" + newName;
    var spanId = document.getElementById("folderselector_selected_id").innerHTML;
    if (spanId < 0) {
        showErrorPopup("Cannot add subfolders to a shared folder.");
        return false;
    }
    if (spanId.length>0) {
        parameter += "&parentid=" + spanId;
    }
    switchDiv('div_f_add');
    makeAjaxCall("AddUserFolder", "folderselectorActionCallback", parameter, true, 'Creating folder...');
}

function folderselectionSubmitDelete() {
    hideDiv('generic_message');
    var spanId = document.getElementById("folderselector_selected_id").innerHTML;
    if (spanId.length<1) {
        showErrorPopup("Please select a folder to delete.");
        return;
    }
    if (spanId < 0) {
        showErrorPopup("Cannot delete a shared folder.");
        return;
    }
    var node = tree.getNodeByProperty('id',spanId);
    if (node.hasChildren(false)) {
        showErrorPopup("Selected folder has sub folder(s). Please delete them first.");
        return;
    }
    var confirmed = window.confirm("Are you sure you want to delete the selected folder?");
    if (confirmed) {
        var parameter = "folderid=" + spanId;
        makeAjaxCall("DeleteUserFolder", "folderselectorActionCallback", parameter, true, 'Deleting folder...');
    }
}

function folderselectionSubmitRename() {
    hideDiv('generic_message');
    var newName = trim(document.getElementById("f_rename_newName").value);
    if (newName==null || newName=="") {
        showErrorPopup("Please type in a new folder name.");
        return false;
    }
    var parameter = "newname=" + newName;
    var spanId = document.getElementById("folderselector_selected_id").innerHTML;
    if (spanId < 0) {
        showErrorPopup("Cannot rename a shared folder.");
        return false;
    }
    if (spanId.length>0) {
        parameter += "&folderid=" + spanId;
    } else {
        showErrorPopup("Please select a folder to rename.");
        return false;
    }
    switchDiv('div_f_rename');
    makeAjaxCall("RenameUserFolder", "folderselectorActionCallback", parameter, true, 'Renaming folder...');
}

function folderselectorActionCallback(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    var divGenericMessage = document.getElementById('generic_message');
    folderselectorReload();
    scroll(0,0);
    divGenericMessage.innerHTML = content;
    showDiv('generic_message');
}

/**
 * Search tips handling
 */
var lastTipsContent = "";
var tipsAjaxXmlHttp = null;

function getTipsHTMLcontents(htmlName) {
    if (window.XMLHttpRequest) {
        tipsAjaxXmlHttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        tipsAjaxXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        showErrorPopup("Sorry, your browser does not support AJAX technology to display tips.");
        return;
    }
    var url = "/webfiles/html/help/tips/" + htmlName;
    if(tipsAjaxXmlHttp) {
        tipsAjaxXmlHttp.onreadystatechange = updateTipsOnScreen;
        tipsAjaxXmlHttp.open("GET", url, true);
        tipsAjaxXmlHttp.send(null);
    }
}

function updateTipsOnScreen() {
    if (tipsAjaxXmlHttp.readyState==4) {
        if (tipsAjaxXmlHttp.status==200) {
            var result = tipsAjaxXmlHttp.responseText;
            var divTips = document.getElementById('div_tips');
            lastTipsContent = divTips.innerHTML;
            divTips.innerHTML = result;
        } else {
            showErrorPopup("There was a problem retreiving AJAX data:\n" + ajaxXmlHttp.statusText);
        }
    }
}

function getPreviousTips() {
    var divTips = document.getElementById('div_tips');
    divTips.innerHTML = lastTipsContent;
    lastTipsContent = "";
}

/**
 * Open the Guided Tour window
 */
function openGuidedTour(url) {
    var width = 900;
    var height = 600;
    var left = (screen.availWidth - width) / 2;
    var top = (screen.availHeight - height) / 2;
    var props = 'height=' + height + ',width=' + width + ',left=' + left + ',top=' + top;
    window.open(url,'guidedtour',props);
}

/** Spell check begin */
function opensuggestions(termid, termname, mappings, extensive, druglinks, diseaselinks, drugadm) {
    parameters = "termid=" + termid + "&term=" + termname + "&mappings=" + mappings + "&extensive=" + extensive + "&druglinks=" + druglinks + "&diseaselinks=" + diseaselinks + "&drugadm=" + drugadm;
    makeAjaxCall("GetSpellingSuggestions", "suggestionBoxCallback", parameters, true, 'Loading spell check suggestions...');
}
  
function suggestionBoxCallback(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    var suggestionDiv = document.getElementById("suggestionsdiv");
    suggestionDiv.innerHTML = content;
    showDiv("suggestionsdiv");
}

var globaltermid;
  
function closeSuggestionBox() {
    var suggestionDiv = document.getElementById("suggestionsdiv");
    suggestionDiv.innerHTML = "";
    hideDiv("suggestionsdiv");
}

function tooltipSuggestions() {
    var dropdown = document.getElementById("suggestedTerms");
    var selectedText = dropdown.options[dropdown.selectedIndex].value;
    dropdown.title = selectedText;
}
  
function doNotReplaceTerm(termid) {
    var term = document.getElementById(termid).childNodes[0].innerHTML;
    term = term.replace(/<.*?>/g, "");
    document.getElementById(termid).innerHTML = "<b>" + term + "</b>"; 
    document.getElementById("suggestionsdiv").innerHTML = "";
    hideDiv("suggestionsdiv");
    updatecount();
}
  
function replaceTerm(termid, mappings, extensive, druglinks, diseaselinks, drugadm, linkoperator, admoperator) {
     var index = document.getElementById("suggestedTerms").selectedIndex;
     var typed = document.getElementById("typedSuggestedTerm").value;
     var termname;
     if (typed.length > 0) {
       termname = typed;
     } else if (index != -1) {
       termname = document.getElementById("suggestedTerms").options[index].text;
     }
     if (termname) {
       globaltermid = termid;
       parameters = "term=" + replaceSpecialChars(termname) + "&mappings=" + mappings + "&extensive=" + extensive + "&druglinks=" + druglinks + "&diseaselinks=" + diseaselinks + "&drugadm=" + drugadm + "&linkop=" + linkoperator + "&admop=" + admoperator;
       makeAjaxCall("GetSpellingRenderTermWithMappings", "termUpdaterCallback", parameters);
     }
  }
  
function termUpdaterCallback(jsonResult) {
    var moduleName = jsonResult.moduleName;
    var content = jsonResult.content;
    document.getElementById(globaltermid).innerHTML = content;
    document.getElementById("suggestionsdiv").innerHTML="";
    hideDiv("suggestionsdiv");
    updatecount();
}

function updatecount() {
   var n = eval(document.getElementById("unmappedcount").innerHTML - 1);
   document.getElementById("unmappedcount").innerHTML = n;
   if (n==0) {
     document.getElementById("foundheader").innerHTML = "<span class='txt' style='color:#007700;'>All term(s) have been spell checked. Updating results...</span>";
     setTimeout("updateResults()", 2000);
   }
}

function replaceSpecialChars(term) {
    return term.replace(/'/g,"`").replace(/\[/g,"(").replace(/\]/g,")");
}
 
function updateResults() {
   var text = document.getElementById("unmappedemtreequery").innerHTML;
   text = text.replace(/<.*?>/g, "").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
   var form = document.getElementById("spelling_form");
   form.search_query.value = trim(text);
    var seconds = new Date().getTime();
    form.unique_id.value = seconds + "";
   form.submit();
}

function mypopup(aUrl) {
  mywindow = window.open (aUrl, "chartdisplay","location=0,status=0,scrollbars=0,width=900,height=700");
  mywindow.moveTo(0,0);
} 

function messageOn(divId) {
	var vpOffset = getScrollY();
	var vpSize = getWindowHeight();
	
	messageSwitch(divId, 'block');
	var positionDiv = document.getElementById('abxw').getElementsByTagName('div')[0];
	if (positionDiv != null) {
		var divSize = getObjectHeight(positionDiv);
		// if divSize not filled out (IE 6 before end of page loading)
		// or size of div too large, show at 10% from the top 
		if (divSize == 0 || divSize > vpSize/1.1) {
			positionDiv.style.top = (vpOffset + vpSize/10) + "px";
		} else {
		// Otherwise, show vertically centered
			positionDiv.style.top = (vpOffset + vpSize/2 - divSize/2) + "px";
		}		
	}
	return false;
}

function messageSwitch(divId, dispStyle) {
	try {
		var arrayPageSize = getPageSize();
		if (document.getElementById('overlay')) {
		    document.getElementById('overlay').style.height = arrayPageSize[1] + 'px';
		}
		document.getElementById(divId).style.display = dispStyle;
		if (document.getElementById('overlay')) {
		   if (dispStyle == 'block') {
				$('#overlay').addClass("overlayVisible");
				$('link[@media*=print][title]').each(function(i) {
					this.disabled = true;
					if (this.getAttribute('title') == 'printDialog') {
						this.disabled = false;
						this.setAttribute('rel', 'stylesheet');
					}
				});
				
				/* Handle keystrokes. */
				$(document).keyup(function (e) {
					var evt = e || window.event;
					switch (evt.keyCode) {
						case 27: if( $('.close') ) { messageOff(divId) };
								break; // hide on escape
						default: 
							return false
						;
					}
				});
				IE6DropDowns('hidden');
			}
		   else {
				$('#overlay').removeClass("overlayVisible");
				$('link[@media*=print][title]').each(function(i) {
					this.disabled = false;
					if (this.getAttribute('title') == 'printDialog') this.disabled = true;
				});
				
				$(document).unbind('keyup');
		       	IE6DropDowns('visible');
			}
		}
	} catch (e) {
		//Do nothing
	}
	return false;
}

/**
Hide select boxes for IE6.
Select dropdowns/boxes penetrate the grey overlay at any z-index.
When adding a new select dropdown/box, add the ID of that select to the list below
*/
function IE6DropDowns(mode) {
	if ($.browser.msie && /6.0/.test(navigator.userAgent) ) {
		var elements = ['search_dlink','search_dadm','search_startyear','search_endyear'];
		for (var i = 0; i < elements.length; i++) {
			var element = document.getElementById(elements[i]);
			if (element) {
				element.style.visibility = mode;
			}
		}
	}
}

/**
Determine the height of a page element
*/
function getObjectHeight(object) {
	return object.offsetHeight;
}

function messageOff(divId) {
	return messageSwitch(divId, 'none');
}

//
//getPageSize()
//
var getPageSize = function() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {  
	    xScroll = window.innerWidth + window.scrollMaxX;
	    yScroll = window.innerHeight + window.scrollMaxY;
	}
	else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
	    xScroll = document.body.scrollWidth;
	    yScroll = document.body.scrollHeight;
	}
	else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	    xScroll = document.body.offsetWidth;
	    yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
	if (self.innerHeight) { // all except Explorer
	    if (document.documentElement.clientWidth){
	        windowWidth = document.documentElement.clientWidth; 
	    }
	    else {
	        windowWidth = self.innerWidth;
	    }
	    windowHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	    windowWidth = document.documentElement.clientWidth;
	    windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body) { // other Explorers
	    windowWidth = document.body.clientWidth;
	    windowHeight = document.body.clientHeight;
	}   
	
	// for small pages with total height less then height of the viewport
	if (yScroll < windowHeight){
	    pageHeight = windowHeight;
	}
	else { 
	    pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if (xScroll < windowWidth){ 
	    pageWidth = xScroll;        
	}
	else {
	    pageWidth = windowWidth;
	}
	
	return [pageWidth,pageHeight];
}

/**
Determine the amount of pixels scrolled down
*/
function getScrollY() {
	var scrOfY = 0;
	if (typeof(window.pageYOffset) == 'number') {
		//Netscape compliant
		scrOfY = window.pageYOffset;
	} else if (document.body && document.body.scrollTop) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
	} else if (document.documentElement && document.documentElement.scrollTop) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
	}
	return scrOfY;
}

/**
Determine the height of the current window
*/
function getWindowHeight() {
	var myHeight = 0;
	if (typeof(window.innerHeight) == 'number') {
		//Non-IE
		myHeight = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if (document.body && document.body.clientHeight) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}


/**  Show a message in a popup div
*/
function displayMessagePopup(title, message, buttonTitle) {
	var boxHtml = '<!-- Dialog -->'
		+ '<div class="overlay" id="overlay"><!--  overlay --></div>'
		+ '<div id="abxw">'
		+ '	<!-- Dialog processing search -->'
		+ '	<div id="progressDialog" class="dialog info">'
		+ '		<div class="t"><div><img src="images/bg-dialog-top-r.gif" height="1px" border="0" /></div></div>'
		+ '		<div class="con clearfix">'
		+ '			<div class="innerCon clearfix">'
		+ '				<p class="login"><span>'+message+'</span></p>'
		+ '				<a onclick="messageOff(\'progressDialog\');" href="javascript:void(0);" class="frmBtn">'
		+ '					<span class="tlc"><span class="trc"><span class="blc"><span class="brc">'+buttonTitle+'</span></span></span></span>'
		+ '				</a>'
		+ '			</div>'
		+ '		</div>'
		+ '		<div class="b"><div><!--  --></div></div>'
		+ '	</div>'
		+ '	<!--// Dialog processing search -->'
		+ '</div>'
		+ '<!--// Dialog -->';
	document.getElementById('abxw').innerHTML = boxHtml;
	messageOn('progressDialog');
}

/**  Show a message in a popup div, without any button (used in login for instance)
*/
function displayMessagePopupNoButton(message) {
	var boxHtml = '<!-- Dialog -->'
		+ '<div class="overlay" id="overlay"><!--  overlay --></div>'
		+ '<div id="abxw">'
		+ '	<!-- Dialog processing search -->'
		+ '	<div id="progressDialog" class="dialog info">'
		+ '		<div class="t"><div><img src="images/bg-dialog-top-r.gif" height="1px" border="0" /></div></div>'
		+ '		<div class="con clearfix">'
		+ '			<div class="innerCon clearfix">'
		+ '				<p class="login"><span>'+message+'</span></p>'
		+ '			</div>'
		+ '		</div>'
		+ '		<div class="b"><div><!--  --></div></div>'
		+ '	</div>'
		+ '	<!--// Dialog processing search -->'
		+ '</div>'
		+ '<!--// Dialog -->';
	document.getElementById('abxw').innerHTML = boxHtml;
	messageOn('progressDialog');
}


function changeAbstractShowHideText(linkId) {
	var link = document.getElementById(linkId);
	var text = link.innerHTML;
	if (text=="Hide abstract&nbsp;") {
		link.innerHTML = "Show abstract&#160;";
	} else {
		link.innerHTML = "Hide abstract&#160;";
	}
}

function showHideFormats(optionObj) {
	var val = optionObj.options[optionObj.selectedIndex].value;
	if ("TEXT" == val) {
		showDiv("plaintextdiv");
		showDiv("optionsPTdiv");
	} else {
		hideDiv("plaintextdiv");
		hideDiv("optionsPTdiv");
	}
}
