HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/PDeckers/opelkapitan.nl/wwwroot/packages/komma/kms/js/kms.js
'use strict';

var attributes = {};

var app = angular.module('kms', [
    'ui.bootstrap',
    'ui.select',
    'ui.date',
    'ui.tree',
    'ui.sortable',
    'ngSanitize',
    'ngFileUpload',
    'fileUpload',
    'kms.dynamic-attribute'
]);

//Tabs
app.run(function ($rootScope) {

    var tabSlug = null;

    var openTab = function (tabSlug) {

        var originalTabSlug = tabSlug;

        if (!tabSlug) return;

        $('#tab-slug').val(tabSlug);

        var tabSlugs = tabSlug.split('/');
        if (tabSlugs.length > 1) {
            var subTabSlug = tabSlugs.pop();
            tabSlug = tabSlugs.join('/');
        }

        //$('.tab-content').css('display','none');
        $('.sub-tab-content').css('display', 'none');

        //$('.entity-tabs > .nav-tabs > li').removeClass('active');
        $('.sub-tabs > .nav-tabs > li').removeClass('active');

        $('#tab-content-' + tabSlug).css('display', 'block');
        $('.entity-tabs > .nav-tabs > li a[href="#' + tabSlug + '"]').parent().addClass('active');

        if (subTabSlug) {
            $('#tab-content-' + tabSlug + ' #sub-tab-content-' + subTabSlug).css('display', 'block');
            $('#tab-content-' + tabSlug + ' .sub-tabs > .nav-tabs > li a[href="#' + originalTabSlug + '"]').parent().addClass('active');
            $('.entity-tabs > .nav-tabs > li a[href="#' + tabSlug + '"]').parent().addClass('active');
        } else {
            $('.tab-content').css('display', 'none');
            $('#tab-content-' + tabSlug).css('display', 'block');
            $('#tab-content-' + tabSlug + ' .sub-tab-content:first').css('display', 'block');
            $('#tab-content-' + tabSlug + ' .sub-tabs > .nav-tabs > li:first').addClass('active');
            $('.entity-tabs > .nav-tabs > li').removeClass('active');
            $('.entity-tabs > .nav-tabs > li a[href="#' + tabSlug + '"]').parent().addClass('active');
        }
    };

    $(window).on('hashchange load', function (event) {
        tabSlug = window.location.hash.substring(1);
        if (tabSlug) openTab(tabSlug);
        openTab($('#tab-slug').val());
    });

    $rootScope.$on('$locationChangeStart', function (event, next, current) {
        var splited = next.split('#');
        tabSlug = splited.length > 1 ? splited.pop().substring(1) : '';
        if (tabSlug) openTab(tabSlug);
        openTab($('#tab-slug').val());
    });

});

app.controller('KmsEntities', function ($scope, $element) {

    $scope.entities = [];
    $scope.paginatedEntities = [];

    $scope.isSorting = false;

    $scope.isSearching = function () {
        return $scope.searchEntitiesText.text.length > 1;
    };

    $scope.currentPage = 1;
    $scope.numPerPage = 5;
    $scope.maxSize = 5;

    var entityList = $('.entities-list-items .entities-list-item', $element);
    for (var i = 0; i < entityList.length; i++) {
        var dataElement = entityList[i];
        var dataObject = {
            thumbHtml: $('.entities-item-pre', dataElement).html(),
            text: $('.entities-item-text', dataElement).html(),
            link: $('a', dataElement).first().attr('href'),
            active: $(dataElement).hasClass('active')
        };
        $scope.entities.push(dataObject);
    }

    $scope.activateSorting = function () {
        $scope.isSorting = true;
    };

    $scope.deactivateSorting = function () {
        $scope.isSorting = false;
    };

    $scope.$watch("currentPage + numPerPage", function () {
        var begin = (($scope.currentPage - 1) * $scope.numPerPage)
            , end = begin + $scope.numPerPage;

        $scope.paginatedEntities = $scope.entities.slice(begin, end);
    });

});

