/**
 *  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 ((verOffset = nAgt.indexOf("MSIE")) < 0){
        showRichPanel();
    }
}

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

/**
 * 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() {
    if (!isBrowserIE8()){
        timeoutIDs += window.setTimeout("showRichPanel()", 100);
        timeoutIDs += ";";
    } else {
        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:modal panel in IE8 don't work, we use alert, only forIE8, onli 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) {
      document.getElementById(buttonId).click();
    }
    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
    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;
}

/**
 *  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:DATATABLE') > -1) &&
        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;
        }
    }
}

/**
 *  On the List of InfoObjects and List of Relations page, in the header of 
 *  every tab, if at least one row is selected on the actual tab, set the action
 *  select to sensitive (disabled = false), else set it to insensitive
 */
function controlSensitivityOfActionSelect(formPrefix, cntTab, isChecked) {
    var cntClicksOnActTab = 0;
    
    // First find out how many rows of the actual tab are selected
    for (i=0; i < document.forms[formPrefix + '_LIST'].elements.length; i++) {
        if (document.forms[formPrefix + '_LIST'].elements[i].name.indexOf(formPrefix + '_LIST:CNT_CLICKED_ROWS_DATATABLE_' + cntTab) > -1) {
            if (isChecked) {
                document.forms[formPrefix + '_LIST'].elements[i].value++;
            } else {
                document.forms[formPrefix + '_LIST'].elements[i].value--;
            }
            cntClicksOnActTab = document.forms[formPrefix + '_LIST'].elements[i].value;
        }
    }
    
    // Then, if at least one row is selected on the actual tab, set the action
    // select to sensitive (disabled = false), else set it to insensitive
    // (disabled = true)
    for (i=0; i < document.forms[formPrefix + '_LIST'].elements.length; i++) {
        if ((document.forms[formPrefix + '_LIST'].elements[i].name.indexOf(formPrefix + '_LIST:DATATABLE_' + cntTab) > -1) &&
        (document.forms[formPrefix + '_LIST'].elements[i].name.indexOf('SELECT_ACTION') > -1)){
            if (cntClicksOnActTab > 0) {
                document.forms[formPrefix + '_LIST'].elements[i].disabled = false;
            } else {
                document.forms[formPrefix + '_LIST'].elements[i].disabled = true;
            }
        }
    }
}
    
/**
 * If the file description input fields have not been clicked by the user,
 * they have the default I18N value e.g. "Enter a description", which doesn't
 * have to be inserted into DB. In this case empty the input field.
 * 
 * @author vk
 */
function clearUnclickedFDs(formName) {
    for (i=0; i < document.forms[formName].elements.length; i++) {
        var inputFieldName = document.forms[formName].elements[i].name;
        var inputFieldId = document.forms[formName].elements[i].id;
        // Find hidden BOOL flag for file description
        if ((inputFieldName.indexOf(formName + ':infoObject_') > -1) && (inputFieldName.indexOf('__FD' + '_CLICKED') > -1)){
            // If the file description hasn't been clicked by the user, clear its value
            if (document.getElementById(inputFieldId).value == 'false') {
                var inputFDId = inputFieldId.substring(0, inputFieldId.indexOf('_CLICKED'));
                document.getElementById(inputFDId).value = '';
            }
        }
    }
}

/**
 * Function for Confirmation when a 'Delete' link is clicked. The h:commandLink 
 * assigns the onclick attribute for internal use. This problem is fixed in 
 * JSF 1.2. For lower JSF versions you can use onmousedown event that occurs before 
 * onclick. Note that this might be Browser dependant.
 * 
 * Example usage:
 *   <h:commandLink action="delete" onmousedown="return confirmDelete(this, 'Do you want to Delete?');">
 *      <h:outputText value="Delete"/>
 *   </h:commandLink>
 * 
 *  function confirmDelete(link, text) {
 *      var isDelete = confirm(text);
 *      if (isDelete) {
 *          link.onclick();
 *      }
 *  }
 *
 * Another important point to note is that the JavaScript block should not return 
 * TRUE under any circumstance. If it does so, the browser will proceed to perform 
 * <a href=�#�> � which is redirecting the browser to the dummy �#� page.
 * http://wiki.apache.org/myfaces/JavascriptWithJavaServerFaces
 * 
 * @author sreekanth
 */
function confirmDelete(link, text) {
  return confirm(text);
}

/**
 * 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 {
            return;//pleaseWait();               
        }
    }
    // 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;
        }
    }
}

/**
 * On having pressed TAB and / or RETURN keys, focus to the next field in the 
 * form! Used in InfoObjectView.java
 */
