/**
 *  CONVERIS JavaScripts for User Interface.
 *  @author sreekanth
 *  Dated: 19 September 2006
 */

var origBackgroundColor = '';
var origColor = '';
var timeoutIDs = '';

function ChangeColor(tableRow,highLight) {
    if (highLight) {
//        tableRow.style.cursor='pointer';
        origBackgroundColor = tableRow.style.backgroundColor;
        tableRow.style.backgroundColor = '#FFEDD9';
        origColor = tableRow.style.color;
        tableRow.style.color = '#334390';
    //tableRow.style.border = 'solid';
    //tableRow.style.borderWidth = '1px';
    //tableRow.style.borderColor = '#969696';
    }
    else {
        tableRow.style.backgroundColor = origBackgroundColor;
        // To avoid the JavaScript error.
        // if (undefined != origColor) {
        if (null != origColor) {
            tableRow.style.color = origColor;
        }else {
            tableRow.style.color = '#FFEDD9';
        }
    //tableRow.style.border = 'solid';
    //tableRow.style.borderWidth = '1px';
    //tableRow.style.borderColor = '#F5F5F5';
    }
}

function DoNav(theUrl) {
    document.location.href = theUrl;
}

/**
 * Find and returns whether the Browser version is MSIE6 or older.
 */
function isBrowserIE6OrBelow() {

    var isIE6 = false;
    // In Internet Explorer, the true version is after "MSIE" in userAgent.
    var nAgt = navigator.userAgent;
    if ((verOffset = nAgt.indexOf("MSIE")) != -1) {

        var fullVersion = parseFloat(nAgt.substring(verOffset+5));
        var majorVersion = parseInt(''+fullVersion);

        // Show ModalPanel only if IE major version is greater than 6.
        if (majorVersion < 7) {
            isIE6 = true;
        }
    }
    return isIE6;
}

/**
 * Find and returns whether the Browser version is MSIE6 or older.
 */
function isBrowserIE8() {

    var isIE8 = false;
    // In Internet Explorer, the true version is after "MSIE" in userAgent.
    var nAgt = navigator.userAgent;
    if ((verOffset = nAgt.indexOf("MSIE")) != -1) {

        var fullVersion = parseFloat(nAgt.substring(verOffset+5));
        var majorVersion = parseInt(''+fullVersion);

        // Show ModalPanel only if IE major version is greater than 6.
        if (majorVersion > 7) {
            isIE8 = true;
        }
    }
    return isIE8;
}

/**
 * When a Link/Button/Drop-Down is clicked (non-AJAX), we show a
 * ModalPanel, so that the User may not click on other controls,
 * during the request is being processed. <br />
 * We call function Richfaces.showModalPanel with window.setTimeout.
 * therefore after we call pleaseWait(), anywhere we must clear timeOut.
 * function terminatePleaseWait() makes that.
 * NOTE: We DO NOT show the ModalPanel for MSIE 6.
 */
function pleaseWait() {
    // since richfaces 3.2.2 Richfaces.showModalPanel with window.setTimeout
    // rich:modal panel dont work in IE8
    var nAgt = navigator.userAgent;
    if (!isBrowserIE6OrBelow()) {
        showRichPanel();
    }
}

function pleaseWaitClose() {
    // since richfaces 3.2.2 Richfaces.showModalPanel with window.setTimeout
    // rich:modal panel dont work in IE8
    var nAgt = navigator.userAgent;
    if (!isBrowserIE6OrBelow()) {
        hideRichPanel();
    }
}

function showRichPanel() {
    Richfaces.showModalPanel('modalPanel',{width:70, top:200});
}

function hideRichPanel() {
    Richfaces.hideModalPanel('modalPanel');
}


function showErrorMsgModalPanel(modalPanelId) {

    // show modal panel if rendered
    if(document.getElementById(modalPanelId) != null) {

        var modalPanelAssignedId = modalPanelId.replace(".*:(.+)$", "$1");
        Richfaces.showModalPanel(modalPanelAssignedId);
    }
}

function showProgressBar() {
    Richfaces.showModalPanel('progressBar_ModalPanel');
}

