



<!-- Begin pageContent -->












  
    //
// File: 
//          FormControl.js
// 
// Synopsis: 
//      A mish-mash of form control routines.
// 

function fnAddOption(oSelect, oText, oValue, nLocation){
    // Don't add an empty option
    if ((oText == null || oText.length == 0) && (oValue == null || oValue.length == 0)){
        return;
    }
    var newOpt = new Option(oText, oValue, false, true);
    var n = oSelect.options.length;

    if(typeof nLocation == 'number' && nLocation < n){
        for(i = n; i > nLocation ; i--){
            oSelect.options[i] = new Option(oSelect.options[i-1].text,oSelect.options[i-1].value,false,false);
            oSelect.options[i].selected = false; // for netscape 4 only
        }
        oSelect.options[nLocation] = newOpt;
    } else {
        oSelect.options[n] = newOpt;
        oSelect.options[n].selected = true;
    }
};

function fnGetSelectedIndex(oInput){
    var sType = null;
    if(typeof oInput.type != "undefined")
        sType = oInput.type;
    else if(oInput.length > 0)
        sType = oInput[0].type;

    if(typeof oInput != "undefined"){
        if(sType.substring(0,6) == "select" && typeof oInput.options != "undefined"){
            for(var i = 0; i < oInput.length; i++){
                if(oInput.options[i].selected == true)
                    return i;
            }
        }
        else if(sType == "radio") {
            // In case we were passed a radio button, we want to get the group.
            if(typeof oInput.length == "undefined")
                oInput = oInput.form.elements[oInput.name];
            for(var i = 0; i < oInput.length; i++){
                if(oInput[i].checked == true)
                    return i;
            }
        }
    }
};

function fnGetSelectedValue(oInput){
    var answer = "";
    var sType = null;
    if(typeof oInput.type != "undefined")
        sType = oInput.type;
    else if(oInput.length > 0)
        sType = oInput[0].type;

    if(typeof oInput != "undefined"){
        var n = -1;
        n = fnGetSelectedIndex(oInput);
        if(sType.substring(0,6) == "select" && typeof oInput.options != "undefined"){
            if(n >= 0 && n < oInput.options.length)
                answer = oInput.options[n].value;
        }
        else if(sType == "radio"){
            // In case we were passed a radio button, we want to
            // get the group.
            if(typeof oInput.length == "undefined")
                oInput = oInput.form.elements[oInput.name];
            if(n >= 0 && n < oInput.length)
                answer = oInput[n].value;
        }
        else{
          answer = oInput.value;
        }
    }

    return answer;
};

// set a value in a select box
function fnSetSelectedValue(oInput, value){
    var bSelectedFound = false;
    for(i = 0; i < oInput.options.length; i++){
      if(value != "" && value == oInput.options[i].value){
          oInput.options[i].selected = true;
          bSelectedFound = true;
      }
    }
};
 
function findOptionByValue(objSelect, strValue) {
    // Straight pass-through 
    return findOption(objSelect, strValue, 'value');
}; 

function findOptionByText(objSelect, strValue) {
    // Straight pass-through 
    return findOption(objSelect, strValue, 'text');
}; 

/*
Find an Option Item of a Select Object by its OPTION Value, 
or if OPTION does not have a value, its Display Text 
return mixed integer of OPTION index, or -1 if not found
*/
function findOption($objSelect, $strNeedle, $strSearch) {
    var $_found = -1;

    // If $objSelect is a nothing [''], convert to a NULL 
    if ( $objSelect == '' )
        $objSelect = null;

    // If $objSelect is a string, convert to Object Reference
    // Then see if Object Reference exists
    else if ( ( typeof ( $objSelect ) ) == 'string' )
        $objSelect = document.getElementById($objSelect);

    // If we have nothing to deal with, just bale...
    if (($objSelect) && ($strNeedle) && (($strSearch == 'text') || ($strSearch == 'value'))) { 
        for (var $i = 0; $i < $objSelect.options.length; $i++) {
            if ( $strSearch == 'value' )
                $objHayStack = $objSelect[$i].value;
            else if ($strSearch == 'text') 
                $objHayStack = $objSelect[$i].text;
            if ($objHayStack == $strNeedle) {
                $_found = parseInt ( $i ); // We found a match
                break;
            }
        }
    }
    // Send back what we have
    return $_found;
}; 

// for Moving option elements up and down within a select box
function doMove(formObject,listObj,direction)
{
    //listObj = document.EditGroupForm.addMembers;

    optSrc = new Option();
    count = 0;
    selectedArray = new Array();
    if (direction == "up"){
        for (var i=0; i < listObj.length; i++){
            if ((listObj[i].selected) && (i > 0)){
                selectedArray[count] = i-1;
                listObj[i].selected = true;
                optSrc.text = listObj[i-1].text;
                optSrc.value = listObj[i-1].value;
                listObj[i-1].text = listObj[i].text;
                listObj[i-1].value = listObj[i].value;
                listObj[i].text = optSrc.text;
                listObj[i].value = optSrc.value;
                count++;
            }
        }
    }
    else if (direction == "down"){
        for (var i=listObj.length-1; i >= 0; i--){
            if ((listObj[i].selected) && (i < listObj.length-1)){
                selectedArray[count] = i+1;
                optSrc.text = listObj[i+1].text;
                optSrc.value = listObj[i+1].value;
                listObj[i+1].text = listObj[i].text;
                listObj[i+1].value = listObj[i].value;
                listObj[i].text = optSrc.text;
                listObj[i].value = optSrc.value;
                count++;
            }
        }
    }

    for (var k=0; k < listObj.length; k++){
        listObj[k].selected = false;
    }
    for (var j=0; j < selectedArray.length; j++){
        var item = selectedArray[j];
        listObj[item].selected = true;
    }
};

