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/SBogers10/edwingovers.komma.pro/resources/assets/js/kms/kms.js
'use strict';
var attributes = {};

var app = angular.module('kms', [
    'ui.bootstrap',
    'ngSanitize',
    'kms.dynamic-attribute',
    'fileUpload'

    // 'ui.select',
    // 'ui.date',
    // 'ui.tree',
    // 'ui.sortable',

    // 'ui.utils.masks',

]);

app.controller('KmsEntities',[ '$scope', '$element',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(),
            status: $('.entities-item-status', 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('KmsEntity',[ '$scope', '$element',function ($scope, $element) {
    // console.log("attaching save to scope");
    $scope.save = function () {
        var button = document.querySelector('input[value="submit-cloaked"]');
        // console.log(button);
        button.click();
    };
}]);

app.controller('SortableTree',['$scope', '$http', '$attrs' ,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.siteslug + '/' + $attrs.slug,
                data: {"tree": angular.toJson($scope.data)}
            }).then(function (response) {
            });
        }
    };

    $scope.openLink = function (id) {
        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();
    };

    // console.log('/kms/api/' + $attrs.siteslug + '/' + $attrs.slug);
    $http.get('/kms/api/' + $attrs.siteslug + '/' + $attrs.slug)
        .then(function (response) {
            // console.log("Kms.js SortableTree controller got data from '"+'/kms/api/' + $attrs.siteslug + '/' + $attrs.slug+"':");
            // console.log(angular.toJson(response.data));
            $scope.data = response.data[0]['children'];
        });
}]);