app.controller('SortableTree', function ($scope, $http, $attrs) {

    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

    $scope.data = [];

    $scope.treeOptions = {
        dropped: function (event) {
            $http({
                method: 'POST',
                url: '/kms/api/' + $attrs.slug,
                data: {"tree": angular.toJson($scope.data)}
            }).then(function (response) {
            });
        }
    };

    $scope.openLink = function (id) {
        if (id >= 1) {
            if ($('#entity .ng-dirty, #entity .error').length > 0) {
                $.confirm({
                    'title': 'Not saved',
                    'message': 'There are changes that has not been saved yet, are you sure you want to leave this page?',
                    'buttons': {
                        'Yes': {
                            'class': 'btn btn-error-glow',
                            'action': function () {
                                window.location = $scope.url + '/' + id;
                            }
                        },
                        'No': {
                            'class': 'btn btn-brand-glow',
                            'action': function () {
                                return false;
                            }
                        }
                    }
                });
            }
            else {
                window.location = $scope.url + '/' + id;
            }
        }
    };

    $scope.toggle = function (scope) {
        scope.toggle();
    };

    var getRootNodesScope = function () {
        return angular.element(document.getElementById('tree-root').scope());
    };

    $scope.collapseAll = function () {
        var scope = getRootNodesScope();
        scope.collapseAll();
    };

    $scope.expandAll = function () {
        var scope = getRootNodesScope();
        scope.expandAll();
    };

    $http.get('/kms/api/' + $attrs.slug)
        .then(function (response) {
            $scope.data = response.data[0]['children'];
        });
});

app.controller('KmsAttributes', function ($scope) {

});

app.controller('KmsAttributeTextFieldController', function ($scope, $element) {
    $scope.attributes = attributes;
    var id = $('input', $element).attr('id');
    attributes[id] = $('input', $element).attr('value');
});

app.controller('KmsAttributeDateController', function ($scope, $element) {
    $scope.attributes = attributes;
    var id = $('input', $element).attr('id');
    attributes[id] = $('input', $element).attr('value');
    $scope.defaultDateOptions = {
        changeYear: true,
        changeMonth: true,
        firstDay: 1
    };
    $('input[ui-date]', $element).datepicker('setDate', attributes[id]);
});

app.controller('KmsAttributeCurrencyFieldController', function ($scope, $element, $timeout) {
    $scope.attributes = attributes;
    var id = $('input', $element).attr('id'); // get the id of the hidden field
    var currencyFieldId = id + '_currency';

    var parseCurrencyStringToCents = function (currencyString) {
        var val = currencyString.toString();
        val = val.replace(/[.]/g, '');
        val = val.replace(/[,]/g, '.');
        val = val.replace(/[^0-9\.]+/g, '');
        if (val != '') val = val * 100;
        return val;
    };

    $scope.$watch('attributes.' + currencyFieldId, function (newValue, oldValue) {
        if (newValue !== oldValue) {
            $scope.attributes[id] = parseCurrencyStringToCents(newValue);
        }
    });
    $scope.attributes[id] = $('input', $element).attr('value'); // get the value of the hidden field
});

app.controller('KmsAttributePercentageFieldController', function ($scope, $element, $timeout) {
    $scope.attributes = attributes;
    var id = $('input', $element).attr('id'); // get the id of the hidden field
    var currencyFieldId = id + '_percentage';

    var parseCurrencyStringToCents = function (currencyString) {
        var val = currencyString.toString();
        val = val.replace(/[%]/g, '');
        val = val.replace(/[,]/g, '.');
        return val;
    };

    $scope.$watch('attributes.' + currencyFieldId, function (newValue, oldValue) {
        if (newValue !== oldValue) {
            $scope.attributes[id] = parseCurrencyStringToCents(newValue);
        }
    });

    $scope.attributes[id] = $('input', $element).attr('value'); // get the value of the hidden field
});