function fnGetFormItem(oForm,sName,sValue){
    if((null!=oForm) && (null!=sName)){
        var o = oForm.elements[sName];
        if(sValue!=null){
            var x = null;
            if(typeof o.length != 'undefined'){
                x = o;
            }
            else if(typeof o.options != 'undefined' &&
                    typeof o.options.length != 'undefined'){
                x = o.options;
            }
            else return null;

            for(var i=0; i<x.length;i++){
                if(x[i].value==sValue) 
                    o = x[i];
            }
        }
        return o;
    }
    else return null;
};

// gets an array of items called, "sName1", "sName2", etc.
// and returns an array of references to those objects
function fnGetItemArray(oForm,sName){
    var i;
    var oItem;
    var arAnswer = new Array();

    for(i=1; i <= oForm.length; i++){
        oItem=oForm[sName+i];
        if(oItem)
            arAnswer = arAnswer.concat(oItem); //  get the item and add it to the array
    }
    return arAnswer;
};

function fnSetFormParameter(oForm,sName,sValue){
    oForm.elements[sName].value=sValue;
};

function fnSetProperty(oItemToChange,sProperty,oNewState){
    if((null!=oItemToChange) && (null!=sProperty) && (null!=oNewState)){
        oItemToChange[sProperty]=oNewState;    
    }
    return;
};


// Email Related Functions --------------------------------------------------------

function createMailTo(oLink, dTo, dSubject, dContent, dCC){
    var browserVersion = navigator.appVersion;
    if (browserVersion.indexOf("MSIE")!=-1){
        // if we are dealing with IE, then we need to assume that the mail
        // client is going to be outlook.  Outlook uses a semi-colon
        // instead of a comma to separate email addresses.
        dTo = dTo.replace(/,/g, ";")
        if (dCC!= "")
            dCC = dCC.replace(/,/g,";")
    }
    // construct the mailto
    var dHref = "mailto:" + dTo + "?";
    if (dCC != "")
        dHref += "cc=" + buildURL(dCC);
    if (dSubject != ""){
        if (dCC != "")
            dHref += "&";
        dHref += "subject=" + buildURL(dSubject);
    }
    if (dContent != "") {
        if (dCC != "" || dSubject != "")
            dHref += "&";
        dHref += "body=" + buildURL(dContent);
    }
    oLink.href = dHref;
};

// Validation Functions -----------------------------------------------------------

/*
This is the generic form validator. To use, set arfn to be an array of validation functions.
Each will be called, and the AND of all results will be returned.
ex:
 <form method="post" action="ModifyObject" onsubmit="return(fnValidateForm(this,[fnValidateAttrs, fnValidateAttrNames]));">
*/
function fnValidateForm(oForm,arfn)
{
    var error = "";

    if(typeof arfn != 'undefined' && arfn.length>0){
        for(var i = 0; i < arfn.length; i++){
            var thisErr = arfn[i](oForm);
            if(thisErr.length > 0)
                error = error + "\n\n- " + thisErr;
        }
    }
    if(error.length > 0){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.ERRORSFOUND", error);
        alert(error);
        return false;
    }
    else
        return true;
};

function fnValidateName(oForm){
    var error = "";
    if(oForm.name.value == ""){
        error = I18n.getTranslatedTemplateText("Globals.MISSINGNAME");
    }
    else if(trim(oForm.name.value) == ""){
        error = I18n.getTranslatedTemplateText("Globals.BLANKNAME");
    }
    oForm.name.value = trim(oForm.name.value);
    return error;
};

function fnValidateRatingKey(oForm){
    var error = "";
    if(oForm.ratingKey.value == ""){
        error = I18n.getTranslatedTemplateText("Globals.MISSINGRATINGKEY");
    }
    return error;
};

function fnValidateDocupload(oForm){
    var error = "";
    if(oForm.elements['DOC_UPLOAD'].value == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.MISSINGFILE");
    }
    return error;
};

function fnValidateURL(oForm){
    var error = "";
    if(oForm.url.value == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.MISSINGURL");
    }
    else if(trim(oForm.url.value) == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.BLANKURL");
    }
    oForm.url.value = trim(oForm.url.value);
    return error;
};

function fnValidateAttrNames(oForm){
    // this function will validate that none of the attrname fields are the same.
    // If they are, it returns false.
    var bAllOkay = true;
    var elList = oForm.elements;
    var selectedValue = "";
    var repeats = "";
    var attrNames = new Object;

    for (i=0; i < elList.length; i++){
        if ((elList[i].name.indexOf("attrname_of"))==0){
            if (attrNames[elList[i].value] == undefined)
                attrNames[elList[i].value]=elList[i].value;
            else{
                if (attrNames[elList[i].value] == "") {continue;}
                repeats += elList[i].value + "\n";
                bAllOkay = false;
            }
        }
    }
    if (!bAllOkay)
        return I18n.getTranslatedTemplateText("javascript_resource_FormControl.DUPLICATEATTRIBUTES", repeats);
    else
        return "";
};

function fnValidateAttrs(oForm){
    // this function will validate that all Date-time and date fields only
    // have numbers in their value.
    var i;
    var bAllOkay = true;
    var elList = oForm.elements;
    var selectedValue = "";
    var index;
    var sName;
    var value;

    for (i=0; i < elList.length; i++){
        if ((elList[i].name.indexOf("attrtype_of"))==0){
            selectedValue = fnGetSelectedValue(elList[i]);
            if (selectedValue == "Date" || selectedValue == "Date-time"){
                sName = elList[i].name.substring(11, elList[i].name.length);
                value = oForm.elements['attrvalue_of'+sName].value;
                if (value.length > 0){
                    if (isNaN(Number(value)))
                        bAllOkay = false;
                }
            }
        }
    }

    if (!bAllOkay)
        return I18n.getTranslatedTemplateText("javascript_resource_FormControl.INVALIDDATETIME");
    else 
        return "";
};