app.controller('KmsAttributes',['$scope', function ($scope) {
    $scope.attributes = attributes;

    // console.log("$scope.attributes (via KmsAttributes)");
    // console.log($scope.attributes);

    // $scope.createModelString = function (modelKey, $itemKey) {
    //
    //
    //     //Check if the modelKey is an array structure (field_name[x])
    //     var match = modelKey.match(/(.*)\[(.*)]/)
    //
    //     //There is no match, so a basic key
    //     if (match == null) {
    //         //SEt the modelKey as modelString
    //         $scope.modelString = modelKey
    //         //ItemKy is null
    //         $scope.itemKey = null;
    //         //return and exit
    //         return $scope.modelString
    //     }
    //
    //     //Set the match[2] as the itemKey
    //     var itemCounter = match[2];
    //
    //     //If the itemKey is not undefined and itemkey is the string itemKey
    //     if (typeof($itemKey) != "undefined" && match[2] == 'itemKey') {
    //         //Set the $itemKey to the scope itemKey
    //         itemCounter = $itemKey
    //     }
    //     //Glue the parts together
    //     var modelString = match[1] + '_' + itemCounter
    //
    //     //Set to the global modelString
    //     $scope.modelString = modelString;
    //     $scope.itemCounter = itemCounter;
    //
    //     //Return the string
    //     return modelString
    // }

    /**
     * Wrapper for Json.parse()
     * So i can parse Json in blade
     * @param value
     */
    $scope.parse = function (value) {
        //If there is no value return;
        if (!value) {
            console.log("Parse without a value");
            return;
        }
        //If it is already an object, return the value
        if (typeof(value) == 'object') {
            console.log("Parse value: "+value);
            return value;
        }

        //Parse the string to a Json object
        console.log("Parse string to Json: "+JSON.parse(value));
        return JSON.parse(value);
    };

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

        // remove accents, swap ñ for n, etc
        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('KmsAttributeTextFieldController',['$scope', '$element' ,function ($scope, $element) {

    $scope.attributes = attributes;
}]);

app.controller('KmsAttributePasswordController',['$scope', '$element' ,function ($scope, $element) {
    $scope.attributes = attributes;

    //Set enabler true (show enable bottom)
    $scope.enabler = true
    //Change the password field to a hidden field
    $('.passwordField', $element).attr('type', 'hidden')

    //Method called when clikced on the enable button
    $scope.enablePasswordField = function () {
        //Change the type of the password field to password
        $('.passwordField', $element).attr('type', 'password')
        //Disable the enable buttom
        $scope.enabler = false
    }
}]);


app.controller('KmsAttributeDateController',['$scope', '$element', function ($scope, $element) {
    $scope.attributes = attributes;

    $('input[ui-date]', $element).datepicker({
        changeYear: true,
        changeMonth: true,
        firstDay: 1,
        dateFormat: 'dd-mm-yy',
    });

}]);

app.controller('KmsAttributeCurrencyFieldController',['$scope', '$element','$locale', function ($scope, $element, $locale) {
    $scope.attributes = attributes;


    $scope.initCurrencyField = function (dec_value, currency) {

        if (typeof(currency) !== 'undefined') {
            //Set currencySymbol
            $locale.NUMBER_FORMATS.CURRENCY_SYM = currency;
        }

        //Set the value an de dec_value
        attributes[$scope.modelString] = {"value": dec_value / 100, "dec_value": dec_value}

        $scope.$watch('attributes.' + $scope.modelString + '.value', function (newValue, oldValue) {
            if (newValue === oldValue) return;

            attributes[$scope.modelString].dec_value = newValue * 100

        });
    }


}]);

app.controller('KmsAttributePercentageFieldController',['$scope', '$element','$timeout', function ($scope, $element, $timeout) {
    $scope.attributes = attributes;

}]);

app.controller('KmsAttributeTextFieldCurrencyController',['$scope', '$element','$timeout', 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('KmsAttributeMultiSelectController',['$scope', '$element', function ($scope, $element) {

    $scope.attributes = attributes;
    $scope.selectData = [];

    /**
     * Initialize the choices for ui-select
     *
     * @param choices | string
     * @returns {*}
     */
    $scope.initChoices = function (choices) {
        //If there are no choices;
        if (!choices) return;

        //If it is not already an object, make one from json
        if (typeof(choices) != 'object') choices = JSON.parse(choices)

        //Set the choices to the selectData
        $scope.selectData = choices
        return choices
    };

    $scope.setValue = function (values) {

        if (!values) return;
        // 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;
        return result;
    };


}]);

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

    //Get the slugField key
    var slugField = $('[data-kms-slug-field]', $element).attr('data-kms-slug-field');
    //Change [[itemCounter]] with the $scope.itemCounter (fieldGroup)
    slugField = slugField.replace('[[itemCounter]]', $scope.itemCounter);

    //Watch the slugField
    $scope.$watch('attributes.' + slugField, function (newValue, oldValue) {
        //When nothing changes, do nothing
        if (newValue === oldValue) return;
        //Set the string converted to Slug to the field
        attributes[$scope.modelString] = $scope.convertToSlug(attributes[slugField]);
    });

}]);


app.controller('KmsAttributeFieldGroupController', ['$scope', '$element',function ($scope, $element) {
    $scope.number = 0;
    $scope.itemKey = 1;
    $scope.maxFieldGroups = null;

    $scope.getNumber = function () {
        return new Array($scope.number);
    }

    $scope.addRow = function () {

        if ($scope.itemKey >= $scope.maxFieldGroups) return
        //Add one to the itemKey
        $scope.itemKey++;
        //Addd one to the numbers
        $scope.number++;

    }
    /**
     * Initialize the given values
     * @param itemKey | Amount (-1) of  items fieldGroups
     * @param maxFieldGroups | max fieldgroups
     */
    $scope.init = function (itemKey, maxFieldGroups) {

        //Items in the fieldGroup
        $scope.itemKey = itemKey
        //Max items in fieldGroup
        $scope.maxFieldGroups = maxFieldGroups
        //If it is a new, add a row
        if (itemKey == 0) $scope.addRow();
    }
}]);

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

    $scope.attributes = attributes;

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

    //Get the name of the slugField
    var slugField = $('[data-kms-slug-field]', $element).attr('data-kms-slug-field');
    //Change [[itemCounter]] with the $scope.itemCounter (fieldGroup)
    slugField = slugField.replace('[[itemCounter]]', $scope.itemCounter)
    //Get the name of the parentField
    var parentField = $('[data-kms-parent-field]', $element).attr('data-kms-parent-field');

    //Set the languageId
    var languageId = $('[data-kms-language-id]', $element).attr('data-kms-language-id');
    //Set the structure
    var structure = $('[data-kms-structure]', $element).attr('data-kms-structure');


    /**
     * This function generates the correct Route
     * when a watched field is changed
     *
     * @param newValue
     * @param oldValue
     */
    var parseStructure = function (newValue, oldValue) {
        //If the value is the same, stop and return
        if (newValue === oldValue) return;

        //Create an empty parentSlug string
        var parentSlug = '';

        // todo: make this work
        //Check if the parentField exist in then attributes
        if (attributes[parentField]) {
            //Check if the parentField has an selected.routes object
            if (!attributes[parentField].selected.routes) {
                //If not trow an error
                console.error('Routes are not set in the ' + parentField + 'field')
            }
            //Set the routes for the current language to parentSlug
            parentSlug = attributes[parentField].selected.routes[languageId];
        }

        //Create newRoute
        var newRoute = '';

        //Replace {{parentSlugs}} with the parentSlug
        newRoute = structure.replace('{{parentSlugs}}', parentSlug);
        //Replace {{slug}} with the Slug
        newRoute = newRoute.replace('{{slug}}', $scope.convertToSlug(newValue));

        //Set the new route to the attribute of the current $scope.modelString
        attributes[$scope.modelString] = newRoute

    };

    //Set a watch on the slugField, and execute the parseStructure method on a change
    $scope.$watch('attributes.' + slugField, parseStructure);
    //If there is an parentField
    if (attributes[parentField]) {
        //Set a watch on the parentField, and execute the parseStructure method on a change
        $scope.$watch('attributes.' + parentField + '.selected', parseStructure);

    }


}]);


app.controller('KmsAttributeSorterController',['$scope', '$element', function ($scope, $element) {
    $scope.attributes = attributes;

}]);

app.filter("multiWordFilter", ['$filter',  function ($filter) {
    console.log('hoi');
    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;
    }
}]);

app.filter('valuesToArrayFilter', function () {
    return function (input) {

        if (!input) return;

        var output = input.map(function (a) {
            return a.value;
        });

        return output


    }
});


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


var IsJsonString = function (str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
};


$(function(){

    var activeListItem = $('#sidebar .navigation li.active');
    var activeListItemParents = activeListItem.parents();
    var activeListItemParentsLength = activeListItemParents.length;

    for(var i = 0; i <= activeListItemParentsLength; i++){
        var node = activeListItemParents[i];
        if(node && node.tagName == 'LI' && node.classList.contains('has-sub-items')){
            node.classList.add('active');
        }
    }

    var siteListItems = document.querySelectorAll('#sidebar .navigation .has-sub-items');
    var siteListItemsLength = siteListItems.length;
    for(var i = 0; i < siteListItemsLength; i++){
        var siteListItem = siteListItems[i].querySelector('span');

        siteListItem.addEventListener('click', function () {
            this.parentNode.classList.toggle('active');
        });
    }

});