jQuery(function($){
	$(document).ready(function() {
		
		
		// **************************************************************
		// tooltipster
		// **************************************************************
		function imageTooltipster() {
			$('.wpex-gmb-tooltip').tooltipster({ delay: 0 });
		} imageTooltipster();
	
	
		
		// **************************************************************
		// image removal function - fired at load and after AJAX
		// **************************************************************
		function imageRemoval() {
	
			jQuery('a.wpex-gmb-remove').on('click', function(event) {
				
				var image	= jQuery(this).attr('rel');
				var parent	= jQuery('form#post input#post_ID').prop('value');
				
				var data = {
					action: 'gallery_remove',
					image: image,
					parent: parent
				};
	
				jQuery.post(ajaxurl, data, function(response) {
					var obj;
					try {
						obj = jQuery.parseJSON(response);
					}
					catch(e) { // bad JSON catch
						// add some error messaging ?
						}
	
					if(obj.success === true) { // it worked. AS IT SHOULD.
						jQuery('div#wpex_gmb').find('div.wpex-gmb-image-wrapper').replaceWith(obj.gallery);
						imageRemoval();
						imageTooltipster();
					}
					else { // something else went wrong
						// add some error messaging?
					}
				});
				
				return false;
				
			});
	
		} imageRemoval();
	
	
	
		// **************************************************************
		// AJAX function resetting the gallery with changes
		// **************************************************************
		function imageGalleryUpdate() {
		
				var parent	= $('form#post input#post_ID').prop('value');	
				var data = {
					action: 'refresh_metabox',
					parent: parent
				};	
				jQuery.post(ajaxurl, data, function(response) {
					var obj;
					try {
						obj = jQuery.parseJSON(response);
					}				
					 // bad JSON catch
					catch(e) {
						alert('Bad JSON Catch');
					}
					// Success
					if(obj.success === true) {
						$('div#wpex_gmb').find('div.wpex-gmb-image-wrapper').replaceWith(obj.gallery);
						imageRemoval();
						$('.wpex-gmb-tooltip').tooltipster({ delay: 0 });
					}				
					// Something went wrong...
					else { }
				});	
		}
		
		$('div#wpex_gmb input#update-gallery').on('click', function(event) {
			imageGalleryUpdate();
		});
		
	
	
		// **************************************************************
		// WP Gallery
		// **************************************************************
		  if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) {
			  
			  // Open media library
			  $('#wpex-gmb-manage-btn').click(function() {
				  wp.media.editor.open();
				  return false;
			  });
			  	  
			  
			  // update images on window close
			  wp.media.view.Modal.prototype.on('close', function(){
				  imageGalleryUpdate();
			  });
			  
			  
		  }
	  
	  
	  

	 });
});