function fnValidatePolicyRoles(oForm){
    var bAllAssigned = true;
    var error = "";
    var option;
    var unAssignedList = "";
    var thisName;
    var stringEnd;
    var totalUnassigned=0;
    var max = 10; // we have to limit the total number of people on the alert
    for (i = 0; i< oForm.selRecipientList.length; i++){
        option = oForm.selRecipientList.options[i].value;
        thisName = oForm.selRecipientList.options[i].text;
        if ((option.indexOf('/') < 0) && (thisName != "") && totalUnassigned++ < max){
            bAllAssigned = false;
            stringEnd = thisName.indexOf(">>");
            thisName = thisName.substring(0,stringEnd-1);
            unAssignedList += "         - "+thisName;
            unAssignedList += "\n";
        }
    }
    if (totalUnassigned >= max)
        unAssignedList += "\nand " + parseInt(totalUnassigned-max) + " more.";
    if (!bAllAssigned)
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.HAVENOROLES", unAssignedList);
    return error;
};

// URL Related Functions ----------------------------------------------------------

/*
The JavaScript escape() function fixes ASCII characters that are not valid for use in URLs, 
but does not handle unicode characters well. 
The encodeURIComponent() function introduced in IE5.5, Netscape 6, and Mozilla will fix this issue,
However, since the function is unavailable in Netscape 4.x and IE5, 
encodeURIComponentNew() is basically reinventing the wheel and created to support old browsers
Source: http://www.worldtimzone.com/res/encode/
*/
function utf8(wide) {
    var c, s;
    var enc = "";
    var i = 0;
    while(i<wide.length) {
        c= wide.charCodeAt(i++);
        // handle UTF-16 surrogates
        if (c>=0xDC00 && c<0xE000) continue;
        if (c>=0xD800 && c<0xDC00) {
            if (i>=wide.length) continue;
            s= wide.charCodeAt(i++);
            if (s<0xDC00 || c>=0xDE00) continue;
            c= ((c-0xD800)<<10)+(s-0xDC00)+0x10000;
        }
        // output value
        if (c<0x80) enc += String.fromCharCode(c);
            else if (c<0x800) enc += String.fromCharCode(0xC0+(c>>6),0x80+(c&0x3F));
            else if (c<0x10000) enc += String.fromCharCode(0xE0+(c>>12),0x80+(c>>6&0x3F),0x80+(c&0x3F));
            else enc += String.fromCharCode(0xF0+(c>>18),0x80+(c>>12&0x3F),0x80+(c>>6&0x3F),0x80+(c&0x3F));
        }
    return enc;
};

var hexchars = "0123456789ABCDEF";

function toHex(n) {
    return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
};

var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

function encodeURIComponentNew(s) {
    var s = utf8(s);
    var c;
    var enc = "";
    for (var i= 0; i<s.length; i++) {
        if (okURIchars.indexOf(s.charAt(i))==-1)
            enc += "%"+toHex(s.charCodeAt(i));
        else
            enc += s.charAt(i);
    }
    return enc;
};

function buildURL(fld)
{
    if (fld == "") return "";
    var encodedField = "";
    var s = fld;
    if (typeof encodeURIComponent == "function"){
        // Use JavaScript built-in function
        // IE 5.5+ and Netscape 6+ and Mozilla
        encodedField = encodeURIComponent(s);
    }
    else {
        // Need to mimic the JavaScript version
        // Netscape 4 and IE 4 and IE 5.0
        encodedField = encodeURIComponentNew(s);
    }
    return encodedField;
};

// validate new record policy form.
function fnValidateNewRecordPolicy(oForm){            
    var error = "";
    if (oForm.name.value  == ""){
        error = I18n.getTranslatedTemplateText("Globals.MISSINGNAME");   
    }
    if (oForm.docSource.value  == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.RECPOL_MISSING_DOCSOURCE");
    }
    if (oForm.sysID.value == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.RECPOL_MISSING_SYSID");
    }        
    return error;
};
       
// validate the Proxy server page in the Admin UI
function fnValidateAdminProxy(oForm){
    var error = "";  
    var useProxy = valButton(oForm.useProxy);
    if (useProxy  == "rulesFile" && oForm.rulesFile.value == "" ){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.ADMIN_MISSING_RULES_FILE");
    }
    return error;
};

function valButton(btn) {
    var cnt = -1;
    for (var i=0; i < btn.length; i++) {
        if (btn[i].checked) {
            cnt = i; 
            i = btn.length;
        }
    }
    if (cnt > -1) return btn[cnt].value;
    else return null;
};

function fnValidateEmailRecipients(oForm){
    var error = "";
    if(oForm.emailRecipients.value == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.MISSING_EMAIL_RECIPIENTS");
    }
    return error;
};

//validate the name of the process report
function fnValidateProcessReportName(oForm){
    var error = "";
    var nameField = oForm.name;
    if(nameField.value == ""){
        error = I18n.getTranslatedTemplateText("Globals.MISSINGNAME");
    }
    else if(trim(nameField.value) == ""){
        error = I18n.getTranslatedTemplateText("Globals.BLANKNAME");
    }
    nameField.value = trim(nameField.value);
    return error;
}

//validate the process definition selected in process report form
function fnValidateProcessReport(oForm){
    var error = "";
    if(oForm.filter_loid_1.value == ""){
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.MISSING_PROCESS_DEFINITION");
    }
    return error;
};

// Ratings Functions --------------------------------------------------------------

