jQuery(function ($) {

    /*
     * Strips one query argument from a given URL string
     *
     */
    function remove_query_arg(key, sourceURL) {

        var rtn = sourceURL.split("?")[0],
            param,
            params_arr = [],
            queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";

        if (queryString !== "") {
            params_arr = queryString.split("&");
            for (var i = params_arr.length - 1; i >= 0; i -= 1) {
                param = params_arr[i].split("=")[0];
                if (param === key) {
                    params_arr.splice(i, 1);
                }
            }

            rtn = rtn + "?" + params_arr.join("&");

        }

        if (rtn.split("?")[1] == "") {
            rtn = rtn.split("?")[0];
        }

        return rtn;
    }


    /*
     * Adds an argument name, value pair to a given URL string
     *
     */
    function add_query_arg(key, value, sourceURL) {

        return sourceURL + '&' + key + '=' + value;

    }


    /**
     * Initialize colorpicker
     *
     */
    $('.wpsbc-colorpicker').wpColorPicker();

    /**
     * Initialize Chosen
     *
     */
    if (typeof $.fn.chosen != 'undefined') {

        $('.wpsbc-chosen').chosen();

    }

    /**
     * Links that have the inactive class should do nothing
     *
     */
    $(document).on('click', 'a.wpsbc-inactive, input[type=submit].wpsbc-inactive', function () {

        return false;

    });

    /**
     * Initialize the sortable function on the Calendar Legend List Table
     *
     */
    $('table.wpsbc_legend_items tbody').sortable({
        handle: '.wpsbc-move-legend-item',
        containment: '#wpcontent',
        placeholder: 'wpsbc-list-table-sort-placeholder',
        helper: function (e, tr) {
            var $originals = tr.children();
            var $helper = tr.clone();

            $helper.children().each(function (index) {
                // Set helper cell sizes to match the original sizes
                $(this).width($originals.eq(index).width());
            });

            return $helper;
        },
        update: function (e, ui) {

            var legend_item_ids = [];

            $('table.wpsbc_legend_items tbody tr .wpsbc-move-legend-item').each(function () {
                legend_item_ids.push($(this).data('id'));
            })

            var data = {
                action: 'wpsbc_sort_legend_items',
                token: $('[name="wpsbc_token"]').val(),
                calendar_id: $('[name="calendar_id"]').val(),
                legend_item_ids: legend_item_ids
            }

            // Add table wrapper and overlay
            $('table.wpsbc_legend_items').wrap('<div class="wpsbc-wp-list-table-wrapper"></div>');
            $('table.wpsbc_legend_items').closest('.wpsbc-wp-list-table-wrapper').append('<div class="wpsbc-overlay"><div class="spinner"></div></div>');

            // Make sort ajax call
            $.post(ajaxurl, data, function (response) {

                response = JSON.parse(response);

                if (!response.success) {

                    window.location.replace(response.redirect_url_error);

                } else {

                    // Remove table wrapper and overlay
                    $('table.wpsbc_legend_items').siblings('.wpsbc-overlay').remove();
                    $('table.wpsbc_legend_items').unwrap('.wpsbc-wp-list-table-wrapper');

                }


            });

        }
    });

    $('table.wpsbc_legend_items tbody').disableSelection();


    /**
     * Handle show/hide of the second color option for Legend Item add/edit screen
     *
     */
    $(document).on('change', 'select[name="legend_item_type"]', function () {
        console.log($(this).val())
        if ($(this).val() == 'single') {
            $('#wpsbc-legend-item-color-2').closest('.wp-picker-container').hide();
            $('.wpsbc-admin-field-changeover-type').hide();
        } else {
            $('#wpsbc-legend-item-color-2').closest('.wp-picker-container').show();
            $('.wpsbc-admin-field-changeover-type').show();
        }
    });

    $(document).ready(function () {

        if ($('select[name="legend_item_type"]').length){
            $('select[name="legend_item_type"]').trigger('change');
        }

    });

    /**
     * Customizer
     * 
     */
     var wpsbc_customizer_themes = {
        'default': {
            'header_background_color': '#f5f5f5',
            'header_text_color': '#000',
            'header_arrow_background_color': '#bdc3c7',
            'header_arrow_color': '#fff',
            'header_dropdown_background_color': '#fff',
            'header_dropdown_border_color': '#bdc3c7',
            'header_dropdown_color': '#000',
            'calendar_background_color': '#fff',
            'calendar_border_color': '#f1f1f1',
            'calendar_text_color': '#000',
            'dates_pad_cells': '#f7f7f7',
            'dates_weeknumbers': '#e8e8e8',
            'dates_border_radius': '0',
        },
        'dark': {
            'header_background_color': '#474747',
            'header_text_color': '#c1c1c1',
            'header_arrow_background_color': '#6a6a6a',
            'header_arrow_color': '#c1c1c1',
            'header_dropdown_background_color': '#6a6a6a',
            'header_dropdown_border_color': '#6a6a6a',
            'header_dropdown_color': '#c1c1c1',
            'calendar_background_color': '#262626',
            'calendar_border_color': '#262626',
            'calendar_text_color': '#c1c1c1',
            'dates_pad_cells': '#474747',
            'dates_weeknumbers': '#848484',
            'dates_border_radius': '0',
        }
    }

    $('body').on('change', '#_customize-input-wpsbc_preset_themes', function (e) {

        var $select = $(this);
        var newval = $select.val().split('-')[1];
        if (typeof wpsbc_customizer_themes[newval] !== 'undefined') {
            $.each(wpsbc_customizer_themes[newval], function (field, value) {
                var $parent = $("#customize-control-wpsbc_" + field);
                if ($parent.find(".color-picker-hex").length) {
                    $parent.find(".color-picker-hex").val(value).trigger('change');
                }
                if ($parent.find('#_customize-input-wpsbc_' + field)) {
                    $parent.find('#_customize-input-wpsbc_' + field).val(value).trigger('change');
                }

            });
            $('#_customize-input-wpsbc_preset_themes').val('');
            $("#sub-accordion-section-wpsbc_presets_options .customize-section-back").trigger('click');
        }

    })

    /**
     * Tab Navigation
     *
     */
    $('.wpsbc-nav-tab').on('click', function (e) {
        e.preventDefault();

        // Nav Tab activation
        $('.wpsbc-nav-tab').removeClass('wpsbc-active').removeClass('nav-tab-active');
        $(this).addClass('wpsbc-active').addClass('nav-tab-active');

        // Show tab
        $('.wpsbc-tab').removeClass('wpsbc-active');

        var nav_tab = $(this).attr('data-tab');
        $('.wpsbc-tab[data-tab="' + nav_tab + '"]').addClass('wpsbc-active');
        $('input[name=active_tab]').val(nav_tab);

        // Change http referrer
        $_wp_http_referer = $('input[name=_wp_http_referer]');

        var _wp_http_referer = $_wp_http_referer.val();
        _wp_http_referer = remove_query_arg('tab', _wp_http_referer);
        $_wp_http_referer.val(add_query_arg('tab', $(this).attr('data-tab'), _wp_http_referer));

    });


    /**
     * Link Calendar
     *
     */
    $('#wpsbc-settings-field-wrapper-calendar-link-' + $('[name="calendar_link_type"]').val()).show();

    $(document).on('change', '[name="calendar_link_type"]', function () {

        $('#wpsbc-settings-field-wrapper-calendar-link-internal').hide();
        $('#wpsbc-settings-field-wrapper-calendar-link-external').hide();

        $('#wpsbc-settings-field-wrapper-calendar-link-' + $(this).val()).show();

    });

    /**
     * Calendar Title Translations Toggle
     */
    $(".wrap.wpsbc-wrap-edit-calendar #titlediv .titlewrap-toggle").click(function (e) {
        e.preventDefault();
        $(this).toggleClass('open');
        $(".titlewrap-translations").slideToggle();

    });

    /**
     * Toggle settings translations
     * 
     */
    $(".wpsbc-wrap").on('click', '.wpsbc-settings-field-show-translations', function (e) {
        e.preventDefault();
        $(this).parents('.wpsbc-settings-field-translation-wrapper').find(".wpsbc-settings-field-translations").slideToggle();
        $(this).toggleClass('open');
    })


    /**
     * Modifies the modal inner height to permit the scrollbar to function properly
     *
     */
    $(window).resize(function () {

        $('.wpsbc-modal-inner').outerHeight($('.wpsbc-modal.wpsbc-active').outerHeight() - $('.wpsbc-modal.wpsbc-active .wpsbc-modal-header').outerHeight() - $('.wpsbc-modal.wpsbc-active .wpsbc-modal-nav-tab-wrapper').outerHeight());

    });

    /**
     * Close modal window
     *
     */
    $(document).on('click', '.wpsbc-modal-close', function (e) {

        e.preventDefault();

        $(this).closest('.wpsbc-modal').find('.wpsbc-modal-inner').scrollTop(0);

        $(this).closest('.wpsbc-modal').removeClass('wpsbc-active');
        $(this).closest('.wpsbc-modal').siblings('.wpsbc-modal-overlay').removeClass('wpsbc-active');

        $(window).resize();

    });

    /**
     * Close modal on clicking the modal overlay
     *
     */
    $(document).on('click', '.wpsbc-modal-overlay.wpsbc-active', function (e) {

        $('.wpsbc-modal.wpsbc-active').find('.wpsbc-modal-close').click();

    });

    /**
     * Open Shortcode Generator modal
     *
     */
    $(document).on('click', '#wpsbc-shortcode-generator-button', function (e) {

        e.preventDefault();

        $('#wpsbc-modal-add-calendar-shortcode, #wpsbc-modal-add-calendar-shortcode-overlay').addClass('wpsbc-active');

        $(window).resize();

        $('.wpsbc-modal.wpsbc-active').click();

    });

    /**
     * Builds the shortcode for the Single Calendar and inserts it in the WordPress text editor
     *
     */
    $(document).on('click', '#wpsbc-insert-shortcode-single-calendar', function (e) {

        e.preventDefault();

        // Begin shortcode
        var shortcode = '[wpsbc ';

        $('#wpsbc-modal-add-calendar-shortcode.wpsbc-active .wpsbc-shortcode-generator-field-calendar').each(function () {

            shortcode += $(this).data('attribute') + '="' + $(this).val() + '" ';

        });

        // End shortcode
        shortcode = shortcode.trim();
        shortcode += ']';

        window.send_to_editor(shortcode);

        $(this).closest('.wpsbc-modal').find('.wpsbc-modal-close').first().trigger('click');

    });


    /**
     * Make the Selected Calendars available for selection if "Display Calendars" value is set
     * to "Selected Calendars"
     *
     */
    $(document).on('change', '#modal-add-calendar-overview-shortcode-calendars', function () {

        if ($(this).val() == '2')
            $('#modal-add-calendar-overview-shortcode-selected-calendars').parent().removeClass('wpsbc-element-disabled');
        else
            $('#modal-add-calendar-overview-shortcode-selected-calendars').parent().addClass('wpsbc-element-disabled');

    });


    /**
     * Builds the shortcode for the Overview Calendar and inserts it in the WordPress text editor
     *
     */
    $(document).on('click', '#wpsbc-insert-shortcode-overview-calendar', function (e) {

        e.preventDefault();

        // Begin shortcode
        var shortcode = '[wpsbc-overview ';

        // Add the calendars shortcode attribute
        var calendars = $('#modal-add-calendar-overview-shortcode-calendars').val();

        if (calendars == '1')
            shortcode += 'calendars="all" ';

        // For selected calendars we want to maintain the order selected by the user, so grabbing
        // the value from the multiple select won't be enough, as this does not maintain the order
        else {

            var $select = $('#modal-add-calendar-overview-shortcode-selected-calendars');
            var select_val = '';

            $select.siblings('.chosen-container').find('li.search-choice a').each(function () {

                select_val += $select.find('option').eq($(this).data('option-array-index')).val() + ','

            });

            // Trim the last comma
            select_val = select_val.slice(0, -1);

            shortcode += 'calendars="' + select_val + '" ';

        }

        // Add the rest of the attributes
        $('#wpsbc-modal-add-calendar-shortcode.wpsbc-active .wpsbc-shortcode-generator-field-calendar-overview').each(function () {

            shortcode += $(this).data('attribute') + '="' + $(this).val() + '" ';

        });

        // End shortcode
        shortcode = shortcode.trim();
        shortcode += ']';

        window.send_to_editor(shortcode);

        $(this).closest('.wpsbc-modal').find('.wpsbc-modal-close').first().trigger('click');

    });

    /**
     * Register and deregister website functionality
     *
     */
    $(document).on('click', '#wpsbc-register-website-button, #wpsbc-deregister-website-button', function (e) {

        e.preventDefault();

        window.location = add_query_arg('serial_key', $('[name="serial_key"]').val(), $(this).attr('href'));

    });

    $(document).on('click', '#wpsbc-check-for-updates-button', function (e) {

        if ($(this).attr('disabled') == 'disabled')
            e.preventDefault();

    });


    /**
     * iCal Import forms
     *
     */
    $(document).on('change', '#wpsbc-ical-file-import input, #wpsbc-ical-file-import select', function () {

        $('#wpsbc-ical-file-import input, #wpsbc-ical-file-import select').each(function () {

            if ($(this).val() == '') {

                $('#wpsbc-ical-file-import input[type=submit]').attr('disabled', true);
                return false;

            } else
                $('#wpsbc-ical-file-import input[type=submit]').attr('disabled', false);

        });

    });

    $(document).on('change', '#ical_url_import_split_days', function () {

        if ($(this).prop('checked')) {
            $('#wpsbc-ical-url-import .wpsbc-settings-field-conditional').show();
        } else {
            $('#wpsbc-ical-url-import .wpsbc-settings-field-conditional').hide();
        }

    });

    $(document).on('change keyup', '#wpsbc-ical-url-import input, #wpsbc-ical-url-import select, #ical_url_import_split_days', function () {

        $('#wpsbc-ical-url-import input, #wpsbc-ical-url-import select:visible').each(function () {

            if ($(this).val() == '') {

                $('#wpsbc-ical-url-import input[type=submit]').attr('disabled', true);
                return false;

            } else
                $('#wpsbc-ical-url-import input[type=submit]').attr('disabled', false);

        });

    });

    /**
     * iCal Settings page fields
     *
     */
    $(document).on('change', '#wpsbc-settings-field-ical-refresh-times-wrapper select', function () {

        if ($(this).val() == 'custom')
            $('#wpsbc-settings-field-ical-custom-refresh-time-wrapper').show();
        else
            $('#wpsbc-settings-field-ical-custom-refresh-time-wrapper').hide();

    });

    $('#wpsbc-settings-field-ical-refresh-times-wrapper select').trigger('change');


    /**
     * Move the calendar from the sidebar to the main content and back in the calendar edit screen 
     * when resizing the window
     *
     */
    $(window).on('resize', function () {

        // Move the calendar from the sidebar to the main content
        if ($(window).innerWidth() < 850) {

            $('.wpsbc-container').closest('.postbox').detach().prependTo('#post-body-content');

        } else {

            $('.wpsbc-container').closest('.postbox').detach().prependTo('#postbox-container-1');

        }

    });

    $(window).trigger('resize');


    /**
     * iCalendar Export warning message
     * 
     */
    $("#ical-export-legend-items").change(function () {
        if ($(this).find('option:selected').length > 1) {
            $(this).siblings('.wpsbc-warning').show();
        } else {
            $(this).siblings('.wpsbc-warning').hide();
        }
    }).trigger('change');

    /**
     * Search Widget Scripts
     * 
     */

    /**
     * Make the Selected Calendars available for selection if "Display Calendars" value is set
     * to "Selected Calendars"
     *
     */
    $(document).on('change', '#modal-add-search-widget-shortcode-calendars', function () {

        if ($(this).val() == '2')
            $('#modal-add-search-widget-shortcode-selected-calendars').parent().removeClass('wpsbc-element-disabled');
        else
            $('#modal-add-search-widget-shortcode-selected-calendars').parent().addClass('wpsbc-element-disabled');

    });

    $(document).on('change', '.wpsbc-widget-display-calendars-select select', function () {
        if ($(this).val() == '2')
            $(this).parents('.widget-content').find('.wpsbc-chosen-wrap').removeClass('wpsbc-element-disabled');
        else
            $(this).parents('.widget-content').find('.wpsbc-chosen-wrap').addClass('wpsbc-element-disabled');

    });

    jQuery(document).on('widget-updated widget-added', function () {
        if (typeof $.fn.chosen != 'undefined') {
            $(".chosen-container").remove();
            $('.wpsbc-chosen').chosen();
        }
    });


    /**
     * Builds the shortcode for the Search Widget and inserts it in the WordPress text editor
     *
     */
    $(document).on('click', '#wpsbc-insert-shortcode-search-widget', function (e) {

        e.preventDefault();

        // Begin shortcode
        var shortcode = '[wpsbc-search ';

        // Add the calendars shortcode attribute
        var calendars = $('#modal-add-search-widget-shortcode-calendars').val();

        if (calendars == '1')
            shortcode += 'calendars="all" ';

        // For selected calendars we want to maintain the order selected by the user, so grabbing
        // the value from the multiple select won't be enough, as this does not maintain the order
        else {

            var $select = $('#modal-add-search-widget-shortcode-selected-calendars');
            var select_val = '';

            $select.siblings('.chosen-container').find('li.search-choice a').each(function () {

                select_val += $select.find('option').eq($(this).data('option-array-index')).val() + ','

            });

            // Trim the last comma
            select_val = select_val.slice(0, -1);

            shortcode += 'calendars="' + select_val + '" ';

        }

        // Add the rest of the attributes
        $('#wpsbc-modal-add-calendar-shortcode.wpsbc-active .wpsbc-shortcode-generator-field-search-widget').each(function () {

            shortcode += $(this).data('attribute') + '="' + $(this).val() + '" ';

        });

        // End shortcode
        shortcode = shortcode.trim();
        shortcode += ']';

        window.send_to_editor(shortcode);

        $(this).closest('.wpsbc-modal').find('.wpsbc-modal-close').first().trigger('click');

    });

    /**
     * Calendar Notes - Add Note
     * 
     */
    $("#wpsbc-calendar-add-note").click(function (e) {
        e.preventDefault();
        $button = $(this);
        $note = $button.siblings('#wpsbc-calendar-note-content')

        $button.prop('disabled', true);
        $note.prop('disabled', true);

        // Prepare the data
        var data = {
            action: 'wpsbc_calendar_add_note',
            calendar_id: $('input[name="calendar_id"]').val(),
            note: $note.val(),
        }

        // Send the request
        $.post(ajaxurl, data, function (response) {

            $button.prop('disabled', false);
            $note.prop('disabled', false).val('');

            if (response != '0') {
                $(".wpsbc-calendar-notes").prepend(response);
            }
        });
    })

    /**
     * Calendar Notes - Remove Note
     * 
     */
    $(document).on('click', '.wpsbc-calendar-note-remove', function (e) {
        e.preventDefault();

        if (!confirm("Are you sure you want to delete this note?"))
            return false;

        var $button = $(this);
        var $wrap = $button.parents('.wpsbc-calendar-note');

        $wrap.css('opacity', 0.4);

        // Prepare the data
        var data = {
            action: 'wpsbc_calendar_remove_note',
            calendar_id: $('input[name="calendar_id"]').val(),
            note_id: $button.data('note-id'),
        }

        // Send the request
        $.post(ajaxurl, data, function () {
            $wrap.remove();
        });

    });

});
