/*
 * This file is for WP image widget
 * 
 * Displays the image uploader for selecting an image.
**/
(function ($) {
    "use strict";

    $(document).ready(function () {

        /**
        * Callback function for the 'click' event of the 'Set Image'
        * anchor in its meta box.
        *
        * Displays the media uploader for selecting an image.
        * 
        * @since 0.1.0
        */

        var renderMediaUploader = function (id) {


            var file_frame, image_data, json;

            /**
            * If an instance of file_frame already exists, then we can open it
            * rather than creating a new instance.
            */
            if (undefined !== file_frame) {

                file_frame.open();
                return;

            }

            /**
            * If we're this far, then an instance does not exist, so we need to
            * create our own.
            *
            * Here, use the wp.media library to define the settings of the Media
            * Uploader. We're opting to use the 'post' frame which is a template
            * defined in WordPress core and are initializing the file frame
            * with the 'insert' state.
            *
            * We're also not allowing the user to select more than one image.
            */
            file_frame = wp.media.frames.file_frame = wp.media({
                frame: 'post',
                state: 'insert',
                multiple: false
            });

            /**
            * Setup an event handler for what to do when an image has been
            * selected.
            *
            * Since we're using the 'view' state when initializing
            * the file_frame, we need to make sure that the handler is attached
            * to the insert event.
            */
            file_frame.on('insert', function () {
                $ = jQuery;

                // Read the JSON data returned from the Media Uploader
                json = file_frame.state().get('selection').first().toJSON();

                // First, make sure that we have the URL of an image to display
                if (0 > $.trim(json.url.length)) {
                    return;
                }

                // After that, set the properties of the image and display it
                $(id + ' .media-upload-container')
                    .children('img.wp-post-image')
                        .attr('src', json.url)
                        .attr('alt', json.caption)
                        .attr('title', json.title)
                    .show()
                    .parent()
                    .removeClass('hidden');

                // Next, hide the anchor responsible for allowing the user to select an image
                $(id + ' .media-upload-container')
                    .prev()
                    .hide();

                // Display the anchor for the removing the background image
                $(id + ' .media-upload-container')
		            .next()
		            .show()

                // Store the image's information into the meta data fields. 
                $(id + ' .media').val(json.url)
                    .trigger("change"); // Val does not fire the change event, then trigger it.
            });

            // Now display the actual file_frame
            file_frame.open();

        }

        /**
        * Callback function for the 'click' event of the 'Remove Image'
        * anchor in its meta box.
        *
        * Resets the meta box by hiding the image and by hiding the 'Remove
        * Image' container.
        *
        * @param    object    $    A reference to the $ object
        * @since    0.2.0
        */
        var resetUploadForm = function (id) {

            // First, we'll hide the image
            $(id + ' .media-upload-container')
                .children('img.wp-post-image')
                .hide();

            // Then display the previous container
            $(id + ' .media-upload-container')
                .prev()
                .show();

            // Finally, we add the 'hidden' class back to this anchor's parent
            $(id + ' .media-upload-container')
                .next()
                .hide()
                .addClass('hidden');

            // Finally, we reset the meta data input fields
            $(id + ' .media-upload-meta')
		        .children()
		        .val('');

        }
        /**
        * Checks to see if the input field for the thumbnail source has a value.
        * If so, then the image and the 'Remove featured image' anchor are displayed.
        *
        * Otherwise, the standard anchor is rendered.
        *
        * @param    object    $    A reference to the $ object
        * @since    1.0.0
        */
        var renderFeaturedImage = function (id) {

            /* If a thumbnail URL has been associated with this image
            * Then we need to display the image and the reset link.
            * Also, we set the Id variable and for the image widget.
            */

            if ('' !== $.trim($(id + ' .media').val())) {
                $(id + ' .media-upload-container').removeClass('hidden');

                $(id + ' .choose-image')
                    .parent()
                    .hide();

                $(id + ' .remove-image')
                    .parent()
                    .removeClass('hidden');

            }

        }


        /**
        * This media uploader is for category page.
        */

        $(".form-field .media-upload-wrapper").each(function () {

            var category_id = $(this).attr('id');

            $(function () {

                $('#' + category_id + ' .choose-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Display the media uploader
                    renderMediaUploader('#' + category_id);

                });

                $('#' + category_id + ' .remove-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Remove the image, toggle the anchors
                    resetUploadForm('#' + category_id);

                });

                $('#addtag' + ' .button').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Remove the image, toggle the anchors
                    resetUploadForm('#' + category_id);

                });

                renderFeaturedImage('#' + category_id);

            });
        });


        /**
        * This media uploader is for metabox
        */

        $(".inside .media-upload-wrapper").each(function () {

            var metabox_id = $(this).attr('id');

            $(function () {

                $('#' + metabox_id + ' .choose-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Display the media uploader
                    renderMediaUploader('#' + metabox_id);

                });

                $('#' + metabox_id + ' .remove-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Remove the image, toggle the anchors
                    resetUploadForm('#' + metabox_id);

                });

                renderFeaturedImage('#' + metabox_id);

            });
        });


        /**
        * This media uploader is for widget admin page.
        */

        $("#widgets-right .media-upload-wrapper").each(function () {

            var widget_id = $(this).attr('id');

            $(function () {

                $('#' + widget_id + ' .choose-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Display the media uploader
                    renderMediaUploader('#' + widget_id);

                });

                $('#' + widget_id + ' .remove-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Remove the image, toggle the anchors
                    resetUploadForm('#' + widget_id);

                });

                renderFeaturedImage('#' + widget_id);

            });
        });


        /**
        * This media uploader is for widget customizer admin page.
        */
        $(document).on('widget-added widget-updated', function (evt, $updatedWidget) {


            var widget_id_part = $updatedWidget.find(' .widget-id').val();
            var widget_id = 'widget-' + widget_id_part + '-widget_image';

            $(function () {

                $('#' + widget_id + ' .choose-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Display the media uploader
                    renderMediaUploader('#' + widget_id);

                });


                $('#' + widget_id + ' .remove-image').on('click', function (evt) {
                    // Stop the anchor's default behavior
                    evt.preventDefault();
                    // Remove the image, toggle the anchors
                    resetUploadForm('#' + widget_id);

                });

                renderFeaturedImage('#' + widget_id);

            });

        });

    });

})(jQuery);