"use strict";
(function ($) {
    $.field_roomtypewithprice = function (element, options) {
        var defaults = {
            values:[],
            item_room_type:'',
            max_room_type:1,
            price_adult_field_name:'',
            price_child_field_name:'',
        }
        var plugin = this;
        plugin.settings = {}
        var $element = $(element), 
            element = element;
        plugin.init = function () {
            plugin.settings = $.extend({}, defaults, options);
            $element.find('.list-room-type').select2();
            $element.find('.price-adult').autoNumeric('init', {aSign: "$ "});
            $element.find('.price-child').autoNumeric('init', {aSign: "$ "});

            $element.find('.btn-add-roomtype').on('click', function(e) {
                plugin.set_task_when_click();
            });

            $element.find('.wrapper-item-roomtype').each(function (index, item) {
                plugin.init_event_roomtype_item($(item))
            });

        };
        plugin.init_event_roomtype_item = function ($item_roomtype) {
            $item_roomtype.find('.btn-delete-roomtype').click(function (e) {
                if ($element.find('.wrapper-item-roomtype').length > 1) {
                    $item_roomtype.remove();
                }
            })
        };
        plugin.set_task_when_click = function () {
            let max_room_type = plugin.settings.max_room_type;
            max_room_type = parseInt(max_room_type);
            let total_current_roomtype = $element.find('.wrapper-item-roomtype').length;
            if (total_current_roomtype >= max_room_type) {
                $.alert({
                    title: 'Error',
                    content: `you cannot add more than ${max_room_type} `
                });
                return;
            }
            var $item_roomtype = $(plugin.settings.item_room_type);
            $item_roomtype.appendTo($element);
            $item_roomtype.find('.list-room-type').select2();
            $item_roomtype.find('.price-adult').autoNumeric('init', {aSign: "$ "});
            $item_roomtype.find('.price-child').autoNumeric('init', {aSign: "$ "});
            $item_roomtype.find('.btn-add-roomtype').on('click',function (e) {
                plugin.set_task_when_click();
            });
            plugin.init_event_roomtype_item($item_roomtype);
        }
        plugin.example= function () {
        };
        plugin.init();
    }
    
    $.fn.field_roomtypewithprice = function (options) {
        
        return this.each(function () {
            
            if (undefined == $(this).data('field_roomtypewithprice')) {
                var plugin = new $.field_roomtypewithprice(this, options);
                $(this).data('field_roomtypewithprice', plugin);
            }
        });
    }
})(jQuery);