'use strict';
(function ($) {
    $.field_ratingstar = function (element, options) {
        var defaults = {
            input_name:''
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element),
            element = element;

        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('#stars li').on('mouseover', function(){
                var onStar = parseInt($(this).data('value'), 10);
                $(this).parent().children('li.star').each(function(e){
                    if (e < onStar) {
                        $(this).addClass('hover');
                    }
                    else {
                        $(this).removeClass('hover');
                    }
                });

            }).on('mouseout', function(){
                $(this).parent().children('li.star').each(function(e){
                    $(this).removeClass('hover');
                });
            });
            $element.find('#stars li').on('click', function(){
                var onStar = parseInt($(this).data('value'), 10);
                var stars = $(this).parent().children('li.star');

                for (let i = 0; i < stars.length; i++) {
                    $(stars[i]).removeClass('selected');
                    $(stars[i]).find('i').removeClass('fas');
                    $(stars[i]).find('i').addClass('far');
                }

                for (let i = 0; i < onStar; i++) {
                    $(stars[i]).addClass('selected');
                    $(stars[i]).find('i').removeClass('far');
                    $(stars[i]).find('i').addClass('fas');
                }

                var ratingValue = parseInt($('#stars li.selected').last().data('value'), 10);
                $element.find(`input[name="${plugin.settings.input_name}"]`).val(ratingValue);

            });
        };
        plugin.example_function = function () {
        };
        plugin.init();
    }

    $.fn.field_ratingstar = function (options) {

        return this.each(function () {

            if (undefined == $(this).data('field_ratingstar')) {
                var plugin = new $.field_ratingstar(this, options);
                $(this).data('field_ratingstar', plugin);
            }
        });
    }
})(jQuery);