function hideProgressBar() {
    Richfaces.hideModalPanel('progressBar_ModalPanel');
}

/**
 * function used only in admin view, in infoobject list overview page.
 * set timeout if browser is not IE. else show richpanel directly
 * to avoid duplicate ID exception
 */
function richPanelWithTimeOut() {
    timeoutIDs += window.setTimeout("showRichPanel()", 100);
    timeoutIDs += ";";
// Richfaces.showModalPanel('modalPanel',{width:70, top:200});
}

/**
 * When SAVE/SAVE&CLOSE link is clicked, we show an alert
 * stating that the User should not click anywhere else. <br />
 *
 * NOTE: This is only for MSIE 6.
 */
function alertBeforeSaving() {
    // Show an alert for IE6 users.
    if (isBrowserIE6OrBelow()) {
        alert('Please note that this action might take a while. \n\
Please do not click on any other controls in this page \n\
until the process is completed.');
    }
}

/**
 * Since rich:modalPanel in IE8 doesn't work, we use alert, only for IE8 and
 * only in ObjectsList.jsp.
 */
function alertForIE8() {
    // Show an alert for IE6 users.
    if (isBrowserIE8()) {
        alert('Please note that this action might take a while. \n\
Please do not click on any other controls in this page \n\
until the process is completed.');
    }
}

/**
 * When the User navigates back, via the browser history (Back button),
 * then sometimes the 'Please wait'/ loading image is shown and cannot
 * be stopped. To avoid this, we call this function upon unloading a page.
 */
function terminatePleaseWait() {
    /* clear all timeOuts, if user clicked multiple */
    var idsToClear = timeoutIDs.split(";");
    if(idsToClear.length > 0) {
        for(var i = 0; i < idsToClear.length - 1; i++) {
            window.clearTimeout(idsToClear[i]);
        }
    }
    Richfaces.hideModalPanel('modalPanel');
}

/**
 * function to submit search button for search
 * if user have clicked enter button.
 */
function submitSearchbutton(buttonId, e) {

    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    } else if (e) {
        keycode = e.which;
    } else {
        return true;
    }
    if (keycode == 13) {
        var obj = document.getElementById(buttonId);
        if(obj != null) {
            obj.click();
        }
    }
    return true;
}

/**
 * function to submit search link of type <A> for search
 * if user have clicked enter button.
 */
function submitSearchlink(linkId, e) {

    var keycode;
    if (window.event) {
        keycode = window.event.keyCode;
    } else if (e) {
        keycode = e.which;
    } else {
        return true;
    }

    if (keycode == 13) {
        var obj = document.getElementById(linkId);
        if(obj != null) {
            var fireOnThis = obj;
            var evt = 'click';

            if( document.createEvent ) {
                var evObj = document.createEvent('MouseEvents');
                evObj.initEvent( evt, true, false );
                fireOnThis.dispatchEvent(evObj);
            }
            else if( document.createEventObject ) {
                fireOnThis.fireEvent('on'+evt);
            }
        }
    }
    return true;
}

/**
 * Disable the given Button when clicked and then Form is submitted.
 */
function submitAndDisable(button, disabledStyle, msg) {

    button.className = disabledStyle; // the styleClass for disabled buttons.
    button.disabled = true;
    button.form.action += "?" + button.name + "=" + encodeURI(button.value); //bug# 6294035
    if(msg != null && msg.length > 1) {
        button.value = msg;
    }

    //     // Code to disable other elements. The element values are not
    //     // submitted when this is applied.
    //     var e = button.form.elements;
    //     for (var elem, i = 0; (elem = e[i]); i++ ) {
    //
    //         if (elem.nodeName == 'INPUT') {
    //             if (elem.type.toLowerCase() == 'submit') {
    //                 elem.disabled = true;
    //             } else if (elem.type.toLowerCase() == 'text') {
    //                 elem.disabled = true;
    //             } else if (elem.type.toLowerCase() == 'textarea') {
    //                 elem.disabled = true;
    //             }
    //         } else if (elem.nodeName == 'TEXTAREA') {
    //             if (elem.type.toLowerCase() == 'textarea') {
    //                 elem.disabled = true;
    //             }
    //         }
    //     }

    button.form.submit();
    return true;
}

