jQuery(document).ready(function(){

	var framePortfolioUpload; // WP Media holder;
	
	jQuery('.cm-js-meta-slider-preview').sortable({
		update: function( event, ui ) {
			updatePortfolioSliderAssets();
		}
	});
	
	jQuery(document).on('click', '.cm-delete_btn', function(e) {
		e.preventDefault();
		
		// Get current selected item
		item = jQuery(this).parent();
		
		//Remove item from the list
		jQuery(item).remove();
		
		// Update assets list
		updatePortfolioSliderAssets();
	});
	
	jQuery(document).on('click', '.otw-add-portfolio-image', function(e) {
		
		e.preventDefault();
		
		if( framePortfolioUpload ) {
			framePortfolioUpload.open();
			return;
		}
		
		framePortfolioUpload = wp.media({
			id: 'otw-cm-portfolio-media-upload',
			multiple: false,
			// Tell the modal to show only images.
			library: {
				type: 'image'
			},
			// Customize the submit button.
			button: {
				// Change close: false, in order to prevent window to close on selection
				close: true
			}
		});
		
		framePortfolioUpload.on( 'select', function() {
			var attachements = framePortfolioUpload.state().get('selection').first().id;
			var attachementURL = wp.media.attachment( attachements ).attributes.url;
			
			if( 1 ) {
				
				imgTAG = '<li class="cm-slider__item" data-src="'+attachementURL+'">';
				imgTAG += '<a href="#" class="cm-delete_btn"></a>';
				imgTAG += '<img src="'+attachementURL+'" width="100" />';
				imgTAG += '</li>';
				
				jQuery('.cm-js-meta-slider-preview').append( imgTAG ); //Display IMG
				updatePortfolioSliderAssets();
				
			} else {
				// Create HTML for visual effect
				var imgTAG = '<img src="'+attachementURL+'" width="150" />';
				// Append HTML for visual preview
				jQuery('.cm-js-img-preview').html( imgTAG ); //Display IMG
				
				// Add Image to Hidden input - save to DB
				jQuery('.cm-js-img-url').val( attachementURL );
			}
		})
		
		framePortfolioUpload.open();
		
		return false;
	} );
} );

function updatePortfolioSliderAssets() {
	var imagesArray = new Array();
	jQuery('.cm-slider-preview > .cm-slider__item').each(function( item, value) {
		imagesArray.push( jQuery(value).data('src') );
	});
	// Add Array to hidden input
	jQuery('.cm-js-img-slider-url').val( imagesArray );
}