/*
This function validates rating definition type selected by the user and
prompts the user if a rating defintiion type is not selected.
*/
function fnValidateRatingDefinition(oForm){
    var optionChecked = -1;
    var error = "";

    if(oForm.localizeRD){
        oForm.attrvalue_of_ITS_valuesAsKeys.value = oForm.localizeRD.checked;
    }

    if(oForm.ratingDefinitionType){
        for (i = oForm.ratingDefinitionType.length - 1; i > -1; i--) {
            if (oForm.ratingDefinitionType[i].checked) {
                optionChecked = i; 
                i = -1;
            }
        }
        if(optionChecked == -1) {
            error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.MISSING_RATING_DEFINITION");
        }
    }

    var tbl = document.getElementById('attrTable');
    var noOfRows = tbl.rows.length - 1;
    error = fnValidateRatingValues(noOfRows);
    return error;
};

/*
This function checks if any duplicate rating values have been entered. 
Values differing only in case are also indicated as duplicate values.
This function also checks if less than two rating values have been entered.
*/
function fnValidateRatingValues(lastRowId){
    var duplicateValuesFound = false;
    var error = "";
    var noOfValues = 0;

    for(var k = 1; k < lastRowId ; k++) {
          var obj1 = document.getElementById("ratingValue_" + k);
          if(obj1) {
               obj1.value = trim(obj1.value);
               if(obj1.value != "") {
                  noOfValues++;
               }
            }
    }

    for(var k = 1; k < lastRowId ; k++) {
        for(var j = k + 1; j < lastRowId;  j++) {
            var obj1 = document.getElementById("ratingValue_" + k);
            var obj2 = document.getElementById("ratingValue_" + j);
     
            if(obj1 && obj2) {
                if((trim(obj1.value.toLowerCase()) == trim(obj2.value.toLowerCase())) && trim(obj1.value) != ""){
                    duplicateValuesFound = true;
                    break;
                }
            }
        } 

        if(duplicateValuesFound) {
            break;
        }
    }    

    if(noOfValues < 2) {
       error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.INVALID_COUNT_RATING_VALUES");
    }
    else if(duplicateValuesFound) {
        error = I18n.getTranslatedTemplateText("javascript_resource_FormControl.DUPLICATE_RATING_VALUES");
    }

    return error;
};

//This function populates the rating values of the Rating definition
function populateRatingValues(oForm, default5StarsOnCoverPageTemplate, default5StarsInContainerTemplate, 
                                   default5StarsOnSearchResultTemplate){
    var len = 5;
    for(var i = 0; i < len; i++){
        var fieldName = 'ratingValue_' + (i + 1).toString();
        var tgtFieldName = 'values' +  i.toString();
        oForm[fieldName].value = oForm[tgtFieldName].value; 
    }

    var newRatingValuesLength = document.getElementById('attrTable').rows.length - 2; // There are two other rows that do not correspond to the rating values related rows
    for(var i = 0; i < newRatingValuesLength; i++){
        var fieldName = "ratingValue_" + eval(i + 1);
        var object = oForm[fieldName];
        if(object){
            object.disabled = true;
        }
    }

    oForm.ratingDefinitionType[0].checked = "checked";
    oForm.ratingDisplayTemplate.value = default5StarsOnCoverPageTemplate;
    oForm.containerViewTemplate.value = default5StarsInContainerTemplate;
    oForm.searchResultTemplate.value = default5StarsOnSearchResultTemplate;
    oForm.ratingDisplayTemplate.disabled = true;
    oForm.containerViewTemplate.disabled = true;
    oForm.searchResultTemplate.disabled = true;

    oForm.Apply.disabled = true;

    oForm.ratingDefinitionType[0].disabled = true;
    oForm.ratingDefinitionType[1].disabled = true;

    // Create hidden fields to store the values of the default templates. Since the disabled fields are
    // not submitted to the server

    // Hidden field for default rating display template
    var defaultRatingDisplayTemplate = document.createElement("input");
    defaultRatingDisplayTemplate.type = "hidden";
    defaultRatingDisplayTemplate.name = "defaultRatingDisplayTemplate";
    defaultRatingDisplayTemplate.id = "defaultRatingDisplayTemplate";
    defaultRatingDisplayTemplate.value = default5StarsOnCoverPageTemplate;
    oForm.appendChild(defaultRatingDisplayTemplate);

    // Hidden field for default container view template
    var defaultContainerViewTemplate = document.createElement("input");
    defaultContainerViewTemplate.type = "hidden";
    defaultContainerViewTemplate.name = "defaultContainerViewTemplate";
    defaultContainerViewTemplate.id = "defaultContainerViewTemplate";
    defaultContainerViewTemplate.value = default5StarsInContainerTemplate;
    oForm.appendChild(defaultContainerViewTemplate);

    // Hidden field for default search result template
    var defaultSearchResultTemplate = document.createElement("input");
    defaultSearchResultTemplate.type = "hidden";
    defaultSearchResultTemplate.name = "defaultSearchResultTemplate";
    defaultSearchResultTemplate.id = "defaultSearchResultTemplate";
    defaultSearchResultTemplate.value = default5StarsOnSearchResultTemplate;
    oForm.appendChild(defaultSearchResultTemplate);

    // Hidden field for default rating type
    var defaultRatingType = document.createElement("input");
    defaultRatingType.type = "hidden";
    defaultRatingType.name = "defaultRatingType";
    defaultRatingType.id = "defaultRatingType";
    defaultRatingType.value = "0";
    oForm.appendChild(defaultRatingType);
};

// Form Element Control and Display Functions -------------------------------------