function disableButton(button, disabledStyle, msg) {

    button.className = disabledStyle; // the styleClass for disabled buttons.
    //button.form.action += "?" + button.name + "=" + encodeURI(button.value); //bug# 6294035
    if(msg != null && msg.length > 1) {
        button.value = msg;
    }
    return true;
}

/**
 * Use for dynamic input components in edit page for onchange event.
 * Submit form if any attribute changed and element dataChanged has value false.
 * In another case do nothing and return.
 */
function submitValue(strFormName) {
    if (document.forms[strFormName] != undefined) {
        var dataChanged = document.forms[strFormName].elements[strFormName + ':dataChanged'].value;

        if ((dataChanged == false) || (dataChanged == 'false')) {
            document.forms[strFormName].elements[strFormName + ':dataChanged'].value = 'true';
            //document.forms[strFormName].submit();
            // Do not submit the form, if any values has been changed on the
            // edit page.
            // Its a usability isuue of the page getting refreshed,
            // the first time user changes something on the page.
            // Fire a onchange event and handle it using ajax, so that the form
            // is submitted and the user is not visually aware of this process.
            fireEvent(document.forms[strFormName].elements[strFormName + ':dataChanged'],'change');
            return;
        } else {
            return;
        }
    }
    // It's important to return undefined since onbeforeunload needs exactly this.
    return;
}

/**
 *  On the List of InfoObjects and List of Relations page, in the header of
 *  every tab, reset the action selection h:selectOneMenu element
 */
function resetHeaderSelectOneMenus(formPrefix) {
    for (i=0; i < document.forms[formPrefix + '_LIST'].elements.length; i++) {

        if ((document.forms[formPrefix + '_LIST'].elements[i].name.indexOf(
            formPrefix + '_LIST:ConverisEntity_') > -1) &&
        (document.forms[formPrefix + '_LIST'].elements[i].name.indexOf('SELECT_ACTION') > -1)) {

            document.forms[formPrefix + '_LIST'].elements[i].options[0].selected = true;
        }
    }
}

/**
 * uncheck all radios excluding this
 * Used from custom:radioButton
 */
function resetStProcessSelectOneRadios(formName, id) {
    var subId = "";
    var eleId = id.substring(formName.length+1, id.length);
    if(eleId.lastIndexOf(":") > 0) {        
        subId = eleId.substring(eleId.lastIndexOf(":")+1, eleId.length);
    } else if (eleId.lastIndexOf("_") > 0){        
        subId = eleId.substring(eleId.lastIndexOf("_")+1, eleId.length);
    }    
    for (i=0; i < document.forms[formName].elements.length; i++) {

        if ((document.forms[formName].elements[i].id.indexOf(subId) > -1)
                                && document.forms[formName].elements[i].id != id) {

            document.forms[formName].elements[i].checked = false;
        }
    }
}

/**
 * Return false if the actually edited Tree, or InfoObjectDTO and so on has been
 * changed and the user wants to discard the changes, else true.
 * Has to be used as per jsf/infoobject/Edit.jsp in the body tag:
 * <body onbeforeunload="return discardChanges(someMsg, someFormName);">
 */
function discardChanges(msgDiscard, strFormName) {
    // Hackish
    if ((msgDiscard == '') || (msgDiscard == undefined)) {
        msgDiscard = 'The data has been changed. Discard?';
    }
    var discardChanges = true;
    if (document.forms[strFormName] != undefined) {
        var dataChanged = document.forms[strFormName].elements[strFormName + ':dataChanged'].value;
        if ((dataChanged == true) || (dataChanged == 'true')) {
            terminatePleaseWait();
            return msgDiscard;
        } else {
            // pleaseWait();
            return;
        }
    }
    // It's important to return undefined since onbeforeunload needs exactly this.
    return;
}

/**
 * confirm if user try to save IO and status Process is not "PUBLISHED"
 **/
