(function($){

    function makeid(length) {
       var result           = '';
       var characters       = 'abcdefghijklmnopqrstuvwxyz0123456789';
       var charactersLength = characters.length;
       for ( var i = 0; i < length; i++ ) {
          result += characters.charAt(Math.floor(Math.random() * charactersLength));
       }
       return result;
    }

    function generate_id() {
        $('.rad-make-id').on('click', function (e) {
            e.preventDefault();
            $(this).siblings('input[type="text"]').val(makeid(6));
        });
    }

    function sticky_topbar()
    {
        var latestKnownScrollPosition = 0,
            tick = false,
            $element = $('#rad-top-bar');

        var update_topbar_position  = function () {

            $element.css("top", latestKnownScrollPosition + 'px');

            tick = false;
        }


        update_topbar_position();

        var requestTick  = function () {
            if (tick == false) {
                window.requestAnimationFrame(update_topbar_position);
            }
            tick = true;
        }

        var onScroll  = function () {
            latestKnownScrollPosition = $(window).scrollTop();
            requestTick();
        }

        $(window).on('scroll', onScroll);
    }
        

    function init_font_collections () {
        var $add_typeface = $('.rad-typeface-add'),
            $font_source = $('select[name="font-source"]'),
            $google_section = $('.google-section'),
            $custom_section = $('.custom-section'),
            $adobe_section = $('.adobe-section'),
            $add_button = $('.add-button'),
            rad_typkitid = $('#field-typekit-id').val();

        $add_typeface.find('.rad-add').on('click', function () {
            $add_typeface.addClass('show-options');
        });

        $add_typeface.find('.cancel-button').on('click', function () {
            $add_typeface.removeClass('show-options');
        });



        $font_source.on('change', function () {
            var value = $(this).val();

            if (value == 'google') {
                $google_section.show();
                $custom_section.hide();
                $adobe_section.hide();
            }
            else if (value == 'adobe') {
                $google_section.hide();
                $custom_section.hide();
                $adobe_section.show();
            }
            else if (value == 'custom') {
                $google_section.hide();
                $custom_section.show();
                $adobe_section.hide();
            }
        }).trigger('change');

        $(document).on('click','.rad-typeface .rad-delete', function () {
            $(this).parents('.rad-typeface').remove();
            collect_fonts();
        });

        $add_button.on('click', function (e) {
            e.preventDefault();
            $add_typeface.removeClass('show-options');
            var font_source = $('select#font-source :selected').val(),
                font_name = '',
                font_link = '',
                font_embed = '',
                font_weights = '',
                template = $('script#rad-typeface-tempalte').html();


            if (font_source == 'google') {
                font_name = $('select#google-fonts :selected').val();
                font_weights = $('select#google-fonts :selected').data("weights").toString();

            }
            else if (font_source == 'adobe') {
                font_name = $('#adobe-fonts :selected').val();
                font_weights = $('select#adobe-fonts :selected').data("weights").toString();
                font_embed = $('#embeding-method').val();

            }
            else {
                font_name = $('#font-name').val();
                font_weights = $('#font-variants').val();
                font_link = $('#css-file').val();
            }


            var weights_tags = '';

            if (font_weights != '') {
                if (font_weights.indexOf(',') > -1) {
                    var weights_array = font_weights.split(',');

                    $.each(weights_array, function (index, item) {
                        var checked = '';
                        if (index == 0) {
                            checked = 'checked';
                            weights_tags = '<span><input type="hidden" value="' + item + '" class="fontweights" name="fontweights">';

                        }
                        weights_tags += '<span><input type="checkbox" value="' + item + '" class="fontweightscheckbox" ' + checked + '>' + item + '</span>';
                    });

                }
                else {
                    weights_tags = '<span><input type="hidden" value="' + font_weights + '" class="fontweights" name="fontweights">';
                    weights_tags += '<span><input type="checkbox" value="' + font_weights + '" class="fontweightscheckbox" checked>' + font_weights + '</span>';
                }
            }


            template = template.replace(new RegExp("{fontname}", 'g'), font_name);
            template = template.replace(new RegExp("{fontsource}", 'g'), font_source);
            template = template.replace(new RegExp("{allweights}", 'g'), font_weights);
            template = template.replace(new RegExp("{fontweights}", 'g'), weights_tags);
            template = template.replace(new RegExp("{fontlink}", 'g'), font_link);
            template = template.replace(new RegExp("{fontembed}", 'g'), font_embed);

            $add_typeface.before(template);

            append_font_to_page(font_source,font_name,font_weights,rad_typkitid,font_link);

            collect_fonts();
        });

        var append_font_to_page = function(font_source,font_name,font_weights,rad_typkitid,font_link){
            var address = '';
            if (font_source == 'google') {
                font_name = font_name.replace(new RegExp(" ", 'g'), "+");
                address = 'https://fonts.googleapis.com/css?family=' + font_name + ':' + font_weights;
            }
            else if (font_source == 'adobe') {
                if(rad_typkitid != '')
                {
                    address = 'https://use.typekit.net/' + rad_typkitid +'.css';
                }
            }
            else {
                address = font_link;
            }

            var link = document.createElement('link');
            link.setAttribute('rel', 'stylesheet');
            link.setAttribute('type', 'text/css');
            link.setAttribute('href', address);
            document.head.appendChild(link);
        };

        $(document).on('click', '.fontweightscheckbox', function () {
            var $hiddeninput = $(this).parents('.font-weights').find('.fontweights'),
                $chckboxes   = $(this).parents('.font-weights').find('.fontweightscheckbox:checked'),
                values       = [];
            
            $chckboxes.each(function() {
                values.push($(this).val());
            });

            $hiddeninput.val(values.join(','));
            collect_fonts();
            
        });

        $(document).on('mouseover', '.fontweightscheckbox', function () {
            var variant = $(this).val(),
                $preview   = $(this).parents('.rad-typeface').find('.rad-typeface-preview');

                if(variant == 'italic')
                {
                    $preview.css('font-style','italic');
                    $preview.css('font-weight','normal');
                } 
                if(variant == 'regular')
                {
                    $preview.css('font-style','');
                    $preview.css('font-weight','normal');
                }
                else if(!isNaN(variant)) //it's numerical
                {
                    $preview.css('font-weight',variant);
                    $preview.css('font-style','normal');
                }
                else if(variant.includes('italic')) 
                {
                    $preview.css('font-style','italic');
                    $preview.css('font-weight',variant.replace('italic', ''));
                }        
        });


        $('.rad-typeface').each(function(){
            var $this  = $(this),
            weights    = $this.find('.fontweights').val(),
            source     = $this.find('input[name="sources"]').val(),
            font       = $this.find('input[name="fonts"]').val(),
            link       = $this.find('input[name="links"]').val(),
            embed      = $this.find('input[name="embeds"]').val(),
            allweights = $this.find('input[name="allweights"]').val();

            append_font_to_page(source,font,allweights,rad_typkitid,link);
        });

        var collect_fonts = function() {
            var $container = $('.fonts-input'),
                $input = $container.find('input[name="fonts-collection"]'),
                json_array = [];

            $container.find('.rad-typeface').each(function(){
                var $this  = $(this),
                weights    = $this.find('.fontweights').val(),
                source     = $this.find('input[name="sources"]').val(),
                font       = $this.find('input[name="fonts"]').val(),
                link       = $this.find('input[name="links"]').val(),
                embed      = $this.find('input[name="embeds"]').val(),
                allweights = $this.find('input[name="allweights"]').val(),
                font_data  = {
                    'source': source,
                    'font': font,
                    'weights': weights,
                    'link' : link,
                    'embed' : embed,
                    'allweights' : allweights,
                };

                json_array.push(font_data);
            });
            //save value
            var json_output = JSON.stringify(json_array);
            $input.val(json_output);

            //update other options
            var $selects = $('select[name="font-body"],select[name="font-headings"],select[name="font-navigation"]')
            var selected_vale = {
                'font-body' : $('select[name="font-body"]').val(),
                'font-headings' : $('select[name="font-headings"]').val(),
                'font-navigation' : $('select[name="font-navigation"]').val(),
            };

            $selects.each(function(){
                $(this).find('option:not(:first)').remove();
            });


            for (i = 0; i < json_array.length; ++i) {
                var source = json_array[i]['source'],
                    font = json_array[i]['font'],
                    weights = json_array[i]['weights'].split(',');

                for (j = 0; j < weights.length; ++j) {
                    var optionText = source + ' : ' + font + ' : ' + weights[j];
  
                    $selects.append(`<option value="${optionText}">${optionText}</option>`); 
                }
            }
            $("#yourSelect option[value='yourValue']").length > 0;
            $.each(selected_vale, function(index, value){
                var $select = $selects.filter('[name="' + index + '"]'),
                    $selected_option = $select.find('option[value="'+ value +'"]');
                if($selected_option.length > 0)
                {
                    $selected_option.prop('selected', true);
                }
                else
                {
                    $select.find("option:first").prop('selected', true);
                }
            });
            $selects.trigger('change');
        }
    }

    function product_hover_style_dependencies () {
        var $product_hover_styles = $('.rad-main .field[data-name="product-style"]');

        $product_hover_styles.find('a').on('image_selected',function(){
            product_hover_styles_change();
        });

        product_hover_styles_change();

        function product_hover_styles_change() {
            var $selected = $product_hover_styles.find('a.selected');

            if ( $selected.hasClass('creative') ) {
                $('.field[data-name="quickview-cursor"]').removeClass('hide-field');
            }
            else
            {
                $('.field[data-name="quickview-cursor"]').addClass('hide-field'); 
            }
        };

    }

    jQuery(function(){
        init_font_collections();
        product_hover_style_dependencies();
        sticky_topbar();
        generate_id();
    });


})(jQuery);