jQuery(function($){
  
  $("document").ready(function(){
    $(".menu-item").on("click", "a.item-edit", function(){
      var that = $(this),
          parent = that.parents(".menu-item").eq(0);

      parent.find(".icp-auto").iconpicker();
    });

    $(".add-to-menu").on("click", ".submit-add-to-menu", function(){
      setTimeout( function(){
        $('body').find(".icp-auto").last().iconpicker(); 
      }, 400);
    });
  });
 

  // Set all variables to be used in scope
  var frame,
      metaBox = $('ul.menu'), // Your meta box id here
      addImgLink = metaBox.find('.kd_nav_change_img'),
      delImgLink = metaBox.find( '.kd_nav_remove_img'),
      imgContainer = '',
      imgIdInput = '';
  
  // ADD IMAGE LINK
  addImgLink.on( 'click', function( event ){

    event.preventDefault();

    var obj_parent = $(this).parents('.input-group').eq(0);
    imgContainer = obj_parent.find(".kd_nav_img_preview");
    imgIdInput = obj_parent.find('.kd_image_upload');
    
    // If the media frame already exists, reopen it.
    if ( frame ) {
      frame.open();
      return;
    }
   
    // Create a new media frame
    frame = wp.media({
      title: 'Select or Upload Media Of Your Chosen Persuasion',
      button: {
        text: 'Use this media'
      },
      multiple: false  // Set to true to allow multiple files to be selected
    });

    
    // When an image is selected in the media frame...
    frame.on( 'select', function() {
      
      // Get media attachment details from the frame state
      var attachment = frame.state().get('selection').first().toJSON();
      console.log(attachment );

      // Send the attachment URL to our custom image input field.
      imgContainer.html( '<img src="'+ attachment.sizes.thumbnail.url +'" alt="" style="max-width:100%;"/>' );

      // Send the attachment id to our hidden input
      imgIdInput.val( attachment.id );

      // Hide the add image link
      addImgLink.addClass( 'hidden' );

      // Unhide the remove image link
      delImgLink.removeClass( 'hidden' );
    });

    // Finally, open the modal on click
    frame.open();
  });
  
  
  // DELETE IMAGE LINK
  delImgLink.on( 'click', function( event ){

    event.preventDefault();

    var obj_parent = $(this).parents('.input-group').eq(0);
    imgContainer = obj_parent.find(".kd_nav_img_preview");
    imgIdInput = obj_parent.find('.kd_image_upload');

    // Clear out the preview image
    imgContainer.html( '' );

    // Un-hide the add image link
    addImgLink.removeClass( 'hidden' );

    // Hide the delete image link
    delImgLink.addClass( 'hidden' );

    // Delete the image id from the hidden input
    imgIdInput.val( '' );

  });

});