function confirmStatusChanged(msgStatChanged, strFormName, statusProcVisible) {
    if (document.forms[strFormName] != undefined) {

        var statVisible = document.forms[strFormName].elements[
        strFormName + ':EDITING_STATUS_pgContent_statusProcess:' +
        statusProcVisible].checked;

        if ((statVisible == false) || (statVisible == 'false')) {
            return confirm(msgStatChanged);
        }else {
            return true;
        }
    } else {
        return true;
    }
}

/**
 * Capture the RETURN key pressed by the users in h:inputTexts: do nothing!
 */
function onEnterSubmitSwallowReturn(event) {

    var ie4 = false;
    if (document.all) {
        ie4 = true;
    }

    if (ie4) {
        if (window.event && window.event.keyCode == 13) {
            return false;
        } else {
            return true;
        }
    } else {
        if (event && event.which == 13) {
            return false;
        } else {
            return true;
        }
    }
}

/**
 * To set the focus on UploadComponent after file uploading.
 */
function focusBrowser(formName) {

    var idUploadComp = document.forms[formName].elements[formName + ':jumpToElementId'].value;
    if (!(idUploadComp=="") && !(idUploadComp==null)) {

        var element = document.forms[formName].elements[formName + ':' + idUploadComp];
        if(element!=undefined) {
            if(idUploadComp.lastIndexOf("_sequenceRelation") != -1) {
                // scroll to the element location only when the focus is on sequence component.
                ScrollToElement(element);
            }
            element.focus();
        }
    // document.getElementById['\'' + formName + ':' + idUploadComp + '\''].focus();
    }
}

/**
 * Call in body.onload If hidden element value is not empty, try to find element with given ID
 * and scroll page to element.
 */
function focusOnElement() {
    
     var focuesOn = document.getElementById("ioWizardView:ioWizardForm:FocusOnHelper");
     // focusEleId is in Value of hidden inputfield in edit page
     var focusEleId = null;
     if(focuesOn != null) {
         focusEleId = focuesOn.value;
     }
     
     if(focusEleId != null && focusEleId.length > 1) {

         var ele = document.getElementById("ioWizardView:ioWizardForm:" + focusEleId);
         if(ele != null) {
             ScrollToElement(ele);
         }
     }
}

/**
 * Scroll the page to a yindex of 100 below the actual yindex of the component.
 */
function ScrollToElement(element) {

    var selectedPosX = 0;
    var selectedPosY = 0;
    while (element != null) {

        selectedPosX += element.offsetLeft;
        selectedPosY += element.offsetTop;
        element = element.offsetParent;
    }
    window.scrollTo(selectedPosX,selectedPosY-100);
}

/**
 * This function evaluates the given text and truncates it until
 * the given length of characters.
 *
 * @param inputField The HTML input field element.
 * @param threshold The maximum number of characters to be allowed.
 * @param remainingCharsFieldID The ID of the TextField that displays the
 * remaining characters.
 */
function truncate(inputField, threshold, remainingCharsFieldID) {

    var elementID = inputField.id;
    // var inputField = document.getElementById(elementID);
    var count = (threshold - inputField.value.length);
    if(count <= 0) {
        inputField.value = inputField.value.substring(0, threshold);
        inputField.focus();
    }
    var lastColonIndex = elementID.lastIndexOf(':');
    var fullCharsFieldID = elementID.substring(0, lastColonIndex) + ':' + remainingCharsFieldID;
    // elements['nonNavObjectDetailForm:nonNavObjectDetailSubview:
    //              pgDetailCenterColumn:0:centerDetail_stat:remainingCharsField'].

    document.
    forms['nonNavObjectDetailForm'].
    elements[fullCharsFieldID].
    value = (threshold - inputField.value.length);
}

/**
 * This function enables the Login button again, which will be
 * disabled once clicked. We call this function in almost all
 * the JSPs in the PublicView of ZWM, as the Login form is
 * embedded in the header. <BR/>
 * This function assumes the following ID for the Login button:
 * userLoginForm:loginButton
 *
 * @version ZWM
 */