/*
Enable or disable the form submit button.
*/
function fnSubmitButtonEnabled(bStatus) {
   var submitBtn = document.getElementById("submitButton");
   if (bStatus == true) {
       submitBtn.disabled = false;
       submitBtn.style.color="black";
   } else {
       submitBtn.disabled = true;
       submitBtn.style.color="gray";
   }
};

/*
Function for suppressing form submission by enter submit.
*/
function noEnter(e){
    var characterCode;
    if(e && e.which){
        characterCode = e.which;
    }
    else{
        characterCode = e.keyCode;
    }
    if(characterCode == 13){
        return false;
    }
    else{
        return true;
    }
};

/*
Get the caret position in a block of text.
 - textInput is the text input form element
 - position is the integer position of the care
*/
function getCaret(textInput) {
    var browserVersion = navigator.appVersion;
    if (browserVersion.indexOf("MSIE")!=-1){
        // IE
        var range = document.selection.createRange();
        range.moveStart("character", -textInput.value.length); 
        return range.text.length;
    } else {
        return (textInput.selectionStart);
    }
};

/*
Set the caret position in a block of text. Used when we replace the text in a text input field 
and need to preserve the caret position.
 - textInput is the text input form element
 - position is the integer position we want to place the caret
*/
function setCaret(textInput, position) {
    var browserVersion = navigator.appVersion;
    if (browserVersion.indexOf("MSIE")!=-1){
        // IE
        var range = textInput.createTextRange();
        range.collapse(true);
        range.moveStart("character", position);
        range.moveEnd("character", 0);
        range.select();
    } else {
        textInput.setSelectionRange(position, position);
    }
};

// Non-AJAX Logical Name Validation Functions -------------------------------------

/*
Validate a logical name. There are two flavours of this function:
 - fnValidateLogicalNameMandatory: the logical name field cannot be blank
 - fnValidateLogicalNameOptional: the logical name field can be left empty
In general, logical names should be mandatory for custom objects, and optional
otherwise.
*/
function fnValidateLogicalNameMandatory(oForm) {
    return validateLogicalName(oForm, true);
}

function fnValidateLogicalNameOptional(oForm) {
    return validateLogicalName(oForm, false);
};

/*
This function validates logical name value.
Should not be invoked directly but only via fnValidateLogicalNameMandatory()
or fnValidateLogicalNameOptional().
*/
function validateLogicalName(oForm, bMandatory) {
    var logicalNameVal = validateLogicalName_getLogicalName(oForm);
    if (logicalNameVal != null) {
        if (logicalNameVal == "") {
            if (bMandatory) {
                return I18n.getTranslatedTemplateText("Globals.MISSINGLOGICALNAME");
            }
            else {
                return "";
            }
        }
        //if some logical name is entered, validate it
        return validateLogicalName_value(logicalNameVal);
    }
    // some error with the form
    return "";
};

/*
Some common client-side validations:
 - check for leading or trailing hyphens
 - check for special characters
Return error string
*/
function validateLogicalName_chars(logicalNameVal) {
    var error = "";
    //Ensure that the logical name does not begin or end with a hyphen
    if(logicalNameVal.charAt(0) == "-" || logicalNameVal.charAt(logicalNameVal.length - 1) == "-") {
        error = I18n.getTranslatedTemplateText("Globals.LOGICAL_NAME_LEADING_TRAILING_HYPHEN_NOT_ALLOWED");
    }
    //Ensure that the logical name includes only alphanumeric characters and hyphens
    else if(!logicalNameVal.match(/^\w+(\-+\w+)*$/)) {
        error = I18n.getTranslatedTemplateText("Globals.LOGICAL_NAME_SPLCHAR_NOT_ALLOWED");
    }
    return error;
};

/*
Simple keyword checking.
*/
function validateLogicalName_value(logicalNameVal) {
    var error = "";
    var keyWords = new Array("Administration","BulkDeleteRatingsAndReviews","ChangeOwner","ChangePolicy","ChangeProcess",
                             "ChangeRecordPolicy","ChangeRetentionPolicy","CloneStructure","CopyObjects","CreateNewObject",
                             "CreateRemoteLink","DeleteNotifications","DeleteObjects","DocUpload","Finalize","GenerateReport",
                             "GetApplication","GetAuditingPolicy","GetBackgroundTask","GetContainer","GetContents",
                             "GetDBMetrics","GetDocument","GetGroup","GetMessage","GetMyPage","GetNotification","GetPolicy",
                             "GetProcessDefinition","GetQuery","GetRatingDefinition","GetRecordPolicy","GetRetentionPolicy",
                             "GetSubscription", "GetTaggedObjectsBrowserCmd", "GetUser","GetUserNotifications",
                             "GetUserSubscriptions","IndexRepair","ManageCTDBundles", "ManageTagsBrowserCmd", 
                             "ModifyDiscussionRecipients","ModifyObject","ModifyProcessDefinition","MoveObject","PasteObjects",
                             "PerformSearch","PresentAddressBookUsers","Present","ProcessInstance","PutObjects","RemoveObjects",
                             "ResetActivityMetrics","RunScript","StreamAsHTML", "tag", "TellPeople","Unsubscribe",
                             "ValidateLogicalName","mypage","mycollectionbin","mylandmarks","mysubscriptions","mypublic",
                             "myprivate","mynotifications","myuser","policiescabinet","usersandgroupscabinet","ua.trigger"); 
    var startWords = new Array("application-","auditingpolicy-","backgroundtask-","bgtask-","cabinet-","comment-",
                             "discussion-","document-","folder-","group-","guard-","home-","message-","notification-","policy-",
                             "definition-","query-","ratingdefinition-","recordlink-","recordpolicy-","report-","retentionpolicy-",
                             "subscription-","url-","user-","webdocument-","workplace-","review-");
    // validate the characters in the logical name
    error = validateLogicalName_chars(logicalNameVal);
    // ensure that the logical name entered is not a keyword
    if (error == "") {
        for(var i = 0; i < keyWords.length; i++) {
            if(logicalNameVal == keyWords[i]) {
                return(I18n.getTranslatedTemplateText("Globals.LOGICAL_NAME_KEYWORD_NOT_ALLOWED", logicalNameVal));
            }
        }
        for(var i = 0; i < startWords.length; i++) {
            if(logicalNameVal.indexOf(startWords[i]) == 0) {
                return(I18n.getTranslatedTemplateText("Globals.LOGICAL_NAME_KEYWORD_NOT_ALLOWED", logicalNameVal));
            }
        }
    }
    return error;
};