app.controller('KmsAttributeTextFieldCurrencyController', function ($scope, $element, $timeout) {

    $scope.attributes = attributes;
    var id = $('input', $element).attr('id'); // get the id of the hidden field

    var taxSelectFieldId = $('[data-kms-tax-field]', $element).attr('data-kms-tax-field');
    var taxFieldId = id + '_tax';
    var noTaxFieldId = id + '_no_tax';

    var parseCurrencyStringToCents = function (currencyString) {
        var val = currencyString.toString();
        val = val.replace(/[.]/g, '');
        val = val.replace(/[,]/g, '.');
        val = val.replace(/[^0-9\.]+/g, '');
        val = val * 100;
        return val;
    };

    var addTax = function (value) {
        if (attributes[taxSelectFieldId].selected) {
            var factor = 1 + (attributes[taxSelectFieldId].selected.fullValue.rate / 100);
            return value * factor;
        }
    };
    var subtractTax = function (value) {
        if (attributes[taxSelectFieldId].selected) {
            var factor = 1 + (attributes[taxSelectFieldId].selected.fullValue.rate / 100);
            return value / factor;
        }
    };

    $scope.$watch('attributes.' + taxFieldId, function (newValue, oldValue) {
        if (newValue !== oldValue) {
            $scope.attributes[id] = parseCurrencyStringToCents(newValue);
        }
    });

    $scope.$watch('attributes.' + noTaxFieldId, function (newValue, oldValue) {
        if (newValue !== oldValue) {
            $scope.attributes[id] = Math.round(addTax(parseCurrencyStringToCents(newValue)));
        }
    });

    var watcherMain = function (newValue, oldVal) {
        if ($.isNumeric($scope.attributes[id])) {
            var $taxField = $('#' + taxFieldId);
            var $noTaxField = $('#' + noTaxFieldId);
            if (!$taxField.is(':focus')) {
                $taxField.val($scope.attributes[id] / 100)
            }
            if (!$noTaxField.is(':focus')) {
                $noTaxField.val(Math.round(subtractTax($scope.attributes[id])) / 100)
            }
        }
    };

    // Clear fields on blur if no value
    $('#' + taxFieldId + ', #' + noTaxFieldId).blur(function (e) {
        if ($scope.attributes[id] == 0) {
            $('#' + taxFieldId + ', #' + noTaxFieldId).val(0);
        }
    });

    $scope.$watch('attributes.' + id, watcherMain);
    $scope.$watch('attributes.' + taxSelectFieldId + '.selected', watcherMain);
    $scope.attributes[id] = $('input', $element).attr('value'); // get the value of the hidden field
    $timeout(watcherMain, 500);
});

app.controller('KmsAttributeSelectController', function ($scope, $element) {

    $scope.attributes = attributes;

    var id = $('ui-select', $element).attr('id');
    var dataElements = $('.select-data [data-value]', $element);
    $scope.attributes[id] = {};
    $scope.selectData = [];

    for (var i = 0; i < dataElements.length; i++) {
        var dataElement = dataElements[i];
        var dataObject = {
            htmlContent: $(dataElement).html(),
            content: $(dataElement).attr('data-content'),
            fullValue: $.parseJSON($(dataElement).attr('data-full-value')),
            value: $(dataElement).attr('data-value')
        };
        $scope.selectData.push(dataObject);
    }

    $scope.initWithValue = function (value) {
        if (!value) return;
        var result = $.grep($scope.selectData, function (e) {
            return e.value == value;
        });
        $scope.attributes[id].selected = result[0];
    };

});

app.controller('KmsAttributeMultiSelectController', function ($scope, $element) {

    $scope.attributes = attributes;

    var id = $('ui-select', $element).attr('id');
    var dataElements = $('.select-data [data-value]', $element);
    $scope.attributes[id] = {};
    $scope.selectData = [];

    for (var i = 0; i < dataElements.length; i++) {
        var dataElement = dataElements[i];
        var dataObject = {
            htmlContent: $(dataElement).html(),
            content: $(dataElement).attr('data-content'),
            fullValue: $.parseJSON($(dataElement).attr('data-full-value')),
            value: $(dataElement).attr('data-value')
        };
        $scope.selectData.push(dataObject);
    }

    $scope.initWithValue = function (values) {
        // compare "values" array and "$scope.selectData" array
        var result = [];
        for (var i = 0; i < $scope.selectData.length; i++) {
            var valueInElement = false;
            for (var j = 0; j < values.length; j++) {
                if ($scope.selectData[i].value == values[j]) {
                    valueInElement = true;
                    break;
                }
            }
            if (valueInElement) result.push($scope.selectData[i]);
        }

        $scope.attributes[id] = angular.toJson(values);
        $scope.attributes[id + '_select'] = result;
    };

    $scope.$watch('attributes.' + id + '_select', function (newValue, oldValue) {
        // create an array with the "value" property of the selected elements
        if (newValue !== oldValue) {
            var elements = [];
            for (var i = 0; i < newValue.length; i++) {
                elements.push(newValue[i].value);
            }
            $scope.attributes[id] = angular.toJson(elements);
        }
    });

});

