var ComitiumUtils = {
    generateGUID : function() {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
    },
    getURLParameter: function(paramName) {
        var searchString = window.location.search.substring(1),
            i, val, params = searchString.split("&");

        for (i = 0; i < params.length; i++) {
            val = params[i].split("=");
            if (val[0] == paramName) {
                return unescape(val[1]);
            }
        }
        return null;
    },
    addURLParameter: function(inputUrl, parameterName, parameterValue) {
        var url = inputUrl ? inputUrl : window.href;
        var sign = "?";

        if (/.+\?.+/.test(url)) {
            sign = '&';
        }

        return url + sign +parameterName+'='+parameterValue;
    },
    cutText: function(str, maxChars, append, onlyFullWords) {

        if (!maxChars || !str) {
            return str ? str : "";
        }

        append = append || '...';

        maxChars = onlyFullWords ? maxChars + 1 : maxChars;

        str = $.trim(str);

        if(str.length <= maxChars){
            return str;
        }

        str = str.substr(0, maxChars - append.length);

        str = onlyFullWords ? str.substr(0, str.lastIndexOf(' ')) : $.trim(str);

        return $.trim(str + append);
    },
    stripTags: function (text){
        return text.replace(/(<([^>]+)>)/ig,"");
    },
    htmlEncode: function(text) {
        return $('<div />').html(text).text();
    },
    populateValueToElements: function(value, elements) {
        $.each(elements, function(){
            $(this).val(value);
        });
    },
    getElementData: function(element) {
        return element.val();
    },
    setElementData: function(element, data) {
        element.val(data);
    },
    getDefaultDescriptionElementFromDynamicFields: function() {
        var descriptionOrigin = null;

        if ($('[data-semantical="subtitle"]').length) {
            descriptionOrigin = $('[data-semantical="subtitle"]');
        } else if ($('[data-semantical="body"]').length) {
            descriptionOrigin = $('[data-semantical="body"]');
        }

        return descriptionOrigin;
    },
    validateEmail: function(email) {
        return !!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email);
    },
    showSpinner: function() {
        $('.cs-module-spinner').show();
    },
    hideSpinner: function() {
        $('.cs-module-spinner').hide();
    },
    makeSlug: function(text, callBack) {
        $.ajax({
            url: Routing.generate('cs_core_make_slug'),
            method: 'GET',
            data: { text: text }
        })
        .done(function(slug) {
            if (typeof callBack === "function" ) {
                callBack.call(this, slug);
            }

            return slug;
        })
        .fail(function() {
            return text;
        });
    },
    tooltip: function(options, selector) {
        var defaultOptions = options||{};
        var elementSelector = selector||'[data-toggle="tooltip"]';
        $(elementSelector).tooltip(defaultOptions);
    },
    displaySlugMessage: function (element) {
        if (element.data('show.slug_message') == true) {
            return;
        }

        if (element.data('initValue') == '' || element.val() == '') {
            element.data('initValue', element.val());
            return;
        }

        var sluggableElement = element
            .parents('form')
            .find($('input[data-slugable]'));

        if (!$(sluggableElement.data('slugable')).val()) {
            return false;
        }

        var message = Translator.trans('cs_common_base.form.slug_message');
        var html = '\
            <div class="update-slug" style="margin-top: 10px">\
                <div class="alert alert-block alert-warning fade in">\
                <button type="button" class="close" data-dismiss="alert"></button>\
                %s\
                </div>\
            </div>';

        var wrapper = $(html.replace('%s', message));

        var hasSpell = element.parents('[data-action="spell_text"]');

        if (hasSpell.length > 0) {
            element.parent().after(wrapper);
        } else {
            element.after(wrapper);
        }


        $('#update-slug', wrapper).on('click',function(e){
            e.preventDefault();

            if (element.val() == '') {
                return;
            }

            var url = sluggableElement.data('url');
            var data = {text: element.val()};

            ComitiumUtils.makeSlug(element.val(), function(slugResult){
                $(sluggableElement.data('slugable')).val(slugResult);
                wrapper.remove();
                element.data('show.slug_message', false);
            });
        });

        $('#cancel-slug', wrapper).on('click',function(e){
            e.preventDefault();
            wrapper.remove();
            element.data('show.slug_message', false);
        });

        element.data('show.slug_message', true);
        element.data('initValue', element.val());
    },
    /**
     * @deprecated in favor of displayMultiOptionToaster
     * @todo refactor views that uses auto-completion-helper to use multi option case
     */
    displayToasterMessage: function (element, message, callBack) {
        if (element.data('show.slug_message') === true) {
            return;
        }

        if (element.data('initValue') === '' || element.val() === '') {
            element.data('initValue', element.val());
            return;
        }

        var html = '\
            <div class="update-slug" style="margin-top: 10px">\
                <div class="alert alert-block alert-warning fade in">\
                <button type="button" class="close" data-dismiss="alert"></button>\
                %s\
                </div>\
            </div>';

        var wrapper = $(html.replace('%s', message));

        var hasSpell = element.parents('[data-action="spell_text"]');

        if (hasSpell.length > 0) {
            element.parent().after(wrapper);
        } else {
            element.after(wrapper);
        }

        $('#update-title', wrapper).on('click',function(e){
            e.preventDefault();

            if (typeof callBack == "function") {
                callBack.call(this);
            }

            element.data('show.slug_message', false);
            wrapper.remove();
        });

        $('#cancel-title', wrapper).on('click',function(e){
            e.preventDefault();
            wrapper.remove();
            element.data('show.slug_message', false);
        });

        element.data('show.slug_message', true);
        element.data('initValue', element.val());
    },
    displayMultiOptionToaster: function (element, message, infoMessage, callBacks) {
        if (element.data('show.slug_message') === true) {
            return;
        }

        if (element.data('initValue') === '' || element.val() === '') {
            element.data('initValue', element.val());
            return;
        }

        var html = '<div class="alert alert-block alert-warning fade in">\
            <button type="button" class="close" data-dismiss="alert"></button>';
            html = html.concat(message);
            for (var o = 0; o < callBacks.length; o++) {
                html = html.concat('<a href="#" class="btn btn-sm defaultBtn" id="'+ callBacks[o].id +'">'+ callBacks[o].message +'</a>');
            }
            html = html.concat(infoMessage);
            html = html.concat('</p></div>');

        var wrapper = $(html.replace('%s', message));

        var hasSpell = element.parents('[data-action="spell_text"]');

        if (hasSpell.length > 0) {
            element.parent().after(wrapper);
        } else {
            element.after(wrapper);
        }

        for (var i = 0; i < callBacks.length; i++) {
            $("#"+callBacks[i].id, wrapper).on('click', callBacks[i], function(e){
                var callBack = e.data;
                e.preventDefault();

                if (typeof callBack.callBack == "function") {
                    callBack.callBack.call(this);
                }

                element.data('show.slug_message', false);
                wrapper.remove();
            });
        }

        element.data('show.slug_message', true);
        element.data('initValue', element.val());
    }
};