function onEnterSubmitFocusTo(event, strFormName, strFocusTo, bConsiderReturnToo) {
    var ie4 = false;
    if (document.all) {
        ie4 = true; 
    }

    if (ie4) {
        if ((window.event) && ((bConsiderReturnToo && (window.event.keyCode == 13)) || (window.event.keyCode == 9))) {
            document.forms[strFormName][strFormName + ':' + strFocusTo].focus();
            return false;
        } else {
            return true;
        }
    } else {
        if ((event) && ((bConsiderReturnToo && (event.which == 13)) || (event.which == 9))) {
            document.forms[strFormName][strFormName + ':' + strFocusTo].focus();
            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)) {
        
        document.forms[formName].elements[formName + ':' + idUploadComp].focus();
        // document.getElementById['\'' + formName + ':' + idUploadComp + '\''].focus();
    }
}

/**
 * When an event occurs in HTML Editor, this function is called.
 * We capture the Blur event to set the value of hidden TextArea 
 * to the value entered in HTML Editor. This method is handled 
 * only for New/Edit InfoObject forms.
 */
function editorOnBlurHandler(event) {
    
    // window.status = "event:" + event.type;
    // Catch only the onblur event.
    if(event.type.toLowerCase() == 'blur') {
        
        // The ID of current editor. E.g.: 'mce_editor_0'
        var idOfEditor = event.target.editorId;
        // Save the current form ID.
        var currentForm;
        // Store the elements array.
        var allElements;
        
        // Consider only the New/Edit InfoObject forms.
        // Get all 'TextArea' elements in the Form.
        if (document.forms['editInfoObjectForm'] != undefined) {
            currentForm = 'editInfoObjectForm';
            allElements = document.forms['editInfoObjectForm'].getElementsByTagName('textarea');
        } else if (document.forms['newInfoObjectForm'] != undefined) {
            currentForm = 'newInfoObjectForm';
            allElements = document.forms['newInfoObjectForm'].getElementsByTagName('textarea');
        } else {
            // If we don't set them to null, we get Script errors.
            currentForm = null;
            allElements = null;
        }
        
        // For other Forms, don't proceed further.
        if (allElements != undefined) {
            
            // Iterate over all elements.
            for (i=0; i<allElements.length; i++) {

                // Identify the Browser: For IE/Opera we need to retrieve the previousSibling 
                // and for other browsers, we retrieve the nextSibling (not tested).
                var isBrowserIE;
                if ((navigator.userAgent.toLowerCase().indexOf("msie") != -1)
                    || (navigator.userAgent.toLowerCase().indexOf("opera") != -1)) {
                    isBrowserIE = true;
                } else {
                    isBrowserIE = false;
                }

                // Get the sibling ID, e.g: 'mce_editor_0_parent'
                var sibling;
                var currelement = allElements[i];
                if (isBrowserIE) {
                    // This is an IE Browser. Get the previous sibling.
                    if (currelement.previousSibling) {
                        // Proceed only if the previous sibling exists.
                        sibling = currelement.previousSibling;
                    }
                } else {
                    // This is NOT an IE Browser. Get the next sibling.
                    // Proceed only if the next sibling exists.
                    if (currelement.nextSibling) {
                        if(currelement.nextSibling.nodeType == 3) {
                            // For Mozilla/Opera
                            sibling = currelement.nextSibling.nextSibling;
                        } else {
                            // For IE
                            sibling = currelement.nextSibling;
                        }
                    }
                }

                if (sibling != undefined) {

                    var sibID = sibling.id;

                    var index = sibID.indexOf(idOfEditor);
                    if (index >= 0) {

                        // There will be other elements that have 'idOfEditor'.
                        // Hence, we filter only the Dynamic Attribute elements.
                        if (currelement.name.indexOf(currentForm) >= 0) {
                            // debugger;
                            // alert('Source ID: ' + idOfEditor + '\nFound for: ' + currelement.name);
                            // alert('TextArea value before: ' + currelement.value);

                            var origDoc = (document.getElementById(idOfEditor).contentWindow 
                                || document.getElementById(idOfEditor).contentDocument);
                            if (origDoc.document) {
                                origDoc = origDoc.document;
                            }

                            var docvalue = origDoc.body.innerHTML;
                            
                            // If docvalue != currelement.value, then it means that 
                            // the user has modified the text in HTML Editor.
                            if (docvalue != currelement.value) {
                                
                                // Set the 'dataChanged' flag to TRUE.
                                document.forms[currentForm].elements[currentForm + ':dataChanged'].value = 'true';
                                
                                // By default, in FF the innerHTML is set to <br>
                                // In IE the innerHTML is set to <P>&nbsp;</P>
                                // Hence, set the value to blank.
                                if (docvalue == '<br>' 
                                    || docvalue == '<br>\n'
                                    || docvalue == '<P>&nbsp;</P>') {
                                    docvalue = '';
                                }
                                currelement.value = docvalue;
                                // Break the loop otherwise other TextAreas will also get this value.
                                break;
                            
                            }
                        }
                    }
                } // End loop for sibling check.
            } // Iteration on all elements.
        } // End no elements found.
    } // BLUR event capture loop.
    // Continue handling events further.
    return true;
}