app.controller('KmsAttributeSlugController', function ($scope, $element) {

    $scope.attributes = attributes;

    var id = $('input.slug', $element).attr('id');
    attributes[id] = $('input.slug', $element).attr('value');
    var autoSlugField = $($element).attr('data-kms-auto-slug-field');
    attributes[autoSlugField] = $('#' + autoSlugField).val();

    $scope.$watch('attributes.' + autoSlugField, function (newValue, oldValue) {
        if (newValue !== oldValue) {
            attributes[id] = slugify(attributes[autoSlugField]);
        }
    });

    function slugify(str) {
        str = str.replace(/^\s+|\s+$/g, ''); // trim
        str = str.toLowerCase();

        // change special chars: ë > e
        var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
        var to = "aaaaaeeeeeiiiiooooouuuunc------";
        for (var i = 0, l = from.length; i < l; i++) {
            str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
        }

        str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
            .replace(/\s+/g, '-') // collapse whitespace and replace by -
            .replace(/-+/g, '-'); // collapse dashes
        return str;
    }

});

app.controller('KmsAttributeRouteController', function ($scope, $element) {

    $scope.attributes = attributes;

    var id = $('input', $element).attr('id');
    attributes[id] = $('input', $element).attr('value');

    var slugField = $('[data-kms-slug-field]', $element).attr('data-kms-slug-field');
    var parentField = $('[data-kms-parent-field]', $element).attr('data-kms-parent-field');
    var languageId = $('[data-kms-language-id]', $element).attr('data-kms-language-id');
    var structure = $('[data-kms-structure]', $element).attr('data-kms-structure');

    var parseStructure = function (newValue, oldValue) {
        if (newValue !== oldValue) {
            attributes[id] = structure;
            attributes[id] = attributes[id].replace('{{slug}}', attributes[slugField]);
            attributes[id] = attributes[id].replace('{{parentSlugs}}', attributes[parentField].selected.fullValue[languageId]);
        }
    };

    $scope.$watch('attributes.' + slugField, parseStructure);
    $scope.$watch('attributes.' + parentField + '.selected', parseStructure);
});

app.controller('KmsAttributeEditableRowsController', function ($scope, $element, $timeout) {

    $scope.attributes = attributes;

    var id = $('> input', $element).attr('id');

    // console.log($('> input', $element).attr('value'));

    if (!$('> input', $element).attr('value')) {
        $scope.attributes[id] = [];
    } else {
        $scope.attributes[id] = angular.fromJson($('> input', $element).attr('value'));
    }

    $scope.addNewRow = function (reference) {
        if ($scope['new_' + reference] == '') return;
        var item = {};
        item[reference] = $scope['new_' + reference];
        $scope.attributes[id].push(item);
        $scope['new_' + reference] = '';
        $scope.processMainValue();

        // Focus on the new created element
        $timeout(function () {
            $scope.$apply();
            $('#' + reference + '_' + ($scope.attributes[id].length - 1), $element).focus();
            $scope.processMainValue();
        }, 0);
    };

    $scope.deleteRow = function (index) {
        $scope.attributes[id].splice(index, 1);
        $scope.processMainValue();
    };

    // QnD: update the main form input manually.
    $scope.processMainValue = function () {
        $('#' + id, $element).val(angular.toJson($scope.attributes[id]));
    };

    $scope.processMainValue();

});

app.filter("multiWordFilter", function ($filter) {
    return function (inputArray, searchText) {
        var wordArray = searchText ? searchText.toLowerCase().split(/\s+/) : [];
        var wordCount = wordArray.length;
        for (var i = 0; i < wordCount; i++) {
            // Hack for filtering on text parameter: {text:wordArray[i]}
            inputArray = $filter('filter')(inputArray, {text: wordArray[i]});
        }
        return inputArray;
    }
});

/**
 * AngularJS default filter with the following expression:
 * "person in people | filter: {name: $select.search, age: $select.search}"
 * performs a AND between 'name: $select.search' and 'age: $select.search'.
 * We want to perform a OR.
 */
app.filter('propsFilter', function () {
    return function (items, props) {
        var out = [];

        if (angular.isArray(items)) {
            items.forEach(function (item) {
                var itemMatches = false;

                var keys = Object.keys(props);
                for (var i = 0; i < keys.length; i++) {
                    var prop = keys[i];
                    var text = props[prop].toLowerCase();
                    if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                        itemMatches = true;
                        break;
                    }
                }

                if (itemMatches) {
                    out.push(item);
                }
            });
        } else {
            // Let the output be the input untouched
            out = items;
        }
        return out;
    };
});