

<?php $__env->startSection('title'); ?>
	
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>

  <div class="container-fluid">

		<div class="row">
			<div class="col-xs-12">
				<section id="message-banner" class="panel panel-primary">
					<header class="panel-heading">
						<h2>
							GALLERY \ ALBUM \ <?php echo e($album->name); ?>

						</h2>
					</header>

					<div class="panel-body">
						<div class="form-group">

		    			
		    			<div class="upload-drop-zone" id="drop-zone">
		    				<div class="caption-wrapper">
	          			<p class="caption"><?php echo app('translator')->getFromJson('backend.drag-and-drop-files-here'); ?></p>
	          			<p><?php echo app('translator')->getFromJson('backend.supported-file-type'); ?>: PNG/JPG </p>
	      				</div>
	      				<input type="file" name="image" title="<?php echo app('translator')->getFromJson('backend.drag-and-drop-files-here'); ?>" id="imageUpload">
	      			</div>
	      			

        			
        			<div class="progress" id="progress">
						    <div class="progress-bar bg-danger" role="progressbar" style="width: 0%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
						    </div>
							</div>
							

		    		</div>

						
		    		<div class="gallery-wrapper">

		    			
		    			<ol class="sortable gallery" id="gallery">

		    				
		    				<?php $__currentLoopData = $album->galleries->sortBy('order'); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $picture): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
			    				<li class="gallery-item" s-val="<?php echo e($picture->id); ?>">
			    					<div class="item-wrapper">
			    						<div class="image">
					    					<img src="<?php echo e(asset($storage_url.'img/gallery/'.$album->slug.'/'.str_replace('.', '_tn.', $picture->path))); ?>" alt="">
			    						</div>
			    						<div class="caption">
			    							<h5 class="item-caption"><?php echo e(isset($picture->caption) ? $picture->caption : ''); ?></h5>
			    						</div>
			    						<div class="controls">
			    							<a class="btn btn-default btn-xs btn-edit" s-id="<?php echo e($picture->id); ?>">
			    								<i class="fa fa-pencil"></i>
			    							</a>
			    							<a class="btn btn-danger btn-xs btn-delete" s-id="<?php echo e($picture->id); ?>">
			    								<i class="fa fa-trash"></i>
			    							</a>
			    						</div>
			    					</div>
			    				</li>
			    			<?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
			    			

		    			</ol>
		    			

		    		</div>
		    		

					</div>

				</section>
			</div>
		</div>

	</div>

	<?php echo $__env->make('backend.album.modal', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>

<?php $__env->stopSection(); ?>

<?php $__env->startSection('script'); ?>
	<script type="text/javascript">

	  /*======= Sortable ========*/

	  var adjustment;
	  var album_id = <?php echo e($album->id); ?>;
	  var album_name = '<?php echo e($album->slug); ?>';
	  var image_url = '<?php echo e(asset($storage_url.'img/gallery/'.$album->slug)); ?>';
	  var current_list = '';
	  var appLocale = '<?php echo e(config('app.locale')); ?>';


		$("ol.sortable").sortable({
	    delay: 100,
	    group: 'sortable',
	    pullPlaceholder: false,

	    // animation on drop
	    onDrop: function  ($item, container, _super) {
	      loading.open();

	      var $clonedItem = $('<li/>').css({height: 0});
	      $item.before($clonedItem);
	      $clonedItem.animate({'height': $item.height()});

	      $item.animate($clonedItem.position(), function  () {
	        $clonedItem.detach();
	        _super($item, container);
	      });
	      $clonedItem.remove();

	      var list = [];

        $("ol.sortable").children().each(function(){
          list.push($(this).attr("s-val"));
	      });

	      console.log(list);

	      $.ajax({
	        headers: {
	              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
	        },
	        url: route('galleries.reorder'),
	        type: 'POST',
	        data: {
            list: list,
	        },
	        error: function(msg) {
		        if( msg.status === 401 ) {
		          $(location).prop('pathname', 'auth/login');
		        }
		        if ( msg.status === 413 ) {
		          toastr.error("File is too large!");
		        }
		        if ( msg.status === 422 ) {
		          var errors = msg.responseJSON;
		          $.each( errors.errors, function(key, value) {
		              toastr.error(value[0]);
		          });
		        } else {
		          toastr.error(msg.statusText);
		          console.log(msg);
		        }
	        },
	        success: function (msg) {
	          toastr.success(msg);
	        },
	        always: function() {
	        	loading.close();
	        }
	      })
	    },

	    // set $item relative to cursor position
	    onDragStart: function ($item, container, _super) {
	      var offset = $item.offset(),
	          pointer = container.rootGroup.pointer;

	      adjustment = {
	        left: pointer.left - offset.left,
	        top: pointer.top - offset.top
	      };

	      _super($item, container);
	    },
	    onDrag: function ($item, position) {
	      $item.css({
	        left: position.left - adjustment.left,
	        top: position.top - adjustment.top
	      });
	    },
	  });
	  /*======= /. Sortable ========*/



	  /*======= /. Uploader ========*/

		$('#imageUpload').fileupload({
        url: route('galleries.store'),
        formData: {album: album_id, subfolder: album_name},
        headers: {
	      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
			},
        error: function(msg) {
          if( msg.status === 401 ) {
            $(location).prop('pathname', 'auth/login');
          }
          if ( msg.status === 422 ) {
            var errors = msg.responseJSON;
            $.each( errors.errors, function(key, value) {
                toastr.error(value[0]);
            });
          } else {
          	toastr.error(msg.statusText);
          	console.log(msg);
          }
        },
        success: function (msg) {
          toastr.success(msg.message);
          console.log(msg);
          $("#gallery").append(msg.list);
        },
        progressall: function (e, data) {
          var progress = parseInt(data.loaded / data.total * 100, 10);
          $('#progress .progress-bar').css(
            'width',
            progress + '%'
          );
        },
        complete: function() {
        	$('#progress .progress-bar').css(
              'width', '0%'
          );
        },
        limitConcurrentUploads: 1,
        sequentialUploads: true,
    }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

	  /*======= /. Uploader ========*/


	  /*======= Edit =======*/
		$(document).on('click', 'a.btn-edit', function(e) {
	  	e.preventDefault();
	  	loading.open();
	  	var mGallery = $('#mGallery');
	  	var storage_url = '/'+$("meta[name=storage_url").attr("content");
	  	var slug = $("#album_name").val();

	  	var id = $(this).attr('s-id');
	  	var url_update = route('galleries.update', id);

	  	current_list = $(this).closest('li.gallery-item');

	  	$.ajax({
        headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: route('galleries.edit', id),
        type: 'GET',
        data: {
          _method: 'GET',
        },
        error: function(msg) {
	        if( msg.status === 401 ) {
	          $(location).prop('pathname', 'auth/login');
	        }
	        if ( msg.status === 413 ) {
	          toastr.error("File is too large!");
	        }
	        if ( msg.status === 422 ) {
	          var errors = msg.responseJSON;
	          $.each( errors.errors, function(key, value) {
	              toastr.error(value[0]);
	          });
	        } else {
	          toastr.error(msg.statusText);
	          console.log(msg);
	        }
        },
        success: function (msg) {
        	console.log(msg);
          mGallery.find("img").attr("src", image_url+'/'+msg.path);
          mGallery.find('form').attr('action', url_update);

          var trans = msg.translations;

          for ( var key in trans ) {
					  $("input[name='caption["+key+"]']").val(trans[key].caption);
					  $("input[name='alt["+key+"]']").val(trans[key].alt);
					}

          mGallery.modal("show");
        },
        always: function() {
        	loading.close();
        }
      })
	  });

	  /*======= Delete ========*/

	  $(document).on('click', 'a.btn-delete', function(e) {
	  	e.preventDefault();
	  	var component = $(this).closest('li');
	  	var id = $(this).attr('s-id');
	  	if( !confirm('Are you sure want to delete this data?')) {
        e.preventDefault();
      } else {
		  	loading.open();
        $.ajax({
	        headers: {
	              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
	        },
	        url: route('galleries.destroy', id),
	        type: 'POST',
	        data: {
	          _method: 'DELETE',
	        },
	        error: function(msg) {
		        if( msg.status === 401 ) {
		          $(location).prop('pathname', 'auth/login');
		        }
		        if ( msg.status === 413 ) {
		          toastr.error("File is too large!");
		        }
		        if ( msg.status === 422 ) {
		          var errors = msg.responseJSON;
		          $.each( errors.errors, function(key, value) {
		              toastr.error(value[0]);
		          });
		        } else {
		          toastr.error(msg.statusText);
		          console.log(msg);
		        }
	        },
	        success: function (msg) {
	          toastr.success(msg);
	          component.fadeOut(350).remove();
	        },
	        always: function() {
	        	loading.close();
	        }
	      })
      }
	  });

	  /*===== Submit Form =====*/
    $(".ajax-submit").on("submit", function(e) {
      e.preventDefault();
      loading.open();
      var form = $(this),
          url = form.attr("action");

      // Check for file inputs.
      if (form.find('[type=file]').length) {

          // If found, prepare submission via FormData object.
          var input       = form.serializeArray(),
              data        = new FormData(),
              contentType = false;

          // Append input to FormData object.
          $.each(input, function(index, input) {
              data.append(input.name, input.value);
          });

          // Append files to FormData object.
          $.each(form.find('[type=file]'), function(index, input) {
              if (input.files.length == 1) {
                  data.append(input.name, input.files[0]);
              } else if (input.files.length > 1) {
                  data.append(input.name, input.files);
              }
          });
      }

      // If no file input found, do not use FormData object (better browser compatibility).
      else {
        var data        = form.serialize(),
            contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
      }

      //Submit request
      $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: 'json',
        contentType: contentType,
        processData: false,

        error: function(msg) {
          if( msg.status === 401 ) {
            $(location).prop('pathname', 'auth/login');
          }
          if ( msg.status === 422 ) {
            var errors = msg.responseJSON.errors;
            $.each( errors, function(key, value) {
                toastr.error(value);
            });

            console.log(msg);
          }
          if ( msg.status === 500 ) {
            toastr.error(msg.responseJSON.message);
          }
          else {
            console.log(msg);
            toastr.error(msg.responseText);
          }
        },
        success: function (msg) {
          toastr.success(msg);
          var caption = $("input[name='caption["+appLocale+"]'").val();
          current_list.find('.item-caption').text(caption);
          $('.modal').modal('hide')
        },
        always: function() {
        	loading.close();
        },
      });
    });

	</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.masterBackend', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>