/**
 * 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);
}


// G.Gelashvili
// functions for converis:rating component
// Shows Rating-Valueas String "Sehr gut, gut ..." accordingly to mouse position in a new layer
function ratingDivDisplay(ratingValue)
{   
   var varRatingDiv = document.getElementById('ratingDiv');
   var divLabel;
   if(ratingValue <= 1) {
       divLabel = "Sehr schlecht";
   }else if(ratingValue > 1 && ratingValue <= 2) {
       divLabel = "Schlecht";
   }else if (ratingValue > 2 && ratingValue <= 3) {
       divLabel = "Mittel";
   }else if (ratingValue > 3 && ratingValue <= 4) {
       divLabel = "Gut";
   }else {
       divLabel = "Sehr gut";
   }
   
   if( !varRatingDiv)   
   {       
      varRatingDiv = document.createElement('div');
      varRatingDiv.id = 'ratingDiv';
      varRatingDiv.style.position = "absolute";
      ratingDivLabel = document.createElement('label');
      varRatingDiv.appendChild(ratingDivLabel);
      ratingDivLabel.id = 'ratingDivLabel';      
      ratingDivLabel.innerHTML = divLabel;
      document.body.appendChild(varRatingDiv);
   } else {
       ratingDivLabel.innerHTML = divLabel;
   }
   
   varRatingDiv.style.display = "block";
   document.onmousemove = updateMousePosition;
   document.onmouseout = ratingDivHide;
}

// Hide ratingDiv Layer
function ratingDivHide()
{
   varRatingLabelDiv = document.getElementById('ratingDiv');
   
   if(varRatingLabelDiv)
   {      
      varRatingLabelDiv.style.display = "none";      
      document.onmousemove = null;
      document.onmouseout = null;
   }
}

function updateMousePosition(e)
{
   varRatingDiv = document.getElementById('ratingDiv');
   
   if (varRatingDiv)
   {      
      var pos = position(e);      
      varRatingDiv.style.left = (pos.x + 2) + "px";
      varRatingDiv.style.top  = (pos.y - 20) + "px";
   }
}
// defins mouse position
function position(e)
{
   var pos = new Object();
   e = (e) ? e : window.event;
   if (document.layers) {
        pos.x = e.pageX;
        pos.y = e.pageY;
   }else if (document.all) {
        pos.x = e.clientX+document.body.scrollLeft;
        pos.y = e.clientY+document.body.scrollTop;
   }else if (document.getElementById) {
        pos.x = e.pageX;
        pos.y = e.pageY;
   }
  
   return pos;
}

//find objects x position 
function findPos(obj) {
    var currLeftPos = 0;
    if (typeof obj.offsetParent != 'undefined') {       
       do {
           currLeftPos += obj.offsetLeft;        
           obj = obj.offsetParent;
       }while (obj != null);
    }
    else if (obj.x != null) {        
        currLeftPos += obj.x; 
    }        
        return currLeftPos;    
}

//will executed if mouse out.
//assigns start average value to rating bar div
function assignAvgValue(id, avgWidth) {
    var ele = document.getElementById(id);
    if(ele != null) {
        ele.style.width = avgWidth+"%";
    }
}

/**
 * @version ZWM
 * 
 * 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
 */
function enableLoginButton() {
    var loginForm = document.forms['userLoginForm'];
    if (loginForm != null) {
        loginForm.elements['userLoginForm:loginButton'].disabled = false;
    }
}

/**
 * generate warn message, if user try to remove mandatory prop. from field.
 * use in infoobjecttype, relationtype attribute edit view
 */
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.entry.fileName.split('\\');
    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]);
				//e.memo.entry.uploadObject.stop();
				//document.forms['fileUploaderForm'].submit();
				return true;
            }
        }
    }
	return true;
}