function validateLogicalName_onKeyUp(event, oForm) {
    var characterCode;
    if(event && event.which){
        characterCode = event.which;
    }
    else{
        characterCode = event.keyCode;
    }
    // non-output caret direction keystroke, we ignore and return
    if ((characterCode >= 33) && (characterCode <= 40)){
        return;
    }
    // do ajax validation
    else{
        fnValidateLogicalName_validate(oForm);
    }
};

/*
Get the logical name and replace spaces with underscores.
*/
function validateLogicalName_getLogicalName(oForm) {
    var target = oForm.logicalName;
    var pos = getCaret(target);
    target.value = target.value.replace(/ /g, '_');
    var value = target.value;
    setCaret(target, pos);
    return value;
};


// AJAX Logical Name Validation Functions -----------------------------------------

var sLogicalNameCurrent = ""; // set this to be the object's existing logical name
var sLogicalNameErrorMessage = ""; // error message returned by the server

/*
Logical name validation with realtime checking against known keywords. We try
to do as much client-side validation as possible to limit the number of ajax
calls we need to make.
*/
function fnValidateLogicalName_validate(oForm) {
    var logicalNameVal = validateLogicalName_getLogicalName(oForm);
    // check for empty string or no changes
    if ((logicalNameVal == "") || (logicalNameVal == sLogicalNameCurrent)) {
        sLogicalNameErrorMessage = "";
        fnValidateLogicalName_update(null);
        return;
    }
    // do client-side validation
    sLogicalNameErrorMessage = validateLogicalName_value(logicalNameVal);
    if (sLogicalNameErrorMessage != "") {
            fnValidateLogicalName_update("false");
            return;
    }
    // do ajax validation
    var url = "/gm/ValidateLogicalName?logicalName=" + encodeURIComponent(logicalNameVal);
    var ajax = new AJAXInteraction(url, fnValidateLogicalName_callback);
    if (ajax != null) {
        ajax.doGet(); 
    }
};

/*
Logical name validation callback parses the response, sets the error message, 
and calls the image and button update function.
*/
function fnValidateLogicalName_callback(responseXML) {
    var oResponse = responseXML.getElementsByTagName("response")[0];
    var sValid = oResponse.getElementsByTagName("valid")[0].firstChild.nodeValue;
    // set the error message
    if (sValid == "false") {
        var sErrorCode = oResponse.getElementsByTagName("message")[0].firstChild.nodeValue;
        sLogicalNameErrorMessage = I18n.getTranslatedTemplateText(sErrorCode, document.getElementById("logicalName").value);
    } else {
        sLogicalNameErrorMessage = "";
    }
    // update the button and image
    fnValidateLogicalName_update(sValid);
};

/*
Set the indicator for logical name validity based on the paramater:
status - null: display nothing, enable button
         "true":  display green tick, enable button
         "false": display red tick, disable button 
*/
function fnValidateLogicalName_update(status) {
    var iconTrue = document.getElementById("logicalName_true");
    var iconFalse = document.getElementById("logicalName_false");
    if (status == null) {
        iconTrue.style.display = "none";
        iconFalse.style.display = "none";
        fnSubmitButtonEnabled(true);
    }
    else if (status == "true") {
        iconTrue.style.display = "block";
        iconFalse.style.display = "none";
        fnSubmitButtonEnabled(true);
    } 
    else if (status == "false") {
        iconTrue.style.display = "none";
        iconFalse.style.display = "block";
        fnSubmitButtonEnabled(false);
    }
};

/*
Proxy for AJAX returned error messages to plug into existing validation script.
Can be used as normal validation function, e.g.
  return fnValidateCustom(formName, [fnValidateLogicalName_getErrorMessage])
*/
function fnValidateLogicalName_getErrorMessage(oForm) {
    return sLogicalNameErrorMessage;
};

// AJAX Logical Name Validate and Submit Form Functions ---------------------------

var oFormObj = null;
var fnValidationFunction = null;
var arfnArray = null;

/*
We don't actually submit the form, we do an AJAX validation of the logical name first
and do the submit logic in the callback function.
*/
function fnValidateLogicalNameAndSubmit(oForm, fnDefaultValidation) {
    return fnValidateLogicalNameAndSubmit(oForm, fnDefaultValidation, []);
};
function fnValidateLogicalNameAndSubmit(oForm, fnDefaultValidation, arfn) {
    // save parameters for callback function to use
    oFormObj = oForm;
    fnValidationFunction = fnDefaultValidation;
    arfnArray = arfn;
    var value = validateLogicalName_getLogicalName(oForm);
    if ((value == "") || (value == sLogicalNameCurrent)) {
        // logical name unchanged or empty, skip AJAX, use default validation
        return fnDefaultValidation(oForm, arfn);
    } else {
        // disable submit button first so user does not submit again due to AJAX latency
        fnSubmitButtonEnabled(false);
        // do client-side validation
        sLogicalNameErrorMessage = validateLogicalName_value(value);
        if (sLogicalNameErrorMessage != "") {
            fnValidateLogicalName_update("false");
            // skip to devault validation
            return fnDefaultValidation(oForm, arfn);
        }
        // do final validation of logical name
        var url = "/gm/ValidateLogicalName?logicalName=" + encodeURIComponent(value);
        var ajax = new AJAXInteraction(url, fnValidateLogicalNameAndSubmit_callback);
        if (ajax != null) {
            ajax.doGet();
        } else {
            // Unlikely case AJAX not supported, we default to original validation and submission
            return fnDefaultValidation(oForm, arfn);
        }
    }
    return false;
};

