@if(!defined('LOAD_MODAL'))

	@push('js')

		<script>
			function openModal(title, form_id, url_open, url_save, callback, size, no_confirm, buttons, callback_after_loaded) {
				var status = 0;
				var dialog = bootbox.dialog({
					title: title,
					message: '<p><i class="fa fa-spin fa-spinner"></i> {{ __('loading') }} ...</p>',
					size: size ? size : 'large',
					scrollable: true,
					buttons: buildModalButtons(form_id, no_confirm, buttons)
				});
									
				dialog.init(function() {
					$.get(url_open, function(data) {
						dialog.find('.bootbox-body').html(data);
						if (callback_after_loaded) {
							eval(callback_after_loaded);
						}
						if (typeof(url_save) !== 'undefined') {
							handlePostModal(form_id,url_save, callback);
						}
					});
				});
			}

			function changeModalContent(dialog, url, callback) {
				dialog.init(function() {
					$.get(url, function(data) {
						dialog.find('.bootbox-body').html(data);
						if (callback) {
							eval(callback);
						}
					});
				});	
			}

			function viewModal(url, size, title) {
				var dialog = bootbox.dialog({
					title: title ? title : 'Web viewer',
					message: '<iframe style="border:0;" src="' + url + '" height="400" width="100%"></iframe>',
					size: size ? size : 'xl',
					scrollable: true,
				});
			}

			function viewWindow(url, size, title) {
				var width = (size == 'sm') ? 400 : 600;
				var title  = title ? title : 'Web viewer';
				window.open(url,title,"menubar=no, status=no, scrollbars=no, menubar=no, width=" + width + ", height=400");
			}

			function buildModalButtons(form_id, no_confirm, buttons) {
				if (!no_confirm) {
					var buttons = {
						cancel: {
							label: '{{ __('Annuler') }}',
							className: 'btn-secondary'
						},
						confirm: {
							label: '{{ __('Sauver') }}',
							className: 'btn-success',
							callback: function() {
								submitModal(form_id);
							}
						},
					};
				}
				return buttons; 
			}

			function submitModal(form_id) {
				if (typeof(tinyMCE) != 'undefined') {
					tinyMCE.triggerSave();
				}
				getModalForm(form_id).trigger('submit');
				status = 1;
			}

			function handlePostModal(form_id, url_save, callback) {
				getModalForm(form_id).off('submit').on('submit', function(e) {
					e.preventDefault();
					var formData = new FormData(this);
					$.ajax({
						url: url_save,
						type: 'POST',
						data: formData,
						success: function (data) {
							if (callback) {
								eval(callback);
							}
						},
						cache: false,
						contentType: false,
						processData: false
					});
				});
			}

			function getModalForm(form_id) {
				var $form = $(form_id);
				if (! $form.length) {
					$form = $('form' + form_id);
				}

				return $form;
			}
		</script>
	@endpush

	@php(define('LOAD_MODAL', true))
@endif