function enableLoginButton() {
    var loginForm = document.forms['userLoginForm'];
    if (loginForm != null) {
        loginForm.elements['userLoginForm:loginButton'].disabled = false;
    }
}

/**
 * Generate warning message, if user try to remove mandatory properties
 * from field. Used in InfoObjectType and RelationType Attribute edit pages.
 */
function confirmMandatoryField(confirmMsg, elId) {
    box = document.getElementById(elId);

    if(!box.checked) {
        if(confirm(confirmMsg)) {
            return true;
        } else {
            box.checked = true;
            return false;
        }
    } else {
        return true;
    }
}

/**
 * Used in the file uploader module, to check if the selected file for upload
 * already exists on the file server.
 */
function _onuploadHandler(e, fileNames, msg) {
    var words = fileNames.split(',');
    var i =0;

    var entryFile = e.memo.entries[0].fileName.split('\\');
    var fileInList = entryFile[entryFile.length-1];

    for (i=0;i<words.length;i++)
    {
        if(fileInList == words[i]) {
            if(!confirm(words[i] +' '+msg)){
                e.memo.entries[0].uploadObject.clear(e.memo.entries[0], true);
                return true;
            } else {
                Richfaces.showModalPanel('uploadFunction_modalPanel');
                return true;
            }
        }
    }
    Richfaces.showModalPanel('uploadFunction_modalPanel');
    return true;
}

/**
 * Used to cancel the file upload process.
 */
function _oncancelHandler(componentId, uploadIdentifier) {
    if (undefined != $(componentId).component.entries[0] && undefined != $(componentId).component) {
        $(componentId).component.entries[0].uploadObject.stop();
        //$(componentId).component.entries[0].uploadObject.clear($(componentId).component.entries[0],true);
        $(componentId).component.clear();
    }
    Richfaces.hideModalPanel(uploadIdentifier);
}

/**
 * Solution for : In IE6, Combo boxes inside modal panel are disabled.
 * In IE6, when the a modal panel is displayed then the modal panel mask does
 * not disable the combobox elements on the underlying page. So RichFaces
 * internally disables all the comboboxes on the current page incl those inside
 * a modal panel. So here reset the disabled attribute of the select element,
 * when showing the modal panel.
 *
 * Use this function on the 'onshow' event of a modalpanel, that could
 * possibly contain a combobox. Pass in as attribute either the view id or the
 * modal panel id in order to apply this function only for the elements inside
 * this modal panel
 */
function enableSelectOptionForIE6(viewMode) {
    if(isBrowserIE6OrBelow()) {
        var ar = document.getElementsByTagName("select");

        for (var i = 0; i < ar.length;i++) {
            var cSel = ar[i];
            if(cSel.id.indexOf(viewMode) != -1) {
                cSel.setAttribute("enabled", "");
                cSel.setAttribute("disabled", "");
            }
        }
    }
}

/**
 * This function returns the (currently viewed) width of the client's
 * browser window.
 * Ref: http://www.alistapart.com/articles/footers/
 */
function getCurrentWindowWidth() {

    var windowWidth = 0;
    if (typeof(window.innerWidth) == 'number') {
        windowWidth = window.innerWidth;
    } else {
        if (document.documentElement && document.documentElement.clientWidth) {
            windowWidth = document.documentElement.clientWidth;
        } else {
            if (document.body && document.body.clientWidth) {
                windowWidth = document.body.clientWidth;
            }
        }
    }
    return windowWidth;
}

/**
 * This function will update the style of the floating footer when the window
 * width is less than 750px. This is a fix for Bug #1524.
 */
function updateFloatFooterStyle() {
    if (document.getElementById) {

        var windowWidth = getCurrentWindowWidth();
        if (windowWidth > 0) {

            var footerElement = document.getElementById('ioWizardView:ioWizardForm:floatFoot');
            // alert('window width: ' + windowWidth);

            if (null != footerElement) {

                if (windowWidth < 756) {
                    footerElement.style.paddingLeft = '5px';
                    footerElement.style.width = '100%';
                } else {
                    footerElement.style.paddingLeft = '243px';
                    footerElement.style.width = '746px';                   
                }
            }
        }
    }
}