/*
Callback for pre-submit AJAX validation, calls normal validation update and then does usual
validation and form submission.
*/
function fnValidateLogicalNameAndSubmit_callback(responseXML) {
    fnValidateLogicalName_callback(responseXML);
    if (fnValidationFunction(oFormObj, arfnArray.concat([fnValidateLogicalName_getErrorMessage]))) {
        oFormObj.submit();
    }
};

// AJAX Functions -----------------------------------------------------------------

/*
AJAX handler. Parameters are:
url - the url of the request as a string
callback - the callback function pointer
*/
function AJAXInteraction(url, callback) {
    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            return null;
        }
    }
    
    function processRequest () {
        // readyState of 4 signifies request is complete
        if (req.readyState == 4) {
            // status of 200 signifies sucessful HTTP call
            if (req.status == 200) {
                if (callback) callback(req.responseXML);
            }
        }
    }

    this.doGet = function() {
        // make a HTTP GET request to the URL asynchronously
        req.open("GET", url, true);
        req.send(null);
    }
};

// RO Functions -------------------------------------------------------------------

//This function validates a Remote Object's External Object System Id
function fnValidateExtSysId(oForm){
    var error = "";
    if(oForm.extObjId.value == ""){
        error = I18n.getTranslatedTemplateText("Globals.MISSINGEXTOBJSYSID");
    }
    else if(trim(oForm.extObjId.value) == ""){
        error = I18n.getTranslatedTemplateText("Globals.BLANKNAME");
    }
    oForm.extObjId.value = trim(oForm.extObjId.value);
    return error;
};

// RP Functions -------------------------------------------------------------------

// Disable/enable Retention Policy form fields
function disableStartCBP(){
    document.RetentionPolicyForm.processList.disabled=true;
    document.RetentionPolicyForm.runAsUserString.disabled=false;
    document.RetentionPolicyForm.addressBookButton.disabled=false;
    document.RetentionPolicyForm.addressBookButton.focus();  
};

function disableRunAsUser(){
    document.RetentionPolicyForm.addressBookButton.disabled=true;
    document.RetentionPolicyForm.runAsUserString.value='';
    document.RetentionPolicyForm.runAsUserString.disabled=true;
    document.RetentionPolicyForm.processList.disabled=false;
    document.RetentionPolicyForm.processList.focus();
};

function disableCreationModificationDate(){
    document.RetentionPolicyForm.deadlineDaysCreate.disabled=true;
    document.RetentionPolicyForm.deadlineHoursCreate.disabled=true;
    document.RetentionPolicyForm.deadlineMinutesCreate.disabled=true;
    document.RetentionPolicyForm.deadlineDaysCreate.value='';
    document.RetentionPolicyForm.deadlineHoursCreate.value='';
    document.RetentionPolicyForm.deadlineMinutesCreate.value='';
    document.RetentionPolicyForm.deadlineDaysModify.disabled=true;
    document.RetentionPolicyForm.deadlineHoursModify.disabled=true;
    document.RetentionPolicyForm.deadlineMinutesModify.disabled=true;
    document.RetentionPolicyForm.deadlineDaysModify.value='';
    document.RetentionPolicyForm.deadlineHoursModify.value='';
    document.RetentionPolicyForm.deadlineMinutesModify.value='';
    document.RetentionPolicyForm.customDateAttribute.disabled=false;
    document.RetentionPolicyForm.customDateAttribute.focus();  
};

function disableModificationSetDate(){
    document.RetentionPolicyForm.deadlineDaysModify.disabled=true;
    document.RetentionPolicyForm.deadlineHoursModify.disabled=true;
    document.RetentionPolicyForm.deadlineMinutesModify.disabled=true;
    document.RetentionPolicyForm.deadlineDaysModify.value='';
    document.RetentionPolicyForm.deadlineHoursModify.value='';
    document.RetentionPolicyForm.deadlineMinutesModify.value='';
    document.RetentionPolicyForm.customDateAttribute.disabled=true;
    document.RetentionPolicyForm.customDateAttribute.value='';  
    document.RetentionPolicyForm.deadlineDaysCreate.disabled=false;
    document.RetentionPolicyForm.deadlineHoursCreate.disabled=false;
    document.RetentionPolicyForm.deadlineMinutesCreate.disabled=false;
    document.RetentionPolicyForm.deadlineDaysCreate.focus();
};

function disableSetCreationDate(){
    document.RetentionPolicyForm.customDateAttribute.disabled=true;
    document.RetentionPolicyForm.customDateAttribute.value=''; 
    document.RetentionPolicyForm.deadlineDaysCreate.disabled=true;
    document.RetentionPolicyForm.deadlineHoursCreate.disabled=true;
    document.RetentionPolicyForm.deadlineMinutesCreate.disabled=true;
    document.RetentionPolicyForm.deadlineDaysCreate.value='';
    document.RetentionPolicyForm.deadlineHoursCreate.value='';
    document.RetentionPolicyForm.deadlineMinutesCreate.value='';
    document.RetentionPolicyForm.deadlineDaysModify.disabled=false;
    document.RetentionPolicyForm.deadlineHoursModify.disabled=false;
    document.RetentionPolicyForm.deadlineMinutesModify.disabled=false;
    document.RetentionPolicyForm.deadlineDaysModify.focus();
};

