jQuery(function($) {
    $(document).ready(function() {
        $('.color_parameter_block').each(function() {
            var $block = $(this);

            if ($('.colorvalue', $block).val().substr(0, 1) === "#") {
                $('.manualcolor', $block).val($('.colorvalue', $block).val());
                $('.colortype', $block).val("manual");
            } else {
                $('.plugincolor', $block).val($('.colorvalue', $block).val());
                $('.colortype', $block).val("plugin");
            }

            $('.colortype', $block).change(function() {
                var $el = $(this);

                $('.plugincolor', $block).hide();
                $('.manualcolor', $block).parents(".wp-picker-container").hide();

                if ($el.val() === 'plugin') {
                    $('.plugincolor', $block).show();
                } else {
                    $('.manualcolor', $block).parents(".wp-picker-container").show();
                }
            });

            $('.plugincolor', $block).change(function() {
                $('.colorvalue', $block).val($(this).val());
            });


            $('.manualcolor', $block).wpColorPicker({
                change: function() {                    
                    $('.colorvalue', $block).val($('.manualcolor', $block).val())
                }
            });

            $('.plugincolor', $block).hide();
            $('.manualcolor', $block).parents(".wp-picker-container").hide();

            if ($('.colorvalue', $block).val().substr(0, 1) === "#") {
                $('.manualcolor', $block).parents(".wp-picker-container").show();
            } else {
                $('.plugincolor', $block).show();
            }
        });

        $('.wpb_save_edit_form').click(function() {
            $('.color_parameter_block').each(function() {
                var $block = $(this);
                if ($('.colortype', $block).val() === 'manual') {
                    $('.colorvalue', $block).val($('.manualcolor', $block).val());
                }
            });
        });
    });
});