var innovation_ruby_setup_sections;
var innovation_ruby_setup_blocks;
var innovation_ruby_composer_template;
var innovation_ruby_composer_page_data;

jQuery(document).ready(function ($) {
    "use strict";

    /*********** LAYOUT PAGE BUILDER *************/

    $('#page_template').change(function () {

        var template = $('#page_template').val();
        //enable page composer
        if ('page-composer.php' == template) {
            $('#innovation_ruby_composer_editor').show();
            $('#innovation_ruby_metabox_composer_options').show();
            $('#innovation_ruby_metabox_single_page_options').hide();
            $('#innovation_ruby_metabox_sidebar_options').hide();
            $('#innovation_ruby_metabox_comment_box_options').hide();
            $('#postdivrich').hide();

        } else {
            $('#innovation_ruby_composer_editor').hide();
            $('#innovation_ruby_metabox_composer_options').hide();

            $('#innovation_ruby_metabox_single_page_options').show();
            $('#innovation_ruby_metabox_sidebar_options').show();
            $('#innovation_ruby_metabox_comment_box_options').show();
            $('#postdivrich').show();
        }
    }).triggerHandler('change');


    /*********** CORE *************/
    var innovation_ruby_page_builder = {

        /*********** INIT *************/
        //init
        init: function () {
            if ('undefined' === typeof innovation_ruby_composer_template) {
                return;
            }
            innovation_ruby_page_builder.setup_section_select();
            innovation_ruby_page_builder.init_section();
        },

        //Init sections
        init_section: function () {
            var sections = $('#innovation_ruby_composer_editor').find('.ruby-sections-wrap');
            innovation_ruby_page_builder.render_section();

            sections.sortable({
                handle: '.ruby-section-bar',
                placeholder: 'ruby-highlight',
                forcePlaceholderSize: true
            });

        },


        //Init blocks
        init_block: function (new_section, section_data) {

            //Load block select
            innovation_ruby_page_builder.setup_block_select(new_section);

            //load block data
            if (section_data) {
                if (section_data['blocks']) {
                    $.each(section_data['blocks'], function (block_id, block_data) {
                        innovation_ruby_page_builder.load_block(block_data['block_name'], new_section.find('.ruby-block-wrap'), block_data);
                    })
                }
            }
            //add sortable block
            var block = new_section.find('.ruby-blocks');
            block.sortable({
                handle: '.ruby-block-bar',
                placeholder: 'ruby-highlight',
                forcePlaceholderSize: true
            });
        },


        /***********CREATE SECTION SELECT*************/
        setup_section_select: function () {

            var select_list = $('#innovation_ruby_section_select');

            //create section element
            $.each(innovation_ruby_setup_sections, function (section_type, config) {
                var select_item = $('<div class="section-select-el"><a href="#"></a></div>');
                if (config['img']) {
                    select_item = $('<div class="section-select-el"><a href="#"><img alt="' + section_type + '" src="' + config['img'] + '"></a></div>');
                }
                select_item.find('a').data('section_type', section_type).append('<span>' + config.title + '</span>');

                //create section list
                select_list.append(select_item);
            });

            //add section
            select_list.find('a').click(innovation_ruby_page_builder.add_section);

            //Toggle select section box
            $('#page_composer_section_select').click(function (e) {
                select_list.slideToggle(200);
                e.stopPropagation();
                return false;
            })

        },

        //add select block list
        setup_block_select: function (new_section) {

            var select_list = new_section.find('.block-select-wrap');

            $.each(innovation_ruby_setup_blocks, function (block_name, config) {
                if (config['section'] === new_section['section_type']) {
                    var select_item = $('<div class="block-select-el"><a href="#"></a></div>');
                    if (config['img']) {
                        select_item = $('<div class="block-select-el"><a href="#"><img alt="' + block_name + '" src="' + config['img'] + '"></a></div>');
                    }
                    select_item.find('a').data('block_name', block_name).append('<span>' + config.title + '</span>');

                    //create block list
                    select_list.append(select_item);
                }
            });

            select_list.find('a').click(innovation_ruby_page_builder.add_block);

            //Toggle select block box
            new_section.find('.add-block-select').click(function (e) {
                select_list.slideToggle(200);
                e.stopPropagation();
                return false;
            })
        },

        /***********CREATE SECTIONS*************/

        //click add section
        add_section: function () {
            //get section type
            var section_type = $(this).data('section_type');

            //create section
            var new_section = innovation_ruby_page_builder.load_section(section_type, false);

            //scroll to section
            if (undefined != new_section) {
                $('body').animate({
                    scrollTop: new_section.offset().top
                }, 500);
            }

            return false;
        },

        //load section
        load_section: function (section_type, section_data) {

            var default_sidebar;
            var uuid;

            if ('undefined' === typeof innovation_ruby_composer_template[section_type]) return;

            //create unique id
            if ('undefined' === typeof section_data.section_id) {
                uuid = $.uuid();
            } else {
                uuid = section_data.section_id;
            }

            //create unique id
            var section_id = 'innovation_ruby_section_' + uuid;
            var new_section = $(innovation_ruby_composer_template[section_type]);
            if (section_type == 'section_has_sidebar') {
                var sidebar_id = 'innovation_ruby_sidebar_' + uuid;
                var sidebar_position_id = 'innovation_ruby_sidebar_position_' + uuid;
                new_section.find('.ruby-section-sidebar').html(innovation_ruby_composer_template['input']['sidebar']);
                if ('undefined' === typeof section_data['section_sidebar_position'])
                    new_section.find('.ruby-sidebar-position').attr('name', sidebar_position_id);
                else
                    new_section.find('.ruby-sidebar-position').attr('name', sidebar_position_id).val(section_data['section_sidebar_position']);
                var sidebar_select = new_section.find('.ruby-sidebar-select');
                if ('undefined' === typeof section_data['section_sidebar'])
                    default_sidebar = 'innovation_ruby_sidebar_default';
                else
                    default_sidebar = section_data['section_sidebar'];
                sidebar_select.attr('name', sidebar_id).val(default_sidebar);
                new_section.find('.ruby-section-sidebar label').click(function () {
                    new_section.find('.ruby-sidebar-select-wrap').slideToggle(200);
                    return false;
                })
            }

            new_section.find('.ruby-section-type').attr('name', section_id).val(section_type);
            new_section.find('.ruby-section-order').val(uuid);
            new_section.find('.ruby-section-label').html(innovation_ruby_setup_sections[section_type].title);

            var section_wrap = $('#innovation_ruby_composer_editor').find('.ruby-sections-wrap');

            //append new section
            section_wrap.children('.ruby-section-empty').remove();
            section_wrap.append(new_section);

            //load button
            innovation_ruby_page_builder.button_section(new_section);

            //init block
            new_section['section_type'] = section_type; //filter block of section
            innovation_ruby_page_builder.init_block(new_section, section_data);

            return new_section;
        },

        //enable button section
        button_section: function (new_section) {
            new_section.find('.ruby-section-bar, .ruby-section-open-option').click(innovation_ruby_page_builder.open_section_setting);
            new_section.find('.ruby-section-delete').click(innovation_ruby_page_builder.delete_section);
        },

        //delete section
        delete_section: function (e) {
            $(e.target).parents('.ruby-section').fadeOut(300, function () {
                $(this).remove()
            });
            return false;
        },

        //open section
        open_section_setting: function (e) {
            var section_setting = $(e.target).parents('.ruby-section').find('.ruby-block-wrap');
            section_setting.slideToggle();
            return false;
        },

        /***********BLOCK*************/
        //click add block
        add_block: function () {
            var this_module = $(this);
            var block_name = this_module.data('block_name');
            var module_wrap = this_module.parents('.ruby-block-wrap');
            var new_block = innovation_ruby_page_builder.load_block(block_name, module_wrap, false);

            if (undefined != new_block) {
                $('body').animate({
                    scrollTop: new_block.offset().top
                }, 500, function () {
                    new_block.find('.ruby-block-open-option').trigger('click');
                });
            }

            return false;
        },

        //load block
        load_block: function (block_name, module_wrap, block_data) {

            var block_name_title;
            var block_name_desc;
            var uuid;

            //create unique id
            if ('undefined' === typeof block_data.block_id) {
                uuid = $.uuid();
            } else {
                uuid = block_data.block_id;
            }

            //load Block Name can translate
            block_name_title = innovation_ruby_setup_blocks[block_name].title;
            block_name_desc = innovation_ruby_setup_blocks[block_name].description;

            //create unique id

            module_wrap.find('.ruby-section-empty').remove();
            var id = 'innovation_ruby_block_' + uuid;
            var new_block = $(innovation_ruby_composer_template['block']);
            var module_id = module_wrap.find('.ruby-section-order').val();
            new_block.find('.ruby-block-name').attr('name', id).val(block_name);
            new_block.find('.ruby-block-order').attr('name', 'innovation_ruby_block_order[' + module_id + '][]').val(uuid);
            new_block.find('.ruby-block-description').html(block_name_desc);
            if (block_data && block_data['block_options']['title']) {
                new_block.find('.ruby-block-label').html(block_name_title + ' : ' + block_data['block_options']['title']);
            } else {
                new_block.find('.ruby-block-label').html(block_name_title);
            }

            var block_wrap = module_wrap.find('.ruby-blocks');

            //load block options
            innovation_ruby_page_builder.block_setting_options(new_block, block_name, block_data['block_options']);

            //append new block
            block_wrap.append(new_block);

            //load button
            innovation_ruby_page_builder.button_block(new_block);

            return new_block;
        },

        //enable button block
        button_block: function (new_block) {
            new_block.find('.ruby-block-bar, .ruby-block-open-option').click(innovation_ruby_page_builder.open_block_setting);
            new_block.find('.ruby-block-delete').click(innovation_ruby_page_builder.delete_block);
        },

        //delete block
        delete_block: function (e) {
            $(e.target).parents('.ruby-block-item').fadeOut(300, function () {
                $(this).remove()
            });
            return false;
        },

        //open block
        open_block_setting: function (e) {
            var block_setting = $(e.target).parents('.ruby-block-item').find('.ruby-block-options-wrap');
            block_setting.slideToggle();
            return false;
        },

        /*********** LOAD BLOCK OPTIONS *************/
        block_setting_options: function (new_block, block_name, innovation_ruby_default_value) {
            var block_id = new_block.find('.ruby-block-name').attr('name');

            $.each(innovation_ruby_setup_blocks, function (name, config) {

                //check option block
                if ($(config.block_options).length == 0) return;

                //check block and get setting option of block
                if (block_name == name) {

                    //remove hidden class
                    new_block.find('.ruby-block-options-wrap').removeClass('hidden');

                    //render block options
                    $.each(config.block_options, function (option, value) {

                        var title;
                        var input;
                        var description;
                        var new_block_options = $(innovation_ruby_composer_template['block_option']);

                        //check if false then return;
                        if (value === false) return;

                        //render title options
                        if (option == 'title') {
                            title = innovation_ruby_composer_template['title']['title'];
                            description = innovation_ruby_composer_template['desc']['title'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render title url
                        if (option == 'title_url') {
                            title = innovation_ruby_composer_template['title']['title_url'];
                            description = innovation_ruby_composer_template['desc']['title_url'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render sub title option
                        if (option == 'sub_title') {
                            title = innovation_ruby_composer_template['title']['sub_title'];
                            description = innovation_ruby_composer_template['desc']['sub_title'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render category option
                        if (option == 'category_id') {
                            title = innovation_ruby_composer_template['title']['category_id'];
                            description = innovation_ruby_composer_template['desc']['category_id'];
                            input = innovation_ruby_composer_template['input']['category'];
                        }

                        //render child of category
                        if (option == 'child_category') {
                            title = innovation_ruby_composer_template['title']['child_category'];
                            description = innovation_ruby_composer_template['desc']['child_category'];
                            input = innovation_ruby_composer_template['input']['show_options'];
                        }

                        //render number child of category
                        if (option == 'num_of_child_category') {
                            title = innovation_ruby_composer_template['title']['num_of_child_category'];
                            description = innovation_ruby_composer_template['desc']['num_of_child_category'];
                            input = innovation_ruby_composer_template['input']['num'];
                        }


                        //render categories option
                        if (option == 'category_ids') {
                            title = innovation_ruby_composer_template['title']['category_ids'];
                            description = innovation_ruby_composer_template['desc']['category_ids'];
                            input = innovation_ruby_composer_template['input']['categories'];
                        }

                        //render tags option
                        if (option == 'tags') {
                            title = innovation_ruby_composer_template['title']['tags'];
                            description = innovation_ruby_composer_template['desc']['tags'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render authors option
                        if (option == 'authors') {
                            title = innovation_ruby_composer_template['title']['authors'];
                            description = innovation_ruby_composer_template['desc']['authors'];
                            input = innovation_ruby_composer_template['input']['authors'];
                        }

                        //render posts per page option
                        if (option == 'posts_per_page') {
                            title = innovation_ruby_composer_template['title']['posts_per_page'];
                            description = innovation_ruby_composer_template['desc']['posts_per_page'];
                            input = innovation_ruby_composer_template['input']['num'];
                        }

                        //render number of slider
                        if (option == 'num_of_slider') {
                            title = innovation_ruby_composer_template['title']['num_of_slider'];
                            description = innovation_ruby_composer_template['desc']['num_of_slider'];
                            input = innovation_ruby_composer_template['input']['num'];
                        }

                        //render posts offset option
                        if (option == 'offset') {
                            title = innovation_ruby_composer_template['title']['offset'];
                            description = innovation_ruby_composer_template['desc']['offset'];
                            input = innovation_ruby_composer_template['input']['num'];
                        }

                        //render posts sorted option
                        if (option == 'orderby') {
                            title = innovation_ruby_composer_template['title']['orderby'];
                            description = innovation_ruby_composer_template['desc']['orderby'];
                            input = innovation_ruby_composer_template['input']['orderby'];
                        }


                        //render posts excerpt
                        if (option == 'excerpt') {
                            title = innovation_ruby_composer_template['title']['excerpt'];
                            description = innovation_ruby_composer_template['desc']['excerpt'];
                            input = innovation_ruby_composer_template['input']['num'];
                        }

                        //render read more button
                        if (option == 'readmore') {
                            title = innovation_ruby_composer_template['title']['readmore'];
                            description = innovation_ruby_composer_template['desc']['readmore'];
                            input = innovation_ruby_composer_template['input']['show_options'];
                        }

                        //render option content
                        if (option == 'content') {
                            title = innovation_ruby_composer_template['title']['content'];
                            description = innovation_ruby_composer_template['desc']['content'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render option image url
                        if (option == 'image_url') {
                            title = innovation_ruby_composer_template['title']['image_url'];
                            description = innovation_ruby_composer_template['desc']['image_url'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render option image link
                        if (option == 'image_link') {
                            title = innovation_ruby_composer_template['title']['image_link'];
                            description = innovation_ruby_composer_template['desc']['image_link'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render option button title
                        if (option == 'button_title') {
                            title = innovation_ruby_composer_template['title']['button_title'];
                            description = innovation_ruby_composer_template['desc']['button_title'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        //render posts pagination
                        if (option == 'pagination') {
                            title = innovation_ruby_composer_template['title']['pagination'];
                            description = innovation_ruby_composer_template['desc']['pagination'];
                            var pagination_options = [];
                            pagination_options.push(innovation_ruby_composer_template['input']['pagination']['none']);
                            $.each(value, function (type, val) {
                                if (val == true) {
                                    pagination_options.push(innovation_ruby_composer_template['input']['pagination'][type]);
                                }
                            });

                            input = '<select class="ruby-field">' + pagination_options.join('') + '</select>';
                        }

                        //render code content
                        if (option == 'custom_html') {
                            title = innovation_ruby_composer_template['title']['custom_html'];
                            description = innovation_ruby_composer_template['desc']['custom_html'];
                            input = innovation_ruby_composer_template['input']['textarea'];
                        }

                        //render short code
                        if (option == 'short_code') {
                            title = innovation_ruby_composer_template['title']['short_code'];
                            description = innovation_ruby_composer_template['desc']['short_code'];
                            input = innovation_ruby_composer_template['input']['textarea'];
                        }

                        //render block style
                        if (option == 'block_style') {
                            title = innovation_ruby_composer_template['title']['block_style'];
                            description = innovation_ruby_composer_template['desc']['block_style'];
                            input = innovation_ruby_composer_template['input']['block_style'];
                        }

                        //render full mode
                        if (option == 'wrap_mode') {
                            title = innovation_ruby_composer_template['title']['wrap_mode'];
                            description = innovation_ruby_composer_template['desc']['wrap_mode'];
                            input = innovation_ruby_composer_template['input']['wrap_mode'];
                        }

                        //render 1st classic post
                        if (option == 'big_first') {
                            title = innovation_ruby_composer_template['title']['big_first'];
                            description = innovation_ruby_composer_template['desc']['big_first'];
                            input = innovation_ruby_composer_template['input']['show_options'];
                        }

                        if (option == 'color') {
                            title = innovation_ruby_composer_template['title']['color'];
                            description = innovation_ruby_composer_template['desc']['color'];
                            input = innovation_ruby_composer_template['input']['color'];
                        }

                        //ad box
                        if (option == 'ad_title') {
                            title = innovation_ruby_composer_template['title']['ad_title'];
                            description = innovation_ruby_composer_template['desc']['ad_title'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        if (option == 'ad_image') {
                            title = innovation_ruby_composer_template['title']['ad_image'];
                            description = innovation_ruby_composer_template['desc']['ad_image'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        if (option == 'ad_url') {
                            title = innovation_ruby_composer_template['title']['ad_url'];
                            description = innovation_ruby_composer_template['desc']['ad_url'];
                            input = innovation_ruby_composer_template['input']['text'];
                        }

                        if (option == 'ad_script') {
                            title = innovation_ruby_composer_template['title']['ad_script'];
                            description = innovation_ruby_composer_template['desc']['ad_script'];
                            input = innovation_ruby_composer_template['input']['textarea'];
                        }

                        /**
                         * Create ruby options
                         */

                        input = $(input);
                        if (typeof value != 'boolean' && input.length) input.val(value);
                        if (innovation_ruby_default_value && typeof innovation_ruby_default_value[option] != 'undefined') input.val(innovation_ruby_default_value[option]);
                        input.attr('name', 'innovation_ruby_block_option[' + block_id + '][' + option + ']');
                        new_block_options.find('.ruby-block-option-label').append(title);
                        new_block_options.find('.ruby-block-option-description').append(description);
                        new_block_options.find('.ruby-block-option-inner').append(input);

                        //append setting
                        new_block.find('.ruby-block-options-wrap').append(new_block_options);
                    })
                }
            });

            return new_block;
        },

        /*********** LOAD SAVED PAGE BUILDER*************/
        render_section: function () {
            var innovation_ruby_composer_editor = $('#innovation_ruby_composer_editor');

            if ('undefined' === typeof innovation_ruby_composer_page_data) {
                innovation_ruby_composer_editor.find('#ruby-page-composer-loading').fadeTo(500, 0, function () {
                    $(this).remove();
                });
                return;
            }

            $.each(innovation_ruby_composer_page_data, function (section_id, section_data) {
                innovation_ruby_page_builder.load_section(section_data['section_type'], section_data);
            });

            innovation_ruby_composer_editor.find('#ruby-page-composer-loading').fadeTo(500, 0, function () {
                $(this).remove();
            })
        }

        /*********** END CORE *************/
    };

    //create unique id
    $.uuid = function () {
        return 'xxxxxxxx_xxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    };

    //init load
    innovation_ruby_page_builder.init();

});