/**
 * This function is used to resize the Modal panels when the desktop resolution
 * is less than 800x600. If the resolution is low, we decrease the size of the
 * given element (identified by strPreviewBodyMainContent) to 600x200
 */
function resizePreviewDialog(strPreviewBodyMainContent) {

    // Check if the screen resolution is low.
    // In such cases, resize the preview dialog.
    var elemPreviewBody = document.getElementById(strPreviewBodyMainContent);
    var panelheight = elemPreviewBody.offsetHeight;
    if ((screen.width <='800') || (screen.height <='600')) { 
        elemPreviewBody.style.width = '550px';
        elemPreviewBody.style.height = '200px';
    }
    else if(panelheight > screen.height) {
        elemPreviewBody.style.height = '550px';
        elemPreviewBody.style.overflowY = 'auto';
    }
}

/**
 * This function sets the CSS position property of the floating footer container
 * to 'relative', only if the Browser is Internet Explorer and its version <= 6.
 */
function fixedFooterInIE6() {
    if (isBrowserIE6OrBelow()) {
        var element = document.getElementById('ioWizardView:ioWizardForm:floatFoot');
        element.style.position = 'relative';
    }
}

/**
 * This function will increase the height of the MainContentArea with respect to
 * the SectionGrid.
 * Logic: First find all the Grid heights and sum it. Then compare this height
 * with the height of sections grid. If the total height is less than the grid
 * of section height, increase the last grid height to the difference of
 * (sectionheight - totalgridheight).
 */
function expandMainContentArea() {

    var wizSectionEdit = document.getElementById('ioWizardView:ioWizardForm:wizSection');
    var wizContentTable = document.getElementById('ioWizardView:ioWizardForm:mainContentGrid');
    if (wizContentTable) {

        var wizContentTableRow = wizContentTable.getElementsByTagName("tr");
    }
    if (wizSectionEdit && wizContentTable && wizContentTableRow) {

        var totalHeight = 0;
        // Find the total height of the rows and
        // the element in the first column of the last row.
        for (i=0; i<wizContentTableRow.length; i++) {
            if (wizContentTableRow[i].className.toString() == 'wiz-content-row') {
                totalHeight = totalHeight + wizContentTableRow[i].cells[0].clientHeight;
                lastRowFirstColumn = wizContentTableRow[i].cells[0];
            }
        }

        // If the Section grid height is greater than the total height (previously
        // found), we set the height of the lastRowFirstColumn element to the
        // calculated difference between the Section grid height and the totalHeight.
        if (totalHeight < wizSectionEdit.clientHeight) {

            var heightDiff = wizSectionEdit.clientHeight - totalHeight;
            if (null != lastRowFirstColumn) {
                lastRowFirstColumn.height = lastRowFirstColumn.clientHeight
                + heightDiff + 'px';
            }
        }
    }
}

/**
 * Provides the functionality to toggle the Help DIV in modules.
 */
function toggleHelp() {
    toggleHelper('help');
    return;
}

function toggleHelper(strHelpId) {
    if (document.getElementById(strHelpId)) {
        helpDiv = document.getElementById(strHelpId);

        if(helpDiv.style.display == "block") {
            helpDiv.style.display = "none";
        } else {
            helpDiv.style.display = "block";
        }
    }
    return;
}

/**
 * Provides the functionality to toggle the Help in InfoObjectEditor wizard.
 */
function toggleEditorWizardHelp(helpTextGrid) {

    if (helpTextGrid) {
        var helpText = helpTextGrid.id + "_helptxt";
        if (document.getElementById(helpText)) {

            var helpBox = document.getElementById(helpText);
            var agt = navigator.userAgent.toLowerCase();
            if (agt.indexOf("safari") != -1) {
                    helpBox.style.width = '95%';
            }

            if (helpBox.style.display == "block") {
                helpBox.style.display = "none";
            } else {
                helpBox.style.display = "block";
            }
        }
    }
    return;
}

