/* Javascript Intelligent Forms functionality by Xander Ladage (<GX> 2008)*/

/*Define globals (functions, variables and inherited) (JSLint) */
/*global addIntelligentFormLoadEvent, displayChange, intelliXL, prepareIntelliById, registerIntelligentFormpartValidation*/
/*global alert, document, ValidationArrays, window */

/**
 * GLOBAL VARIABLE: Two-dimesnional array containing validation arrays.
 * Each validation array contains the following elements by index:
 * [0] String   formpart id
 * [1] String   depending formpart NAME
 * [2] String   depending value for list items (works with list formparts only)
 *              If the formpart is not a list formpart, this will be empty
 * [3] Boolean  check for emptyness of input field (works with input / texarea formparts)
 *              If the formpart is not a input / textarea formpart, this will be false
 */
ValidationArrays = [];




/**
 * This function is used for the form "onchange" call.
 * It checks for all registered validations if the formparts depending on eachother should be displayed or not
 *
 * @return    call to the function displayChange(id, display), to change the display of the formpart div based on the validation
 */
function intelliXL(checkValidationArray) {
    try {
        var existingValidation = null;
        var formpartdivid = null;
        var dependingOn = null;
        var dependingObjs = null;
        var dependingValue = null;
        var isEmptyCheck = null;
        var newDisplay = null;
        var dependingObj = null;
        var dependingObjType = null;
        
        for (var i = 0; i < checkValidationArray.length; i = i + 1) {
            existingValidation = checkValidationArray[i];
            formpartdivid = existingValidation[0];
            dependingOn = existingValidation[1];
            dependingValue = existingValidation[2];
            isEmptyCheck = existingValidation[3];
            
            // Using check te see if text input/area if not empty
            if (isEmptyCheck) {
                dependingObjs = document.getElementsByName(dependingOn);
                if (dependingObjs.length > 0) {
                    newDisplay = false;
                    for (var i2 = 0; i2 < dependingObjs.length; i2 = i2 + 1) {
                        dependingObj = dependingObjs[i2];
                        dependingObjType = dependingObj.type;
                        if ((dependingObjType === 'text' || dependingObjType === 'textarea') && dependingObj.value.length > 0) {
                            newDisplay = true;
                        }
                    }
                    // Change display of formpart div
                    displayChange(formpartdivid, newDisplay);
                }  
            }
            
            // Using check te see if list item is selected
            if (dependingValue.length > 0 && ! isEmptyCheck) {
                dependingObjs = document.getElementsByName(dependingOn);
                if (dependingObjs.length > 0) {
                    newDisplay = false;
                    
                    for (var i3 = 0; i3 < dependingObjs.length; i3 = i3 + 1) {
                        dependingObj = dependingObjs[i3];
                        dependingObjType = dependingObj.type;
                        
                        // Display based on selected radio button or checkbox
                        if (dependingObjType === 'radio' || dependingObjType === 'checkbox') {
                            if (dependingObj.checked && dependingObj.value === dependingValue) {
                                newDisplay = true;
                            }
                        }
                        
                        // Display based on selected dropdown option
                        if (dependingObjType === 'select-one') {
                            if (dependingObj.options[dependingObj.selectedIndex].value === dependingValue) {
                                newDisplay = true;
                            }
                        }
                    }
                    // Change display of formpart div
                    displayChange(formpartdivid, newDisplay);
                }
            }  
        } 
    } catch (e) {
        window.status = 'An error occurred: ' + e.message + ' (' + e.name + ')';
    }
}




/**
 * Registers the validations of the formparts
 * 
 * @param   id          id of the formpart which has a validation depending on other formparts
 * @param   validation  ValidationArrays array containing the validation data
 * @return              Adding array to ValidationArrays
 */
function registerIntelligentFormpartValidation(id, validation) {
    try { 
        var existingValidation = null;
        var validationExists = false;
    
        for (var i = 0; i < ValidationArrays.length; i = i + 1) {
            existingValidation = ValidationArrays[i];
            if (existingValidation[0] === validation[0]) {
                validationExists = true;
            }
        }
        if (! validationExists) {
            ValidationArrays[ValidationArrays.length] = validation;
        }
    } catch (e) {
        window.status = 'An error occurred: ' + e.message + ' (' + e.name + ')';
    }
}




/**
 * Changes the display of the DOM object
 * 
 * @param   id        id of DOM formpart div object(s)
 * @param   display   boolean indicating if DOM formpart div object should be displayed or not
 * @return            Changes display property of DOM formpart div object
 */
function displayChange(id, display) {
    try {
        var dependingObj = document.getElementById(id);
        if (dependingObj !== null) {
            if (display) { 
                dependingObj.style.display = "block";
            } else {
                dependingObj.style.display = "none";
            }
        } 
    } catch (e) {
        window.status = 'An error occurred: ' + e.message + ' (' + e.name + ')';
    }
}




/**
 * Function to prepare the array with validations which needs to be checked.
 * By using this function, not all validations are checked, but only those with respect to the changed formpart
 * The onchange of the formpart supplies the formpart identifier, which we can use to see which validations are depending on this formpart
 * 
 * @param   formpartid  identifier of the formpart which was changed. Empty id or "*" leads to all validations being checked
 * @return              call to the intelliXL(checkValidationArray) function, using only needed validations
 */
function prepareIntelliById(formpartid) {
    try {
        var fpid = formpartid;
        var valArray = [];
        var currentValidation = null;
        if (fpid === "*" || fpid === "") {
            valArray = ValidationArrays;
        } else {
            for (var i = 0; i < ValidationArrays.length; i = i + 1) {
                currentValidation = ValidationArrays[i];
                if (fpid === currentValidation[1]) {
                    valArray[valArray.length] = currentValidation;
                }
            }
        }
        if (valArray.length > 0) {
            intelliXL(valArray);
        }
    } catch (e) {
        window.status = 'An error occurred: ' + e.message + ' (' + e.name + ')';
    } 
}




/**
 * Display the form correctly with an onload event
 * 
 * @return              function call to prepare (and check) all validations
 */
function intelliOnload() {
    prepareIntelliById('*');
}