// Tagging Functions --------------------------------------------------------------

//function that validates the syntax of non empty tags
function validateTagSyntax(tags, maxTagSize, maxInputTagsCount, existingTagsCount){
    var errorMsgAdded = false;
    var error = "";
    var currentTagsCount = 0;
    if(existingTagsCount)
    {
       currentTagsCount = existingTagsCount;
    }
    if(tags != null && tags != ""){
        var tags_array = tags.split(/\s+/);
        if(tags_array.length > currentTagsCount)
        {
          //check this only if user added greater number of tags
          if(tags_array.length - currentTagsCount > maxInputTagsCount){
            error = I18n.getTranslatedTemplateText("Globals.TAG_COUNT_LIMIT_EXCEEDED", maxInputTagsCount);
            return error;
          }
        }
        //if no of tags are valid..check for syntax
        var errorMsg = I18n.getTranslatedTemplateText("Globals.TAG_NAME_SPLCHAR_NOT_ALLOWED");
        for( i = 0; i < tags_array.length; i++){ 
            //Ensure that the tag names do not contain
            //the characters viz., '"&<>\%+?,
            if(tags_array[i].match(/[\.,\'\"&<>\\%\+\/\?{}]/)){
                if(!errorMsgAdded){
                    error += errorMsg;
                    errorMsgAdded = true;
                }
                error += " -" + tags_array[i] + "\n";
            }
        }
        if(error != ""){
            return error;
        }

        //if no error has been encountered so far..check for tag size
        errorMsgAdded = false;
        errorMsg = I18n.getTranslatedTemplateText("Globals.TAG_SIZE_LIMIT_EXCEEDED", maxTagSize);
        for( i = 0; i < tags_array.length; i++){ 
            if(tags_array[i].length > maxTagSize){
                if(!errorMsgAdded){
                    error = errorMsg;
                    errorMsgAdded = true;
                }
                error += " -" + tags_array[i] + "\n";
            }
        }
    }
    return error;
};

/*
Function that validates the tag names
It is to ensure that no special characters can be included as a part of tag names
It alerts the user if the tag name is invalid and returns true or false depending upon 
whether the tag name is valid or not
*/
function validateTagNames(tagsField, checkForEmpty, maxTagSize, maxInputTagsCount, existingTagsCount)
{
    var error = ""; 
    var errorMsg = "";

    if(tagsField)
    {
        tagsValue = trim(tagsField.value);
        if(checkForEmpty){
            if(tagsValue == ""){
                var errorMsg = I18n.getTranslatedTemplateText("Globals.MISSING_TAG_NAME");
                alert(errorMsg);
                return false;
            }
        }
        error += validateTagSyntax(tagsValue, maxTagSize, maxInputTagsCount, existingTagsCount);
        if(error != ""){
            alert(error);
            return false;
        }
    }
   return true;
};

function submitTagForm(form, tagValue){
    form.action = "/gm/tag/" + tagValue;
    if(form.P1){
        form.P1.value = tagValue;
    }
    if(form.OT){
        form.OT.value = "tag";
    }
    form.submit();
};

function fnGetCheckBoxArray(array){
    var arAnswer = new Array();
    for(var i = 0; i < array.length; i++){
        var value = array[i].value;
        var oItem = document.getElementById(value);
        if(oItem){
            arAnswer = arAnswer.concat(oItem); // get the item and add it to the array
        }
    }
    return arAnswer;
};

function fnGetSelectedArray(oForm,sName){
    var i;
    var oItem;
    var arAnswer = new Array();
    var arSelectedValues = new Array();
    var elements = document.getElementsByTagName("input");
    var length = elements.length;
    if(length){
        for(var i = 0; i < length; i++){
            var element = elements[i];
            if(element && element.type == "hidden" && element.name == sName){
                arSelectedValues = arSelectedValues.concat(element); // get the item and add it to the array
            }
        }
    }
    var selTypes = arSelectedValues;
    for(i = 0; i < selTypes.length; i++){
        oItem = selTypes[i];
        if(oItem)
            arAnswer = arAnswer.concat(oItem); // get the item and add it to the array
    }
  return arAnswer;
};

function setObject(arList, sName){
    var selValues = "";
    var numChecked = 0;
    for(var i = 0; i < arList.length; i++){
        var oItem = arList[i];
        var value = oItem.value;
        if(oItem){
            var checkBoxItem = document.getElementById(value);
            if(checkBoxItem && checkBoxItem.checked && checkBoxItem.disabled == false){                  
                var id = checkBoxItem.id;
                numChecked = numChecked + 1;
                var tagName = id.substring(id.indexOf("_") + 1);
                selValues = selValues + tagName;
                if(numChecked > 0 && i < arList.length - 1){
                    selValues = selValues + ",";
                }
            } else {
                selValues = selValues + value;
                if(i < arList.length - 1){
                    selValues = selValues + ",";
                }
            }
        }
    }
    document.getElementById(sName).value = selValues;
};

//Function that validates if any tags are selected for merge
function fnValidateTagsSelected(oForm,fieldName){
    var inputField = oForm[fieldName];
    var count = 0;
    for(var i=0; i<inputField.options.length; i++){
        if(inputField.options[i].selected == true){
            count = count + 1;
        }
    }
    if(count <= 1){
        var errorMsg = I18n.getTranslatedTemplateText("javascript_resource_FormControl.MERGE_ATLEAST_TWO_TAGS");
        alert(errorMsg);
        return false;
    }  
    return true;
};

// Function for tag search 
function performTagSearch(oForm){
    oForm.action = "ManageTags";
    oForm.method = "post";
    oForm.submit();
};


  
  


<!-- End pageContent -->