// ================== BEGIN: Temporarily save relation attributes ==============

// Arrays for all input fields of RelationTypeAttributes displayed.
var allFormElements = new Array();
var arrayOfIdex = new Array();

/**
 * In CONVERIS v3.5, after changing the value in the UIComponents of
 * RelationTypeAttributes and clicking on 'Select' or 'Close' link will
 * clear/reset the changed values to the original values. To avoid this
 * behaviour, we store the entered values temporarily and then set them
 * on the UIComponent, when an AJAX call is completed.
 */
function storeRelationAttributes(formElement) {
    if (formElement) {
        if (formElement.type == "select-one") {
            var index = formElement.selectedIndex;
            formElement.options[index].selected = true;
            arrayOfIdex[arrayOfIdex.length] = formElement.id + ','+ index;
        }

        if (allFormElements.length == 0) {
            allFormElements[0] = formElement;
        } else if (!contains(allFormElements, formElement)) {
            allFormElements[allFormElements.length] = formElement;
        }
    }
}

/**
 * Checks whether the component is present in the temporary array of objects.
 */
function contains(formElement, obj) {
    for (var i = 0; i < formElement.length; i++) {
        if (formElement[i] == obj) {
            return true;
        }
    }
  return false;
}

/**
 * After adding a relation, add the values present in the temporary array to
 * the components in the page.
 */
function updateValuesOfRelationFields() {
    var tempFormElement;
    for (var i=0; i<allFormElements.length; i++ ) {

        tempFormElement = document.getElementById(allFormElements[i].id.toString());
        if (tempFormElement.type == "text" || tempFormElement.type == "textarea" ) {
            tempFormElement.value = allFormElements[i].value;

        } else if(tempFormElement.type == "checkbox" || tempFormElement.type == "radio") {
            tempFormElement.checked = allFormElements[i].checked;

        } else if(tempFormElement.type == "select-one") {

            var agt = navigator.userAgent.toLowerCase();
            if (agt.indexOf("msie") != -1) {
                for (var idx = 0; idx<arrayOfIdex.length; idx++) {

                    var tempArrayTextFields = arrayOfIdex[idx].split(',');
                    var tempId = tempArrayTextFields[0];

                    if (allFormElements[i].id == tempId) {
                        tempFormElement.selectedIndex=tempArrayTextFields[1];
                    }
                }
            } else {
                var index1 = allFormElements[i].selectedIndex;
                tempFormElement.options[index1].selected = true;
            }
        }
        tempFormElement = null;
    }
}

/**
 * Reset the input fields when the page is reloaded.
 */
function resetRelationInputFields() {
    allFormElements = [];
    arrayOfIdex = [];
}
// ================== END: Temporarily save relation attributes ================

function findSearch(target) {
    links=document.getElementsByTagName("input");
    for(i=0;i<links.length;i++) {
        link=links[i];

        var applyPattern='.+:' + target + '$';
        var match = link.id.match(applyPattern);
        if(match != null) {
            return link;
        }
    }
    return null;
}

function clickSearch(target) {
    var search = findSearch(target);
    if(search){
        fireEvent(search,'click');
    }
}

function fireEvent(obj,evt){

    var fireOnThis = obj;    
    if( document.createEvent ) {
        var evObj = document.createEvent('MouseEvents');
        evObj.initEvent( evt, true, false );
        fireOnThis.dispatchEvent(evObj);
    } else if( document.createEventObject ) {        
        fireOnThis.fireEvent('on'+evt);
    }
}

/**
 * Fire event on the dummy link on edit page to submit the page.
 */
function fireDummyLinkToSubmitEditPage() {    
    if (document.forms['ioWizardView:ioWizardForm'] != undefined) {
        var nAgt = navigator.userAgent;
        // No support for createEvent in Apple Safari. Do not use this function in Safari
        // find another solution for Safari
        if (nAgt.indexOf("Safari") == -1) {
            var elemt = document.getElementById('ioWizardView:ioWizardForm:dummyLinkToSubmit');            
            fireEvent(elemt,'click');
        }
    }    
    return;
}

