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

    var EditSite = function (existingSiteUrls, siteId) {
        // While this is false, editing the title can generate the address
        this.addressFixed = false;
        this.existingUrls = [];
        this.isValidUrl = true;
        this.invalidUrlDeleted = false;
        this.siteId = parseInt(siteId);

        this.init(existingSiteUrls);
    };

    EditSite.prototype.generateSlug = function(title) {
        var length_limit = 40;

        var rus = {'а':'a', 'б':'b', 'в':'v', 'г':'g', 'д':'d', 'е':'e', 'ё':'jo', 'ж':'zh', 'з':'z', 'и':'i', 'й':'j', 'к':'k', 'л':'l', 'м':'m', 'н':'n', 'о':'o', 'п':'p', 'р':'r', 'с':'s', 'т':'t', 'у':'u', 'ф':'f', 'х':'h', 'ц':'c', 'ч':'ch', 'ш':'sh', 'щ':'sch', 'ъ':'', 'ы':'y', 'ь':'', 'э':'e', 'ю':'ju', 'я':'ja'};
        var pattern = /[^a-zA-Z0-9_]/g;

        title = title.toLowerCase();
        var slug  = '';
        for (var i = 0; i < title.length; i++)
        {
            var charact = title.substring(i, i + 1);
            if (rus[charact])
                slug += rus[charact];
            else
                slug += charact;
        }

        if (slug.match(pattern))
            slug = slug.replace(pattern, "_");

        if (slug.length > length_limit)
            slug = slug.substring(0, length_limit);

        return slug;
    };

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

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

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

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

        self.existingUrls = existing_site_urls;

        if (self.siteId === 0)
        {
            $('#site_title').on('keyup', function()
            {
                if (!self.addressFixed)
                {
                    var slug = self.generateSlug($(this).val());
                    $('#site_url').val(slug);
                    self.checkUrl(slug);
                }
            });
        }

        $('#site_url').on('keyup', function()
        {
            self.addressFixed = true;
            self.checkUrl($(this).val());
        });
    };

    return EditSite;
});
