define (['jquery'], function($) {

    var EditPageProperties = function (existingPageUrls) {
        this.existingUrls = [];
        this.isValidUrl = true;
        this.invalidUrlDeleted = false;

        this.init(existingPageUrls);
    };

    EditPageProperties.prototype.checkUrl = function(url) {
        this.isValidUrl = true;

        // Pull out parallel paths
        var urls = [];
        for (var key in this.existingUrls)
        {
            if (this.existingUrls.hasOwnProperty(key))
            {
                urls.push({
                    url: this.existingUrls[key].url.split('/').pop(),
                    is_deleted: this.existingUrls[key].is_deleted
                })
            }
        }

        for (var i = 0; i < urls.length; i++)
        {
            if (urls[i].url === url) {
                this.isValidUrl = false;
                this.invalidUrlDeleted = urls[i].is_deleted;
            }
        }

        if (!this.isValidUrl)
        {
            $('#page_url').addClass('is-invalid');
            if (this.invalidUrlDeleted) {
                $('#url_in_use_deleted').removeClass('d-none');
            } else {
                $('#url_in_use').removeClass('d-none');
            }
            $('#edit_page_submit').prop('disabled', 'disabled');
        } else
        {
            $('#page_url').removeClass('is-invalid');
            $('#url_in_use, #url_in_use_deleted').addClass('d-none');
            $('#edit_page_submit').prop('disabled', '');
        }
    };

    EditPageProperties.prototype.init = function(existing_page_urls) {
        // jQuery redefines `this`...
        var self = this;

        self.existingUrls = existing_page_urls;

        $('#page_url').on('keyup', function()
        {
            self.checkUrl($(this).val());
        });
    };

    return EditPageProperties;
});
