<commit_before>(function() {
    'use strict';

    angular
        .module('webApp')
        .controller('InputsCtrl', InputsCtrl);

    InputsCtrl.$inject = ['FragmentFactory', 'PolicyFactory', 'TemplateFactory', '$filter', '$modal'];

    function InputsCtrl(FragmentFactory, PolicyFactory, TemplateFactory, $filter, $modal) {
        /*jshint validthis: true*/
       var vm = this;

       vm.getInputs = getInputs;
       vm.deleteInput = deleteInput;
       vm.getInputTypes = getInputTypes;
       vm.createInput = createInput;
       vm.editInput = editInput;
       vm.createInputModal = createInputModal;
       vm.editInputModal = editInputModal;
       vm.duplicateInput = duplicateInput;
       vm.deleteInputConfirm = deleteInputConfirm;
       vm.getPolicyNames = getPolicyNames;
       vm.setInputsId = setInputsId;
       vm.inputTypes = [];
       vm.inputId = 1;

       init();

        /////////////////////////////////

        function init() {
            getInputs();
        };

        function getInputs() {
            var inputList = FragmentFactory.GetFragments("input");

            inputList.then(function (result) {
                vm.inputsData = vm.setInputsId(result);
                vm.getInputTypes(result);
            });
        };

        function deleteInput(fragmentType, fragmentName, index) {
            console.log('--> Deleting input');
            console.log('> Getting Policies affected');
            var policiesToDelete = PolicyFactory.GetPolicyByFragmentName(fragmentType, fragmentName);

            policiesToDelete.then(function (result) {
                console.log(result);

                var policies = vm.getPolicyNames(result);
                var inputToDelete =
                {
                    'type':fragmentType,
                    'name': fragmentName,
                    'policies': policies,
                    'index': index
                };
                vm.deleteInputConfirm('lg', inputToDelete);
            },
            function (error) {
              console.log('#ERROR#');
              console.log(error);
            });
        };

        function duplicateInput(inputName) {
            var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];

            var newName = autoIncrementName(inputSelected.name);
            inputSelected.name = newName;

            var newName = SetDuplicatetedInput('sm', inputSelected);
       };

        function createInput() {
           var inputFragmentTemplate = TemplateFactory.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
                console.log('*********Controller');
                console.log(result);

                var createInputData = {
                    'action': 'create',
                    'inputDataTemplate': result,
                    'texts': {
                        'title': '_INPUT_WINDOW_NEW_TITLE_',
                        'button': '_INPUT_WINDOW_NEW_BUTTON_',
                        'button_icon': 'icon-circle-plus'
                    }
                };

               vm.createInputModal(createInputData);
           });
        };

        function editInput(inputType, inputName, index) {
           var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];
           var id = inputSelected.id;

           delete inputSelected["id"];

           var inputFragmentTemplate = TemplateFactory.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
                console.log('--> Editing input');
                console.log('> Getting Fragment Template');
                console.log(result);
                console.log('> Getting Policies affected');
                var policiesAffected = PolicyFactory.GetPolicyByFragmentName(inputType, inputName);
                var inputDataTemplate = result;

                policiesAffected.then(function (result) {
                    console.log(result);

                    var policies = vm.getPolicyNames(result);
                    var editInputData = {
                        'index': index,
                        'id': id,
                        'action': 'edit',
                        'inputSelected': inputSelected,
                        'inputDataTemplate': inputDataTemplate,
                        'policies': policies,
                        'texts': {
                            'title': '_INPUT_WINDOW_MODIFY_TITLE_',
                            'button': '_INPUT_WINDOW_MODIFY_BUTTON_',
                            'button_icon': 'icon-circle-check'
                        }
                    };

                    vm.editInputModal(editInputData);
                },
                function (error) {
                  console.log('#ERROR#');
                  console.log(error);
                });
           });
        };

        function setInputsId(inputsData) {
            for (var i=0; i < inputsData.length; i++) {
                inputsData[i].id = vm.inputId;
                vm.inputId++;
            }
            return inputsData;
        };

        function getPolicyNames(policiesData) {
            var policies = [];

            for (var i=0; i<policiesData.length; i++){
                policies.push(policiesData[i].name);
            }

            return policies;
        };

        function getInputTypes(inputs) {
            for (var i=0; i<inputs.length; i++) {
                var newType = false;
                var type    = inputs[i].element.type;

                if (i === 0) {
                    vm.inputTypes.push({'type': type, 'count': 1});
                }
                else {
                    for (var j=0; j<vm.inputTypes.length; j++) {
                        if (vm.inputTypes[j].type === type) {
                            vm.inputTypes[j].count++;
                            newType = false;
                            break;
                        }
                        else if (vm.inputTypes[j].type !== type){
                            newType = true;
                        }
                    }
                    if (newType) {
                        vm.inputTypes.push({'type': type, 'count':1});
                    }
                }
            }
        };

        function createInputModal(newInputTemplateData) {
            var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return newInputTemplateData;
                   }
               }
            });

            modalInstance.result.
               then(function (newInputData) {
                   console.log('*************** Controller back');
                   console.log(newInputData);

                   var newFragment = FragmentFactory.CreateFragment(newInputData.data);

                   newFragment
                       .then(function (result) {
                           console.log('*********Fragment created');
                           console.log(result);

                           var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                           result.id = newId;

                           vm.inputsData.push(result);
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
            };

        function editInputModal(editInputData) {
           var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return editInputData;
                   }
               }
           });

           modalInstance.result.
               then(function (updatedInputData) {
                   console.log('*************** Controller back');
                   console.log(updatedInputData);

                   var updatedFragment = FragmentFactory.UpdateFragment(updatedInputData.data);

                   updatedFragment
                       .then(function (result) {
                           console.log('*********Fragment updated');
                           console.log(result);

                           result.id = updatedInputData.id;

                           vm.inputsData[updatedInputData.index] = result;
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
        };

        function deleteInputConfirm(size, input) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_delete_modal.tpl.html',
                controller: 'DeleteFragmentModalCtrl',
                size: size,
                resolve: {
                    item: function () {
                        return input;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    console.log(selectedItem);
                    var fragmentDeleted = FragmentFactory.DeleteFragment(selectedItem.type, selectedItem.name);

                    fragmentDeleted
                        .then(function (result) {
                            console.log('*********Fragment deleted');
                            vm.inputsData.splice(selectedItem.index, 1);

                        });
                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };

        function SetDuplicatetedInput(size, inputName) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_duplicate_modal.tpl.html',
                controller: 'DuplicateFragmentModalCtrl as vm',
                size: 'lg',
                resolve: {
                    item: function () {
                        return inputName;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    delete selectedItem["id"];
                    console.log(selectedItem);

                    var newFragment = FragmentFactory.CreateFragment(selectedItem);

                    newFragment
                        .then(function (result) {
                            console.log('*********Fragment created');
                            console.log(result);

                            var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                            selectedItem.id = newId;

                            vm.inputsData.push(selectedItem);
                        },
                        function (error) {
                            console.log(error);
                            console.log('Modal dismissed at: ' + new Date())
                        });

                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };
    };

    /*NEW & EDIT FRAGMENT MODAL CONTROLLER*/
    angular
        .module('webApp')
        .controller('NewFragmentModalCtrl', NewFragmentModalCtrl);

    NewFragmentModalCtrl.$inject = ['$modalInstance', 'item', 'FragmentFactory'];

    function NewFragmentModalCtrl($modalInstance, item, FragmentFactory) {
        /*jshint validthis: true*/
        var vm = this;

        vm.setProperties = setProperties;
        vm.ok = ok;
        vm.cancel = cancel;
        vm.initFragmentObject = initFragmentObject;
        vm.setFragmentData = setFragmentData;
        vm.createTypeModels = createTypeModels;
        vm.dataSource = {};
        vm.dataSource.element = {};
        vm.templateInputsData = [];
        vm.properties = [];
        vm.error = false;

        init();

        /////////////////////////////////

        function init() {
            console.log('--> NewFragmentModalCtrl');
            console.log('> Data received');
            console.log(item);

            setTexts(item.texts);

            vm.action = item.action;

            if (vm.action === 'edit') {
                vm.templateInputsData = item.inputDataTemplate;
                vm.dataSource = item.inputSelected;
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = vm.index;
                vm.policiesAffected = item.policies;
            }
            else {
                vm.templateInputsData = item.inputDataTemplate;
                vm.initFragmentObject(vm.templateInputsData);
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = 0;
            }
        };

        function setTexts(texts) {
            vm.modalTexts = {};
            vm.modalTexts.title = texts.title;
            vm.modalTexts.button = texts.button;
            vm.modalTexts.icon = texts.button_icon;
        }

        function initFragmentObject(fragmentData) {
            /*Init fragment*/
            vm.dataSource.fragmentType = 'input';
            vm.dataSource.name = '';

            /*Init fragment.element*/
            vm.dataSource.element.type = fragmentData[0].name;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;

            /*Init fragment.element.configuration*/
            vm.dataSource.element.configuration = {};

            vm.setFragmentData(0);
        };

        function createTypeModels(fragmentData) {
            /*Create one properties model for each input type*/
            for (var i=0; i<fragmentData.length; i++){
                vm.properties[fragmentData[i].name] = {};

                for (var j=0; j<fragmentData[i].properties.length; j++) {
                    if (fragmentData[i].properties[j].propertyId !== 'name' && fragmentData[i].properties[j].propertyId !== 'type'){
                        vm.properties[fragmentData[i].name][fragmentData[i].properties[j].propertyId] = '';
                    }
                }

                /*Init properties*/
                if(i === 0 && vm.action !== 'edit') {
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                }

                else if(vm.action === 'edit' && fragmentData[i].name === vm.dataSource.element.type) {
                    vm.properties[fragmentData[i].name] = vm.dataSource.element.configuration;
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                    vm.index = i;
                }
            }
        };

        function setFragmentData(index) {
            /*Set fragment*/
            vm.dataSource.description = vm.templateInputsData[index].description.long;
            vm.dataSource.shortDescription = vm.templateInputsData[index].description.short;
            vm.dataSource.icon = vm.templateInputsData[index].icon.url;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;
        };

        function setProperties(index, inputName) {
            vm.selectedIndex = index;
            vm.dataSource.element.configuration = vm.properties[inputName];
            vm.setFragmentData(index);
        };

        function ok() {
            if (vm.form.$valid){
                checkInputName(vm.dataSource.fragmentType, vm.dataSource.name);
            }
        };

        function checkInputName(inputType, inputName) {
            var newFragment = FragmentFactory.GetFragmentByName(inputType, inputName);

            newFragment
            .then(function (result) {
                vm.error = true;
            },
            function (error) {
                var callBackData = {
                    'index': item.index,
                    'id': item.id,
                    'data': vm.dataSource,
                };
               $modalInstance.close(callBackData);
            });
        };

        function cancel() {
            $modalInstance.dismiss('cancel');
        };
    };

    /*DELETE INPUT MODALS CONTROLLER */
    angular
        .module('webApp')
        .controller('DeleteFragmentModalCtrl', DeleteFragmentModalCtrl);

    DeleteFragmentModalCtrl.$inject = ['$scope', '$modalInstance', 'item'];

    function DeleteFragmentModalCtrl($scope, $modalInstance, item) {
        console.log('*********Modal');
        console.log(item);

        $scope.inputs = item;

        $scope.ok = function () {
            $modalInstance.close($scope.inputs);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };

    /*DUPLICATE INPUT MODAL CONTROLLER */
    angular
        .module('webApp')
        .controller('DuplicateFragmentModalCtrl', DuplicateFragmentModalCtrl);

    DuplicateFragmentModalCtrl.$inject = ['$modalInstance', 'item', 'FragmentFactory'];

    function DuplicateFragmentModalCtrl($modalInstance, item, FragmentFactory) {
        /*jshint validthis: true*/
        var vm = this;

        vm.ok = ok;
        vm.cancel = cancel;
        vm.error = false;

        init();

        ///////////////////////////////////////

        function init () {
            console.log('*********Modal');
            console.log(item);
            vm.inputData = item;
        };

        function ok() {
            if (vm.form.$valid){
                checkInputName(vm.inputData.fragmentType, vm.inputData.name);
            }
        };

        function checkInputName(inputType, inputName) {
            var newFragment = FragmentFactory.GetFragmentByName(inputType, inputName);

            newFragment
            .then(function (result) {
                vm.error = true;
            },
            function (error) {
                $modalInstance.close(vm.inputData);
            });
        };

        function cancel() {
            $modalInstance.dismiss('cancel');
        };
    };
})();
<commit_msg>feature/inputs-v1: renaming modals in conrtoller<commit_after>(function() {
    'use strict';

    angular
        .module('webApp')
        .controller('InputsCtrl', InputsCtrl);

    InputsCtrl.$inject = ['FragmentFactory', 'PolicyFactory', 'TemplateFactory', '$filter', '$modal'];

    function InputsCtrl(FragmentFactory, PolicyFactory, TemplateFactory, $filter, $modal) {
        /*jshint validthis: true*/
       var vm = this;

       vm.getInputs = getInputs;
       vm.deleteInput = deleteInput;
       vm.getInputTypes = getInputTypes;
       vm.createInput = createInput;
       vm.editInput = editInput;
       vm.createInputModal = createInputModal;
       vm.editInputModal = editInputModal;
       vm.duplicateInput = duplicateInput;
       vm.deleteInputConfirm = deleteInputConfirm;
       vm.getPolicyNames = getPolicyNames;
       vm.setInputsId = setInputsId;
       vm.inputTypes = [];
       vm.inputId = 1;

       init();

        /////////////////////////////////

        function init() {
            getInputs();
        };

        function getInputs() {
            var inputList = FragmentFactory.GetFragments("input");

            inputList.then(function (result) {
                vm.inputsData = vm.setInputsId(result);
                vm.getInputTypes(result);
            });
        };

        function deleteInput(fragmentType, fragmentName, index) {
            console.log('--> Deleting input');
            console.log('> Getting Policies affected');
            var policiesToDelete = PolicyFactory.GetPolicyByFragmentName(fragmentType, fragmentName);

            policiesToDelete.then(function (result) {
                console.log(result);

                var policies = vm.getPolicyNames(result);
                var inputToDelete =
                {
                    'type':fragmentType,
                    'name': fragmentName,
                    'policies': policies,
                    'index': index
                };
                vm.deleteInputConfirm('lg', inputToDelete);
            },
            function (error) {
              console.log('#ERROR#');
              console.log(error);
            });
        };

        function duplicateInput(inputName) {
            var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];

            var newName = autoIncrementName(inputSelected.name);
            inputSelected.name = newName;

            var newName = SetDuplicatetedInput('sm', inputSelected);
       };

        function createInput() {
           var inputFragmentTemplate = TemplateFactory.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
                console.log('*********Controller');
                console.log(result);

                var createInputData = {
                    'action': 'create',
                    'inputDataTemplate': result,
                    'texts': {
                        'title': '_INPUT_WINDOW_NEW_TITLE_',
                        'button': '_INPUT_WINDOW_NEW_BUTTON_',
                        'button_icon': 'icon-circle-plus'
                    }
                };

               vm.createInputModal(createInputData);
           });
        };

        function editInput(inputType, inputName, index) {
           var inputSelected = $filter('filter')(angular.copy(vm.inputsData), {name:inputName}, true)[0];
           var id = inputSelected.id;

           delete inputSelected["id"];

           var inputFragmentTemplate = TemplateFactory.GetNewFragmentTemplate('input');

           inputFragmentTemplate.then(function (result) {
                console.log('--> Editing input');
                console.log('> Getting Fragment Template');
                console.log(result);
                console.log('> Getting Policies affected');
                var policiesAffected = PolicyFactory.GetPolicyByFragmentName(inputType, inputName);
                var inputDataTemplate = result;

                policiesAffected.then(function (result) {
                    console.log(result);

                    var policies = vm.getPolicyNames(result);
                    var editInputData = {
                        'index': index,
                        'id': id,
                        'action': 'edit',
                        'inputSelected': inputSelected,
                        'inputDataTemplate': inputDataTemplate,
                        'policies': policies,
                        'texts': {
                            'title': '_INPUT_WINDOW_MODIFY_TITLE_',
                            'button': '_INPUT_WINDOW_MODIFY_BUTTON_',
                            'button_icon': 'icon-circle-check'
                        }
                    };

                    vm.editInputModal(editInputData);
                },
                function (error) {
                  console.log('#ERROR#');
                  console.log(error);
                });
           });
        };

        function setInputsId(inputsData) {
            for (var i=0; i < inputsData.length; i++) {
                inputsData[i].id = vm.inputId;
                vm.inputId++;
            }
            return inputsData;
        };

        function getPolicyNames(policiesData) {
            var policies = [];

            for (var i=0; i<policiesData.length; i++){
                policies.push(policiesData[i].name);
            }

            return policies;
        };

        function getInputTypes(inputs) {
            for (var i=0; i<inputs.length; i++) {
                var newType = false;
                var type    = inputs[i].element.type;

                if (i === 0) {
                    vm.inputTypes.push({'type': type, 'count': 1});
                }
                else {
                    for (var j=0; j<vm.inputTypes.length; j++) {
                        if (vm.inputTypes[j].type === type) {
                            vm.inputTypes[j].count++;
                            newType = false;
                            break;
                        }
                        else if (vm.inputTypes[j].type !== type){
                            newType = true;
                        }
                    }
                    if (newType) {
                        vm.inputTypes.push({'type': type, 'count':1});
                    }
                }
            }
        };

        function createInputModal(newInputTemplateData) {
            var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return newInputTemplateData;
                   }
               }
            });

            modalInstance.result.
               then(function (newInputData) {
                   console.log('*************** Controller back');
                   console.log(newInputData);

                   var newFragment = FragmentFactory.CreateFragment(newInputData.data);

                   newFragment
                       .then(function (result) {
                           console.log('*********Fragment created');
                           console.log(result);

                           var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                           result.id = newId;

                           vm.inputsData.push(result);
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
            };

        function editInputModal(editInputData) {
           var modalInstance = $modal.open({
               animation: true,
               templateUrl: 'templates/inputs/input-details.tpl.html',
               controller: 'NewFragmentModalCtrl as vm',
               size: 'lg',
               resolve: {
                   item: function () {
                       return editInputData;
                   }
               }
           });

           modalInstance.result.
               then(function (updatedInputData) {
                   console.log('*************** Controller back');
                   console.log(updatedInputData);

                   var updatedFragment = FragmentFactory.UpdateFragment(updatedInputData.data);

                   updatedFragment
                       .then(function (result) {
                           console.log('*********Fragment updated');
                           console.log(result);

                           result.id = updatedInputData.id;

                           vm.inputsData[updatedInputData.index] = result;
                           console.log(vm.inputsData);
                       },
                       function (error) {
                           console.log(error);
                           console.log('Modal dismissed at: ' + new Date())
                       });

               }, function () {
                   console.log('Modal dismissed at: ' + new Date())
               });
        };

        function deleteInputConfirm(size, input) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_delete_modal.tpl.html',
                controller: 'DeleteFragmentModalCtrl',
                size: size,
                resolve: {
                    item: function () {
                        return input;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    console.log(selectedItem);
                    var fragmentDeleted = FragmentFactory.DeleteFragment(selectedItem.type, selectedItem.name);

                    fragmentDeleted
                        .then(function (result) {
                            console.log('*********Fragment deleted');
                            vm.inputsData.splice(selectedItem.index, 1);

                        });
                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };

        function SetDuplicatetedInput(size, inputName) {
            var modalInstance = $modal.open({
                animation: true,
                templateUrl: 'templates/components/st_duplicate_modal.tpl.html',
                controller: 'DuplicateFragmentModalCtrl as vm',
                size: 'lg',
                resolve: {
                    item: function () {
                        return inputName;
                    }
                }
            });

            modalInstance.result
                .then(function (selectedItem) {
                    delete selectedItem["id"];
                    console.log(selectedItem);

                    var newFragment = FragmentFactory.CreateFragment(selectedItem);

                    newFragment
                        .then(function (result) {
                            console.log('*********Fragment created');
                            console.log(result);

                            var newId = vm.inputsData[vm.inputsData.length-1].id + 1;
                            selectedItem.id = newId;

                            vm.inputsData.push(selectedItem);
                        },
                        function (error) {
                            console.log(error);
                            console.log('Modal dismissed at: ' + new Date())
                        });

                },
                function () {
                    console.log('Modal dismissed at: ' + new Date())
                });
        };
    };

    /*NEW & EDIT FRAGMENT MODAL CONTROLLER*/
    angular
        .module('webApp')
        .controller('NewFragmentModalCtrl', NewFragmentModalCtrl);

    NewFragmentModalCtrl.$inject = ['$modalInstance', 'item', 'FragmentFactory'];

    function NewFragmentModalCtrl($modalInstance, item, FragmentFactory) {
        /*jshint validthis: true*/
        var vm = this;

        vm.setProperties = setProperties;
        vm.ok = ok;
        vm.cancel = cancel;
        vm.initFragmentObject = initFragmentObject;
        vm.setFragmentData = setFragmentData;
        vm.createTypeModels = createTypeModels;
        vm.dataSource = {};
        vm.dataSource.element = {};
        vm.templateInputsData = [];
        vm.properties = [];
        vm.error = false;

        init();

        /////////////////////////////////

        function init() {
            console.log('--> NewFragmentModalCtrl');
            console.log('> Data received');
            console.log(item);

            setTexts(item.texts);

            vm.action = item.action;

            if (vm.action === 'edit') {
                vm.templateInputsData = item.inputDataTemplate;
                vm.dataSource = item.inputSelected;
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = vm.index;
                vm.policiesAffected = item.policies;
            }
            else {
                vm.templateInputsData = item.inputDataTemplate;
                vm.initFragmentObject(vm.templateInputsData);
                vm.createTypeModels(vm.templateInputsData);
                vm.selectedIndex = 0;
            }
        };

        function setTexts(texts) {
            vm.modalTexts = {};
            vm.modalTexts.title = texts.title;
            vm.modalTexts.button = texts.button;
            vm.modalTexts.icon = texts.button_icon;
        }

        function initFragmentObject(fragmentData) {
            /*Init fragment*/
            vm.dataSource.fragmentType = 'input';
            vm.dataSource.name = '';

            /*Init fragment.element*/
            vm.dataSource.element.type = fragmentData[0].name;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;

            /*Init fragment.element.configuration*/
            vm.dataSource.element.configuration = {};

            vm.setFragmentData(0);
        };

        function createTypeModels(fragmentData) {
            /*Create one properties model for each input type*/
            for (var i=0; i<fragmentData.length; i++){
                vm.properties[fragmentData[i].name] = {};

                for (var j=0; j<fragmentData[i].properties.length; j++) {
                    if (fragmentData[i].properties[j].propertyId !== 'name' && fragmentData[i].properties[j].propertyId !== 'type'){
                        vm.properties[fragmentData[i].name][fragmentData[i].properties[j].propertyId] = '';
                    }
                }

                /*Init properties*/
                if(i === 0 && vm.action !== 'edit') {
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                }

                else if(vm.action === 'edit' && fragmentData[i].name === vm.dataSource.element.type) {
                    vm.properties[fragmentData[i].name] = vm.dataSource.element.configuration;
                    vm.dataSource.element.configuration = vm.properties[fragmentData[i].name];
                    vm.index = i;
                }
            }
        };

        function setFragmentData(index) {
            /*Set fragment*/
            vm.dataSource.description = vm.templateInputsData[index].description.long;
            vm.dataSource.shortDescription = vm.templateInputsData[index].description.short;
            vm.dataSource.icon = vm.templateInputsData[index].icon.url;
            vm.dataSource.element.name = 'in-' + vm.dataSource.element.type;
        };

        function setProperties(index, inputName) {
            vm.selectedIndex = index;
            vm.dataSource.element.configuration = vm.properties[inputName];
            vm.setFragmentData(index);
        };

        function ok() {
            if (vm.form.$valid){
                checkInputName(vm.dataSource.fragmentType, vm.dataSource.name);
            }
        };

        function checkInputName(inputType, inputName) {
            var newFragment = FragmentFactory.GetFragmentByName(inputType, inputName);

            newFragment
            .then(function (result) {
                vm.error = true;
            },
            function (error) {
                var callBackData = {
                    'index': item.index,
                    'id': item.id,
                    'data': vm.dataSource,
                };
               $modalInstance.close(callBackData);
            });
        };

        function cancel() {
            $modalInstance.dismiss('cancel');
        };
    };

    /*DELETE INPUT MODALS CONTROLLER */
    angular
        .module('webApp')
        .controller('DeleteFragmentModalCtrl', DeleteFragmentModalCtrl);

    DeleteFragmentModalCtrl.$inject = ['$scope', '$modalInstance', 'item'];

    function DeleteFragmentModalCtrl($scope, $modalInstance, item) {
        console.log('*********Modal');
        console.log(item);

        $scope.inputs = item;

        $scope.ok = function () {
            $modalInstance.close($scope.inputs);
        };

        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    };

    /*DUPLICATE INPUT MODAL CONTROLLER */
    angular
        .module('webApp')
        .controller('DuplicateFragmentModalCtrl', DuplicateFragmentModalCtrl);

    DuplicateFragmentModalCtrl.$inject = ['$modalInstance', 'item', 'FragmentFactory'];

    function DuplicateFragmentModalCtrl($modalInstance, item, FragmentFactory) {
        /*jshint validthis: true*/
        var vm = this;

        vm.ok = ok;
        vm.cancel = cancel;
        vm.error = false;

        init();

        ///////////////////////////////////////

        function init () {
            console.log('*********Modal');
            console.log(item);
            vm.inputData = item;
        };

        function ok() {
            if (vm.form.$valid){
                checkInputName(vm.inputData.fragmentType, vm.inputData.name);
            }
        };

        function checkInputName(inputType, inputName) {
            var newFragment = FragmentFactory.GetFragmentByName(inputType, inputName);

            newFragment
            .then(function (result) {
                vm.error = true;
            },
            function (error) {
                $modalInstance.close(vm.inputData);
            });
        };

        function cancel() {
            $modalInstance.dismiss('cancel');
        };
    };
})();
<|endoftext|>


<commit_before>'use strict';

var expect  = require('chai').expect;
var ColorContrastChecker = require('../src/color-contrast-checker');
var ccc = new ColorContrastChecker();

describe('Three Digit Color Code Lengths', function() {
  it('should accept 3 digit color code', function() {
    var result = ccc.isValidThreeDigitColorCode("#FFF");
    expect(result).to.be.true;
  });

  it('should reject 2 digit color code', function() {
    var result = ccc.isValidThreeDigitColorCode("#FF");
    expect(result).to.be.false;
  });

  it('should reject 4 digit color code', function() {
    var result = ccc.isValidThreeDigitColorCode("#FFFF");
    expect(result).to.be.false;
  });
});

describe('Six Digit Color Code Lengths', function() {
  it('should accept 6 digit color code', function() {
    var result = ccc.isValidSixDigitColorCode("#FFFFFF");
    expect(result).to.be.true;
  });

  it('should reject 5 digit color code', function() {
    var result = ccc.isValidSixDigitColorCode("#FFFFF");
    expect(result).to.be.false;
  });

  it('should reject 7 digit color code', function() {
    var result = ccc.isValidSixDigitColorCode("#FFFFFFF");
    expect(result).to.be.false;
  });
});

describe('Supported Color Code Lengths', function() {
  it('should accept 3 digit color code', function() {
    var result = ccc.isValidColorCode("#FFF");
    expect(result).to.be.true;
  });

  it('should accept 6 digit color code', function() {
    var result = ccc.isValidColorCode("#FFFFFF");
    expect(result).to.be.true;
  });

  it('should reject 7 digit color code', function() {
    var result = ccc.isValidColorCode("#FFFFFFF");
    expect(result).to.be.false;
  });
});

describe('Supported Custom Ratio Inputs', function() {
  it('should accept an integer', function() {
    var result = ccc.isValidRatio(1);
    expect(result).to.be.true;
  });

  it('should accept a float', function() {
    var result = ccc.isValidRatio(3.2);
    expect(result).to.be.true;
  });

  it('should reject a string', function() {
    var result = ccc.isValidRatio("3.2");
    expect(result).to.be.false;
  });
});

describe('Convert Color from 3 digit to 6 digit', function() {
  it('should convert 3 digit color to 6 digit', function() {
    var result = ccc.convertColorToSixDigit("#FFF");
    expect(result).to.equal("#FFFFFF");
  });
});

describe('Convert Hex to Luminance', function() {
  it('should convert 3 digit color luminance value', function() {
    var result = ccc.hexToLuminance("#FFF");
    expect(result).to.equal(1);
  });

  it('should convert 6 digit color luminance value', function() {
    var result = ccc.hexToLuminance("#FFFFFF");
    expect(result).to.equal(1);
  });

  it('should convert blue color luminance value', function() {
    var result = ccc.hexToLuminance("#0000FF");
    expect(result).to.equal(0);
  });

   it('should convert yellow color luminance value', function() {
    var result = ccc.hexToLuminance("#ffff00");
    expect(result).to.equal(1);
  });
});

describe('Basic Validation for LevelAA', function() {
   it('should return true when contrast is valid for three digit color codes', function() {
    var result = ccc.isLevelAA("#FFF", "#000", 14);
    expect(result).to.be.true;
  });

  it('should return true when contrast is valid', function() {
    var result = ccc.isLevelAA("#FFFFFF", "#000000", 14);
    expect(result).to.be.true;
  });

  it('should return false when contrast is invalid', function() {
    var result = ccc.isLevelAA("#000000", "#000000", 14);
    expect(result).to.be.false;
  });
});

describe('Basic Validation for LevelAAA', function() {
   it('should return true when contrast is valid for three digit color codes', function() {
    var result = ccc.isLevelAA("#FFF", "#000", 14);
    expect(result).to.be.true;
  });

  it('should return true when contrast is valid', function() {
    var result = ccc.isLevelAA("#FFFFFF", "#000000", 14);
    expect(result).to.be.true;
  });

  it('should return false when contrast is invalid', function() {
    var result = ccc.isLevelAA("#000000", "#000000", 14);
    expect(result).to.be.false;
  });
});

describe('Basic Validation for Custom Ratio', function() {
  it('should return true when contrast is valid for three digit color codes', function() {
   var result = ccc.isLevelCustom("#FFF", "#000", 14, 5);
   expect(result).to.be.true;
 });

 it('should return true when contrast is valid', function() {
   var result = ccc.isLevelCustom("#FFFFFF", "#000000", 14, 5);
   expect(result).to.be.true;
 });

 it('should return false when contrast is invalid', function() {
   var result = ccc.isLevelCustom("#000000", "#000000", 14, 5);
   expect(result).to.be.false;
 });
});

describe('Six Digit Pair Validation for LevelAAA', function() {
  var pairs = [
      {
          'colorA': '#000000',
          'colorB': '#000000',  // All should fail
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#FFFFFF',  //All should pass
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#848484',  //AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#848484',  //All should pass (because of font)
          'fontSize': 19
      },
      {
          'colorA': '#000000',
          'colorB': '#757575',  //AA should pass AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#656565',  //All should fail
          'fontSize': 14
      }
  ];

  var expectedResults = [
    { WCAG_AA: false, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: false, WCAG_AAA: false } ];

  function objectsAreSame(x, y) {
    var objectsAreSame = true;
    x.forEach((element, index) => {
      if (element.WCAG_AA !== y[index].WCAG_AA) {
        objectsAreSame = false
      }
      if (element.WCAG_AAA !== y[index].WCAG_AAA) {
        objectsAreSame = false
      }
    });
    return objectsAreSame;
    }

  it('should return the expectedResults for checkPairs', function() {
    var results = ccc.checkPairs(pairs);
    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(6);
    expect(objectsAreSame(results, expectedResults)).to.be.true;
  });
});

describe('Three Digit Pair Validation for LevelAAA', function() {
  var pairs = [
      {
          'colorA': '#000',
          'colorB': '#000',  // All should fail
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#FFF',  //All should pass
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#848',  //AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#848',  //All should pass (because of font)
          'fontSize': 19
      },
      {
          'colorA': '#000',
          'colorB': '#757',  //AA should pass AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#656',  //All should fail
          'fontSize': 14
      }
  ];

  var expectedResults = [
    { WCAG_AA: false, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: false, WCAG_AAA: false } ];

  function objectsAreSame(x, y) {
    var objectsAreSame = true;
    x.forEach((element, index) => {
      if (element.WCAG_AA !== y[index].WCAG_AA) {
        objectsAreSame = false
      }
      if (element.WCAG_AAA !== y[index].WCAG_AAA) {
        objectsAreSame = false
      }
    });
    return objectsAreSame;
   }
  it('should return the expectedResults for checkPairs', function() {
    var results = ccc.checkPairs(pairs);
    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(6);
    expect(objectsAreSame(results, expectedResults)).to.be.true;
  });
});

  describe('Six Digit Pair Validation for Custom Ratio', function() {
    var pairs = [
        {
            'colorA': '#000000',
            'colorB': '#000000',  // This should fail
            'fontSize': 14
        },
        {
            'colorA': '#000000',
            'colorB': '#FFFFFF',  // This should pass
            'fontSize': 14
        },
        {
            'colorA': '#000000',
            'colorB': '#848484',  // This should pass
            'fontSize': 14
        },
        {
            'colorA': '#000000',
            'colorB': '#656565',  // This should fail
            'fontSize': 14
        }
    ];

    var expectedResults = [
      { customRatio: false },
      { customRatio: true },
      { customRatio: true },
      { customRatio: false } ];

    function objectsAreSame(x, y) {
      var objectsAreSame = true;
      x.forEach((element, index) => {
        if (element.WCAG_AA !== y[index].WCAG_AA) {
          objectsAreSame = false
        }
        if (element.WCAG_AAA !== y[index].WCAG_AAA) {
          objectsAreSame = false
        }
      });
      return objectsAreSame;
    }

  it('should return the expectedResults for checkPairs', function() {
    var results = ccc.checkPairs(pairs, 5.6);
    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(4);
    expect(objectsAreSame(results, expectedResults)).to.be.true;
  });
});
<commit_msg>Fix test input<commit_after>'use strict';

var expect  = require('chai').expect;
var ColorContrastChecker = require('../src/color-contrast-checker');
var ccc = new ColorContrastChecker();

describe('Three Digit Color Code Lengths', function() {
  it('should accept 3 digit color code', function() {
    var result = ccc.isValidThreeDigitColorCode("#FFF");
    expect(result).to.be.true;
  });

  it('should reject 2 digit color code', function() {
    var result = ccc.isValidThreeDigitColorCode("#FF");
    expect(result).to.be.false;
  });

  it('should reject 4 digit color code', function() {
    var result = ccc.isValidThreeDigitColorCode("#FFFF");
    expect(result).to.be.false;
  });
});

describe('Six Digit Color Code Lengths', function() {
  it('should accept 6 digit color code', function() {
    var result = ccc.isValidSixDigitColorCode("#FFFFFF");
    expect(result).to.be.true;
  });

  it('should reject 5 digit color code', function() {
    var result = ccc.isValidSixDigitColorCode("#FFFFF");
    expect(result).to.be.false;
  });

  it('should reject 7 digit color code', function() {
    var result = ccc.isValidSixDigitColorCode("#FFFFFFF");
    expect(result).to.be.false;
  });
});

describe('Supported Color Code Lengths', function() {
  it('should accept 3 digit color code', function() {
    var result = ccc.isValidColorCode("#FFF");
    expect(result).to.be.true;
  });

  it('should accept 6 digit color code', function() {
    var result = ccc.isValidColorCode("#FFFFFF");
    expect(result).to.be.true;
  });

  it('should reject 7 digit color code', function() {
    var result = ccc.isValidColorCode("#FFFFFFF");
    expect(result).to.be.false;
  });
});

describe('Supported Custom Ratio Inputs', function() {
  it('should accept an integer', function() {
    var result = ccc.isValidRatio(1);
    expect(result).to.be.true;
  });

  it('should accept a float', function() {
    var result = ccc.isValidRatio(3.2);
    expect(result).to.be.true;
  });

  it('should reject a string', function() {
    var result = ccc.isValidRatio("3.2");
    expect(result).to.be.false;
  });
});

describe('Convert Color from 3 digit to 6 digit', function() {
  it('should convert 3 digit color to 6 digit', function() {
    var result = ccc.convertColorToSixDigit("#FFF");
    expect(result).to.equal("#FFFFFF");
  });
});

describe('Convert Hex to Luminance', function() {
  it('should convert 3 digit color luminance value', function() {
    var result = ccc.hexToLuminance("#FFF");
    expect(result).to.equal(1);
  });

  it('should convert 6 digit color luminance value', function() {
    var result = ccc.hexToLuminance("#FFFFFF");
    expect(result).to.equal(1);
  });

  it('should convert blue color luminance value', function() {
    var result = ccc.hexToLuminance("#0000FF");
    expect(result).to.equal(0);
  });

   it('should convert yellow color luminance value', function() {
    var result = ccc.hexToLuminance("#ffff00");
    expect(result).to.equal(1);
  });
});

describe('Basic Validation for LevelAA', function() {
   it('should return true when contrast is valid for three digit color codes', function() {
    var result = ccc.isLevelAA("#FFF", "#000", 14);
    expect(result).to.be.true;
  });

  it('should return true when contrast is valid', function() {
    var result = ccc.isLevelAA("#FFFFFF", "#000000", 14);
    expect(result).to.be.true;
  });

  it('should return false when contrast is invalid', function() {
    var result = ccc.isLevelAA("#000000", "#000000", 14);
    expect(result).to.be.false;
  });
});

describe('Basic Validation for LevelAAA', function() {
   it('should return true when contrast is valid for three digit color codes', function() {
    var result = ccc.isLevelAA("#FFF", "#000", 14);
    expect(result).to.be.true;
  });

  it('should return true when contrast is valid', function() {
    var result = ccc.isLevelAA("#FFFFFF", "#000000", 14);
    expect(result).to.be.true;
  });

  it('should return false when contrast is invalid', function() {
    var result = ccc.isLevelAA("#000000", "#000000", 14);
    expect(result).to.be.false;
  });
});

describe('Basic Validation for Custom Ratio', function() {
  it('should return true when contrast is valid for three digit color codes', function() {
   var result = ccc.isLevelCustom("#FFF", "#000", 14, 5);
   expect(result).to.be.true;
 });

 it('should return true when contrast is valid', function() {
   var result = ccc.isLevelCustom("#FFFFFF", "#000000", 14, 5);
   expect(result).to.be.true;
 });

 it('should return false when contrast is invalid', function() {
   var result = ccc.isLevelCustom("#000000", "#000000", 14, 5);
   expect(result).to.be.false;
 });
});

describe('Six Digit Pair Validation for LevelAAA', function() {
  var pairs = [
      {
          'colorA': '#000000',
          'colorB': '#000000',  // All should fail
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#FFFFFF',  //All should pass
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#998899',  //AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#998899',  //All should pass (because of font)
          'fontSize': 19
      },
      {
          'colorA': '#000000',
          'colorB': '#887788',  //AA should pass AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000000',
          'colorB': '#656565',  //All should fail
          'fontSize': 14
      }
  ];

  var expectedResults = [
    { WCAG_AA: false, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: false, WCAG_AAA: false } ];

  function objectsAreSame(x, y) {
    var objectsAreSame = true;
    x.forEach((element, index) => {
      if (element.WCAG_AA !== y[index].WCAG_AA) {
        objectsAreSame = false
      }
      if (element.WCAG_AAA !== y[index].WCAG_AAA) {
        objectsAreSame = false
      }
    });
    return objectsAreSame;
    }

  it('should return the expectedResults for checkPairs', function() {
    var results = ccc.checkPairs(pairs);
    console.log(results, "\n", expectedResults);
    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(6);
    expect(objectsAreSame(results, expectedResults)).to.be.true;
  });
});

describe('Three Digit Pair Validation for LevelAAA', function() {
  var pairs = [
      {
          'colorA': '#000',
          'colorB': '#000',  // All should fail
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#FFF',  //All should pass
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#989',  //AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#989',  //All should pass (because of font)
          'fontSize': 19
      },
      {
          'colorA': '#000',
          'colorB': '#878',  //AA should pass AAA should fail
          'fontSize': 14
      },
      {
          'colorA': '#000',
          'colorB': '#656',  //All should fail
          'fontSize': 14
      }
  ];

  var expectedResults = [
    { WCAG_AA: false, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: true, WCAG_AAA: true },
    { WCAG_AA: true, WCAG_AAA: false },
    { WCAG_AA: false, WCAG_AAA: false } ];

  function objectsAreSame(x, y) {
    var objectsAreSame = true;
    x.forEach((element, index) => {
      if (element.WCAG_AA !== y[index].WCAG_AA) {
        objectsAreSame = false
      }
      if (element.WCAG_AAA !== y[index].WCAG_AAA) {
        objectsAreSame = false
      }
    });
    return objectsAreSame;
   }
  it('should return the expectedResults for checkPairs', function() {
    var results = ccc.checkPairs(pairs);
    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(6);
    expect(objectsAreSame(results, expectedResults)).to.be.true;
  });
});

  describe('Six Digit Pair Validation for Custom Ratio', function() {
    var pairs = [
        {
            'colorA': '#000000',
            'colorB': '#000000',  // This should fail
            'fontSize': 14
        },
        {
            'colorA': '#000000',
            'colorB': '#FFFFFF',  // This should pass
            'fontSize': 14
        },
        {
            'colorA': '#000000',
            'colorB': '#998899',  // This should pass
            'fontSize': 14
        },
        {
            'colorA': '#000000',
            'colorB': '#656565',  // This should fail
            'fontSize': 14
        }
    ];

    var expectedResults = [
      { customRatio: false },
      { customRatio: true },
      { customRatio: true },
      { customRatio: false } ];

    function objectsAreSame(x, y) {
      var objectsAreSame = true;
      x.forEach((element, index) => {
        if (element.WCAG_AA !== y[index].WCAG_AA) {
          objectsAreSame = false
        }
        if (element.WCAG_AAA !== y[index].WCAG_AAA) {
          objectsAreSame = false
        }
      });
      return objectsAreSame;
    }

  it('should return the expectedResults for checkPairs', function() {
    var results = ccc.checkPairs(pairs, 5.6);
    expect(results).to.be.an('array');
    expect(results).to.have.lengthOf(4);
    expect(objectsAreSame(results, expectedResults)).to.be.true;
  });
});
<|endoftext|>


<commit_before>if (enyo && enyo.version) {
	enyo.version.layout = "2.4.0-pre.1";
}
<commit_msg>Update version string to 2.4.0-pre.2<commit_after>if (enyo && enyo.version) {
	enyo.version.layout = "2.4.0-pre.2";
}
<|endoftext|>


<commit_before>// $Id$
/*
file: autoToc.js
author: Jobi Carter
contact: keacarterdev@gmail.com
license: WTFPL
purpose: Automatically generate two table of contents on tiki pages with more than one header. The tocs are composed of clickable links to headers. One toc stays on the top of the page, while the seconds scrolls along with the page (css necessary) and hides until moused over.
last updated: 08/09/13

This script can be implimented in Tiki Wiki via editing the tiki-setup.php file and adding the following to the end of it.
	$headerlib->add_jsfile('path/to/file/here');

Generated output / What this does
	This script will generate two divs which contain a clickable table of contents for the headers on the page. One sits at the top of the page, and the other appears when you scroll past the one on the top. When you scroll past the top toc, a tab appears on the top of the page. When you mouse over this tab, a table of contents will appear. Clicking an item in the toc, or scrolling the page, will make the tab close again. The tab will be semi-transparent until it is moused over, and the toc appears. You can also click the tab to be taken to the top of the page.

disabling the toc
		turn off this script by adding a div with the id "toc-off" to a page.
		this script can be turned off for a category by adding a module with the "toc-off" div, and setting that module to only appear on that category.
		the script can be set to apply only to specific headers via the largestHeader and smallestHeader variables
		the script can be completely disabled by removing the headerLib entry in tiki-setup.php

This script does the following:
		determine if wiki page
		determine if page has the "toc-off"
		determine if more than one header on page
		insert toc HTML
		iterate over page and set Ids for header elements
			This is necessary because WYSIWYG fails to set correct Ids consistently.
		While setting header Ids, generate a HTML indented list of header anchors which point to their respective headers via header id
		set mouseover and onScroll events for two tocs

The following CSS should be applied to your theme's css file for correct behavior. You may need to adjust margin (where the toc that scrolls with you shows up) based on your theme:

	div#outerToc {
	        position:fixed;
	        top:0px;
	        margin-left:25%;
	        background:#E0E0E0;
	        display:none;
	        padding:10px;
	        border-radius:0px 0px 5px 5px;
	        z-index:5;
	}

*/

$(function () {
	//if a wiki page, and if there is no toc-off div
	if (document.getElementById("page-data") && !document.getElementById("toc-off") && document.location.href.indexOf("tiki-print.php") == -1) {
		//get headers
		headers = $("div#page-data").find(":header");

		//if there are more than one headers on the page
		if (headers.length > 1) {

			//**************Add the Toc Divs to the Page**************//

			//set target div IDs. these divs will be populated with an autoToc
			//innerToc and toc-static are required. Additional divs may be specified.
			tocDivs = ["innerToc", "toc-static"];

			//string to add html for toc divs
			tocString = "
  Table of Contents, or Click for Page Top

";

			//create the div to hold the tocs, and populate its inner HTML with the tocString
			tocContainer = document.createElement("div");
			tocContainer.innerHTML = tocString;

			//get pageData div, as we want to add toc before that
			page = document.getElementById("page-data");

			//add the tocContainer as first child of page-data div
			firstChild = page.firstChild;
			page.insertBefore(tocContainer, firstChild);

			//Configure starting header and ending header
			largestHeader = 1;
			smallestHeader = 6;

			//**************Iterate over headers and create autoToc HTML List**************//

			//start from indentation level 0, with header one as base
			previousHeaderLevel = 1;

			//create object to store processed IDs.
			var processedId = new Object();

			//function to process header Id generation. If an ID which has been processed is generated again and passed in again, the id name will be incremented to id_[1*]
			function processId(id) {
				if (id in processedId) {
					//if processed before
					//iterate count for header with this ane
					processedId[id] += 1;
					//set the new id to id plus count for header
					newId = id + "_" + processedId[id];
				} else {
					//if not processed before
					//add to "dictionary' with count of 0
					processedId[id] = 0;
					//return id passed in
					newId = id;
				}
				return newId;
			}

			//open HTML list and initialize string which will store the HTML list
			var str = '
';

			//Iterate over the headers
			for (i = 0; i < headers.length; i++) {

				//get header level for header to see if this header should be processed or not
				headerLevel = parseInt(headers[i].tagName[1]);

				//If the header level in range of acceptable headers, begin processing it
				if (headerLevel >= largestHeader && headerLevel <= smallestHeader) {

					//store browser location to append the #[1*/header text] to
					browserLocation = document.location.href;

					//Make the base URL for the link as everything up to page name plus hash. multistructure pages might have issues with this, but we are avoiding multistruction pages to avoid multicategory pages, so should be fine. For links to headers (via ids) to work, you need to have a clean url like cewiki/pagename#id, with nothing after the id string: https://cewiki-dev.colorado.edu/es-Searching+for+a+Student+Record#Overview will work, but https://cewiki-dev.colorado.edu/es-Searching+for+a+Student+Record#Overview&structure=es-Enrollment+Services will not.
					pointTo = browserLocation.substring(0, browserLocation.indexOf('&')) + "#";

					//current header
					header = headers[i]

					//grab the whole header element to show as the anchor text
					aText = header.innerHTML.trim(); //trim incase inner html is text (if <hx>text</hx>)

					//if the header is complicated (composed of multiple HTML Elements)
					if (header.children.length > 0) {
						//set the id to the the inner text of the header, with underscores instead of "<", ">", and spaces (" "). Increment Id checks if the ID has been assigned yet, and if so, increments the Id with a number at the end of the id name
						id = processId($(aText).text().trim().replace(/ /g, "_").replace(/</g, "_").replace(/>/g, "_"))

						//if the header is simple
					} else {
						//the inner html of the header is just text, so use anchor text for the id directly
						id = processId(aText.replace(/ /g, "_").replace(/</g, "_").replace(/>/g, "_")) //replace all spaces with underscore, and special chars
					}

					//construct the URL from the base URL with a # and the ID for the Div
					url = pointTo + id; //url is baseurl#divId

					//set the element's id to the constructed ID
					//Need to do this because WYSIWYG does not set IDs on divs correctly. May be able to set flag to check if tiki editor, and mimic how it creates IDs, avoiding this step.
					header.setAttribute("id", id);

					//create the HTML anchor item with the text from the header and pointing to baseurl#divId
					itm = '
' + aText + '
';

					//*****use the information gathered to write the string of the HTML for the list of anchors*****//

					//The following code determines how indented the previous header was, and closes or opens sublists to match that indentation level.
					//Example:
					//h1
					//h2
					//h3
					//h1
					//Above, if it had just written the h3, and it went to write the h1, its initial indentLevel would be 1, while previous would be 3, so it would know it needs to close sublists equal to the difference beteen its indentation level and that of h3. So, it would need to close two levels from h3 to get to h1, and then write the item.
					//To do this, the code below either applies ++ or -- on the indentLevel variable while closing or opening sublists until the current indentLevel matches the previousHeaderLevel.

					indentLevel = headerLevel;

					//if header is a sub header (nested on a child level of the previous header), meaning its indent level is greater than that of the previousHeaderLevel
					if (indentLevel > previousHeaderLevel) {
						//open a new sublist for each level of difference

						//this is an alternative way to think about this
						//~ openCount = indentLevel - previousHeaderLevel
						//~ for i in range(openCount):
						//~ str +="
"
						//~ str+= item

						while (indentLevel > previousHeaderLevel) {
							//open sublist
							str += "
";
							//track header level vs previous header to tell when to stop
							indentLevel -= 1;
						}
						//when header levels match, write item
						str += itm;
					}
					//else, if header is higher up (parent level of list, but wont be a parent of the page because below)
					else if (indentLevel < previousHeaderLevel) {
						//close sublists for each level of difference
						while (indentLevel < previousHeaderLevel) {
							//close sublist
							str += "
";
							//track header level vs previous header to tell when to stop
							indentLevel += 1;
						}
						//when header levels match, write item
						str += itm;

						//elif header levels are same
					} else if (indentLevel == previousHeaderLevel) {
						//write item
						str += itm;
					}
				}
				//set current header level to previous header level for next iteration
				previousHeaderLevel = headerLevel;
			}

			//close list
			str += '
';

			//set target div's inner html to the list
			for (i = 0; i < tocDivs.length; i++) {
				document.getElementById(tocDivs[i]).innerHTML = str;
			}

			//**************Add special mouse over and scroll behavior to toc**************//
			//make it so the non-static toc shows up on top of the page when you scroll past the first static top which sits at the top of the page.
			//make it so that when you mouse over the non-static toc's outer container, the inner container shows up
			//make it so that when you scroll, the innner-toc, which holds the toc, hides, and you just see the outerToc container.

			//set onmouseover for outerToc
			document.getElementById("outerToc").onmouseover = function () {
				//closure, sets "scope/context" for function setVis on mouse over
				var inner = document.getElementById('innerToc');
				var outer = document.getElementById('outerToc');

				function setVis(inner, outer) {
					//make the outerToc container more opaque
					outer.style.opacity = 1;
					//show the inner toc div, displaying the toc
					inner.style.display = 'block';
				}

				return setVis(inner, outer);
			}

			//set the scroll functionality
			//determine where the "mobile toc" should start showing up
			static_toc = $('#outerToc-static');
			start = $(static_toc).offset().top + $(static_toc).height();

			//assign inner and outer vars for window scroll event
			var outer = $('#outerToc'); //$(div);
			var inner = $('#innerToc');

			//set on scroll event to do: on scroll, hide the floating toc if you would overlap with the toc on the top of the page, otherwise hide the inner toc
			$.event.add(window, "scroll", function () {
				//position
				var p = $(window).scrollTop();

				//if current position is below the other toc and start of the page
				if (p > start) {
					//set outertoc position to fixed at top of screen
					outer.css('display', 'block');
					//hide inner toc
					inner.css('display', 'none');
					//make outerToc slightly transparent
					document.getElementById('outerToc').style.opacity = .5
				} else {
					//if current position overlaps with the static toc at top of page, hide non-static toc div
					outer.css('display', 'none');
				}
			});
		}
	}
});<commit_msg>[FIX] Avoid JS error in AutoTOC. Thanks jonnyb<commit_after>// $Id$
/*
file: autoToc.js
author: Jobi Carter
contact: keacarterdev@gmail.com
license: WTFPL
purpose: Automatically generate two table of contents on tiki pages with more than one header. The tocs are composed of clickable links to headers. One toc stays on the top of the page, while the seconds scrolls along with the page (css necessary) and hides until moused over.
last updated: 08/09/13

This script can be implimented in Tiki Wiki via editing the tiki-setup.php file and adding the following to the end of it.
	$headerlib->add_jsfile('path/to/file/here');

Generated output / What this does
	This script will generate two divs which contain a clickable table of contents for the headers on the page. One sits at the top of the page, and the other appears when you scroll past the one on the top. When you scroll past the top toc, a tab appears on the top of the page. When you mouse over this tab, a table of contents will appear. Clicking an item in the toc, or scrolling the page, will make the tab close again. The tab will be semi-transparent until it is moused over, and the toc appears. You can also click the tab to be taken to the top of the page.

disabling the toc
		turn off this script by adding a div with the id "toc-off" to a page.
		this script can be turned off for a category by adding a module with the "toc-off" div, and setting that module to only appear on that category.
		the script can be set to apply only to specific headers via the largestHeader and smallestHeader variables
		the script can be completely disabled by removing the headerLib entry in tiki-setup.php

This script does the following:
		determine if wiki page
		determine if page has the "toc-off"
		determine if more than one header on page
		insert toc HTML
		iterate over page and set Ids for header elements
			This is necessary because WYSIWYG fails to set correct Ids consistently.
		While setting header Ids, generate a HTML indented list of header anchors which point to their respective headers via header id
		set mouseover and onScroll events for two tocs

The following CSS should be applied to your theme's css file for correct behavior. You may need to adjust margin (where the toc that scrolls with you shows up) based on your theme:

	div#outerToc {
	        position:fixed;
	        top:0px;
	        margin-left:25%;
	        background:#E0E0E0;
	        display:none;
	        padding:10px;
	        border-radius:0px 0px 5px 5px;
	        z-index:5;
	}

*/

$(function () {
	//if a wiki page, and if there is no toc-off div
	if (document.getElementById("page-data") && !document.getElementById("toc-off") && document.location.href.indexOf("tiki-print.php") == -1) {
		//get headers
		headers = $("div#page-data").find(":header");

		//if there are more than one headers on the page
		if (headers.length > 1) {

			//**************Add the Toc Divs to the Page**************//

			//set target div IDs. these divs will be populated with an autoToc
			//innerToc and toc-static are required. Additional divs may be specified.
			tocDivs = ["innerToc", "toc-static"];

			//string to add html for toc divs
			tocString = "
  Table of Contents, or Click for Page Top

";

			//create the div to hold the tocs, and populate its inner HTML with the tocString
			tocContainer = document.createElement("div");
			tocContainer.innerHTML = tocString;

			//get pageData div, as we want to add toc before that
			page = document.getElementById("page-data");

			//add the tocContainer as first child of page-data div
			firstChild = page.firstChild;
			page.insertBefore(tocContainer, firstChild);

			//Configure starting header and ending header
			largestHeader = 1;
			smallestHeader = 6;

			//**************Iterate over headers and create autoToc HTML List**************//

			//start from indentation level 0, with header one as base
			previousHeaderLevel = 1;

			//create object to store processed IDs.
			var processedId = new Object();

			//function to process header Id generation. If an ID which has been processed is generated again and passed in again, the id name will be incremented to id_[1*]
			function processId(id) {
				if (id in processedId) {
					//if processed before
					//iterate count for header with this ane
					processedId[id] += 1;
					//set the new id to id plus count for header
					newId = id + "_" + processedId[id];
				} else {
					//if not processed before
					//add to "dictionary' with count of 0
					processedId[id] = 0;
					//return id passed in
					newId = id;
				}
				return newId;
			}

			//open HTML list and initialize string which will store the HTML list
			var str = '
';

			//Iterate over the headers
			for (i = 0; i < headers.length; i++) {

				//get header level for header to see if this header should be processed or not
				headerLevel = parseInt(headers[i].tagName[1]);

				//If the header level in range of acceptable headers, begin processing it
				if (headerLevel >= largestHeader && headerLevel <= smallestHeader) {

					//store browser location to append the #[1*/header text] to
					browserLocation = document.location.href;

					//Make the base URL for the link as everything up to page name plus hash. multistructure pages might have issues with this, but we are avoiding multistruction pages to avoid multicategory pages, so should be fine. For links to headers (via ids) to work, you need to have a clean url like cewiki/pagename#id, with nothing after the id string: https://cewiki-dev.colorado.edu/es-Searching+for+a+Student+Record#Overview will work, but https://cewiki-dev.colorado.edu/es-Searching+for+a+Student+Record#Overview&structure=es-Enrollment+Services will not.
					pointTo = browserLocation.substring(0, browserLocation.indexOf('&')) + "#";

					//current header
					header = headers[i]

					//grab the whole header element to show as the anchor text
					aText = header.innerHTML.trim(); //trim incase inner html is text (if <hx>text</hx>)

					//if the header is complicated (composed of multiple HTML Elements)
					if (header.children.length > 0) {
						//set the id to the the inner text of the header, with underscores instead of "<", ">", and spaces (" "). Increment Id checks if the ID has been assigned yet, and if so, increments the Id with a number at the end of the id name
						id = processId($(aText).text().trim().replace(/ /g, "_").replace(/</g, "_").replace(/>/g, "_"))

						//if the header is simple
					} else {
						//the inner html of the header is just text, so use anchor text for the id directly
						id = processId(aText.replace(/ /g, "_").replace(/</g, "_").replace(/>/g, "_")) //replace all spaces with underscore, and special chars
					}

					//construct the URL from the base URL with a # and the ID for the Div
					url = pointTo + id; //url is baseurl#divId

					//set the element's id to the constructed ID
					//Need to do this because WYSIWYG does not set IDs on divs correctly. May be able to set flag to check if tiki editor, and mimic how it creates IDs, avoiding this step.
					header.setAttribute("id", id);

					//create the HTML anchor item with the text from the header and pointing to baseurl#divId
					itm = '
' + aText + '
';

					//*****use the information gathered to write the string of the HTML for the list of anchors*****//

					//The following code determines how indented the previous header was, and closes or opens sublists to match that indentation level.
					//Example:
					//h1
					//h2
					//h3
					//h1
					//Above, if it had just written the h3, and it went to write the h1, its initial indentLevel would be 1, while previous would be 3, so it would know it needs to close sublists equal to the difference beteen its indentation level and that of h3. So, it would need to close two levels from h3 to get to h1, and then write the item.
					//To do this, the code below either applies ++ or -- on the indentLevel variable while closing or opening sublists until the current indentLevel matches the previousHeaderLevel.

					indentLevel = headerLevel;

					//if header is a sub header (nested on a child level of the previous header), meaning its indent level is greater than that of the previousHeaderLevel
					if (indentLevel > previousHeaderLevel) {
						//open a new sublist for each level of difference

						//this is an alternative way to think about this
						//~ openCount = indentLevel - previousHeaderLevel
						//~ for i in range(openCount):
						//~ str +="
"
						//~ str+= item

						while (indentLevel > previousHeaderLevel) {
							//open sublist
							str += "
";
							//track header level vs previous header to tell when to stop
							indentLevel -= 1;
						}
						//when header levels match, write item
						str += itm;
					}
					//else, if header is higher up (parent level of list, but wont be a parent of the page because below)
					else if (indentLevel < previousHeaderLevel) {
						//close sublists for each level of difference
						while (indentLevel < previousHeaderLevel) {
							//close sublist
							str += "
";
							//track header level vs previous header to tell when to stop
							indentLevel += 1;
						}
						//when header levels match, write item
						str += itm;

						//elif header levels are same
					} else if (indentLevel == previousHeaderLevel) {
						//write item
						str += itm;
					}
				}
				//set current header level to previous header level for next iteration
				previousHeaderLevel = headerLevel;
			}

			//close list
			str += '
';

			//set target div's inner html to the list
			for (i = 0; i < tocDivs.length; i++) {
				document.getElementById(tocDivs[i]).innerHTML = str;
			}

			//**************Add special mouse over and scroll behavior to toc**************//
			//make it so the non-static toc shows up on top of the page when you scroll past the first static top which sits at the top of the page.
			//make it so that when you mouse over the non-static toc's outer container, the inner container shows up
			//make it so that when you scroll, the innner-toc, which holds the toc, hides, and you just see the outerToc container.

			//set onmouseover for outerToc
			document.getElementById("outerToc").onmouseover = function () {
				//closure, sets "scope/context" for function setVis on mouse over
				var inner = document.getElementById('innerToc');
				var outer = document.getElementById('outerToc');

				function setVis(inner, outer) {
					//make the outerToc container more opaque
					outer.style.opacity = 1;
					//show the inner toc div, displaying the toc
					inner.style.display = 'block';
				}

				return setVis(inner, outer);
			}

			//set the scroll functionality
			//determine where the "mobile toc" should start showing up
			static_toc = $('#outerToc-static');
			start = $(static_toc).offset().top + $(static_toc).height();

			//assign inner and outer vars for window scroll event
			var outer = $('#outerToc'); //$(div);
			var inner = $('#innerToc');

			//set on scroll event to do: on scroll, hide the floating toc if you would overlap with the toc on the top of the page, otherwise hide the inner toc
			$.event.add(window, "scroll", function () {
				//position
				var p = $(window).scrollTop();

				//if current position is below the other toc and start of the page
				if (p > start) {
					//set outertoc position to fixed at top of screen
					outer.css('display', 'block');
					//hide inner toc
					inner.css('display', 'none');
					//make outerToc slightly transparent
					var elem = document.getElementById('outerToc');
					if (elem) {
						elem.style.opacity = 0.5;
					}
				} else {
					//if current position overlaps with the static toc at top of page, hide non-static toc div
					outer.css('display', 'none');
				}
			});
		}
	}
});<|endoftext|>


<commit_before>/**
 * Created by devebiz on 11/6/15.
 */
angular
    .module("app", [])
    .controller("myController", function ($scope) {
        $scope.liste = ["Eier", "Butter", "Brot"];
    });<commit_msg>Finalized MVC Pattern<commit_after>/**
 * Created by devebiz on 11/6/15.
 */
angular
    .module("app", [])
    .controller("myController", function ($scope, datenQuelle) {
        $scope.liste = datenQuelle.getListe();
    })
    .factory("datenQuelle", function () {
        var liste = ["Eier", "Butter", "Brot"];
        return Object.create({
            getListe: function () {
                return liste.slice();
            }
        });
    });<|endoftext|>