
<patTemplate:tmpl name="pageoutput" unusedvars="strip">
<style>
#dropzone {
	border-width:5px;
	border-style:dashed;
	border-color:#333;
    height: 100px;
    line-height: 100px;
    text-align: center;
    font-weight: bold;
}
#dropzone.in {
    width: 100%;
    height: 200px;
    line-height: 200px;
    font-size: larger;
}
#dropzone.hover {
    background: lawngreen;
}
#dropzone.fade {
    -webkit-transition: all 0.3s ease-out;
    -moz-transition: all 0.3s ease-out;
    -ms-transition: all 0.3s ease-out;
    -o-transition: all 0.3s ease-out;
    transition: all 0.3s ease-out;
    opacity: 1;
}

.popover{
    min-width: 300px ! important;
    }

</style>

<h2 class="page-header">{TITLE}</h2>
<p class="alert alert-info">{_JOMRES_MEDIA_CENTRE_INSTRUCTIONS}</p>
<p>{_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_GENERIC}</p>

<hr/>

<div class="panel panel-default">
	<div class="panel-heading">
        <h2 class="panel-title">{_JOMRES_MEDIA_CENTRE_RESOURCE}</h2>
    </div>
    <div class="panel-body">
        <div class="col-md-10">
             <p>{RESOURCE_TYPE_OPTIONS} <span id="resource_id_dropdown"><input type="hidden" id="resource_id" value="" /></span></p>
        </div>
        <div class="col-md-2">
            <a href="{DEFAULT_PREVIEW_LINK}" data-remote="false" data-toggle="modal" data-target="#previewModal" class="btn btn-default btn-lg" id="image_preview_button">
                <i class="fa fa-link" aria-hidden="true"></i>
               {_JOMRES_FRONT_PREVIEW}
            </a>
            <button type="button" class="btn btn-info" data-toggle="popover" data-placement="left" title="{_JOMRES_FRONT_PREVIEW}" data-trigger="focus" data-content="{_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_PREVIEW}"><i class="fa fa-info" aria-hidden="true"></i></button>
        </div>
    </div>
	<div class="panel-footer">
        <patTemplate:tmpl name="notes" unusedvars="strip" type="simpleCondition" requiredVars="note">
            <button type="button" class="btn btn-info" data-toggle="popover" title="" data-trigger="focus" data-content='{NOTE}'><i class="fa fa-info" aria-hidden="true"></i></button>
        </patTemplate:tmpl>
    </div>
</div>

<div class="row">
	<div class="col-md-7">
		<div class="page-header">
			<h4>{_JOMRES_MEDIA_CENTRE_RESOURCE_ALREADY_UPLOADED}</h4>
		</div>
		<div id="existing_images"></div>
	</div>
	<div class="col-md-5">
		<div class="well well-small">
			<div id="tour_target_mediacentre_uploadcontrols"></div>
			<div id="tour_target_mediacentre_selectedimages"></div>

			<div class="page-header">
                <h4>{HUPLOAD_FORM}</h4>
            </div>
           
			<!-- The fileinput-button span is used to style the file input field as button -->
			<span class="btn btn-success fileinput-button">
				<i class="fa fa-plus"></i>
				<span>{_JOMRES_MEDIA_CENTRE_BUTTON_ADD}</span>
				<!-- The file input field used as target for the file upload widget -->
				<input id="fileupload" type="file" name="files[]" multiple>
			</span>
			<div class="btn btn-default" id="clearbutton">
				<i class="fa fa-minus"></i>
				{_JOMRES_MEDIA_CENTRE_CLEAR}
			</div>
			<span class="btn btn-primary" id="upload_all">
				<i class="fa fa-upload"></i>
				{_JOMRES_MEDIA_CENTRE_BUTTON_UPLOAD_ALL}
			</span>
            
             <button type="button" class="btn btn-info" data-toggle="popover" data-placement="left" title="{_JOMRES_COM_A_UPLOADS_FILESIZE}" data-trigger="focus" data-content="{_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_FILESIZE_PRE}{MAX_UPLOAD_SIZE}{_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_FILESIZE_POST} {_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_LIMITATIONS} {_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_IMAGE_RESOLUTION_PRE}{WIDTH_PIXELS} {_JOMRES_MEDIA_CENTRE_INSTRUCTIONS_IMAGE_RESOLUTION_POST}"><i class="fa fa-info" aria-hidden="true"></i></button>
			<!--<button type="button" class="btn btn-danger delete">
				<i class="icon-trash"></i>
				<span>Delete</span>
			</button>
			<input type="checkbox" class="toggle">-->
			<div class="clearfix">&nbsp;</div>
			<!-- The global progress bar -->
			<div id="progress" class="progress">
				<div class="bar"></div>
			</div>
			<div id="dropzone" class="fade">{_JOMRES_MEDIA_CENTRE_DRAGNDROP}</div>
			<!-- The container for the uploaded files -->
			<!--<table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>-->
			
			<div id="files" class="files"></div>
		</div>
	</div>
</div>

<script>
var ajax_url = "{AJAX_URL}";
<patTemplate:tmpl name="preview_links" unusedvars="strip" type="simpleCondition" requiredVars="resource_type">
var preview_link_{RESOURCE_TYPE} = '{PREVIEW_LINK}';
</patTemplate:tmpl>

jomresJquery(function () {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = ajax_url + '&task=media_centre_handler',
        uploadButton = jomresJquery('<button/>')
            .addClass('btn btn-primary start')
            .prop('disabled', true)
            .text('Processing...')
            .on('click', function () {
                var $this = jomresJquery(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('Abort')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });

				// Vince
				var resource_types = jomresJquery('#resource_types');
				var resource_id    = jomresJquery('#resource_id');
				data.formData = {resource_type: resource_types.val() , resource_id:  resource_id.val() };
                data.submit().always(function () {
                    $this.remove();
                });
				
            });
    jomresJquery('#fileupload').fileupload({
		dropZone: jomresJquery('#dropzone'),
        url: url,
        dataType: 'json',
        autoUpload: false,
        acceptFileTypes: /(\.|\/){ALLOWED_FILE_TYPES}$/i,
        maxFileSize: 5000000, // 5 MB
        // Enable image resizing, except for Android and Opera,
        // which actually support image resizing, but fail to
        // send Blob objects via XHR requests:
        disableImageResize: false,
		imageMaxWidth: {MAX_WIDTH}-1,
		imageMaxHeight: {MAX_WIDTH}-1,
        previewMaxWidth: 100,
        previewMaxHeight: 100,
        previewCrop: true
    }).on('fileuploadadd', function (e, data) {
        data.context = jomresJquery('<div/>').appendTo('#files');
        jomresJquery.each(data.files, function (index, file) {
            var node = jomresJquery('<p/>')
                    .append(jomresJquery('<span/>').text(file.name));
					//.css({ float: "left" })
					//.addClass( "well well-small" );
					 
            if (!index) {
                node
                    .append('<br>')
                    .append(uploadButton.clone(true).data(data));
            }
			node.addClass('alert');
            node.appendTo(data.context);
			
        });
		
		jomresJquery('#files').show("slow");
		
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = jomresJquery(data.context.children()[index]);
        if (file.preview) {
            node
                .prepend('<br>')
                .prepend(file.preview);
        }
        if (file.error) {
            node
                .append('<br>')
                .append(file.error);
        }
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('{_JOMRES_MEDIA_CENTRE_BUTTON_UPLOAD}')
                .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        jomresJquery('#progress .bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
		jomresJquery.each(data.files, function (index, file) {
			jomresJquery(data.context.children()[index]).attr('id', file.random_id);
			jomresJquery('#'+file.random_id).parent().addClass('uploaded');
			jomresJquery('#'+file.random_id).addClass('alert alert-success');
			jomresJquery('#progress .bar').css( 'width', '0%' );
			if (file.hasOwnProperty ('error'))
				{
				jomresJquery.each(data.files, function (index, file) {
				var error = '<div class="alert alert-error">' + file.error + '</div>';
				jomresJquery(data.context.children()[index])
					.append('<br>')
					.append(error);
					});
				}
			else
				{
				/*
				var delete_link = '<a href="javascript:void(0);" class="btn btn-danger" onclick="delete_file(\''+file.deleteUrl+'\' , \''+file.random_id+'\')">{_JOMRES_MEDIA_CENTRE_BUTTON_DELETE}</a>';
				var view_link = '<a href="'+file.url+'" target="_blank" class="btn btn-primary">{_JOMRES_MEDIA_CENTRE_BUTTON_VIEW}</a>';

				var links = view_link + " " + delete_link;
				
				jomresJquery(data.context.children()[index])
					.append(links);
				*/	
				jomresJquery(data.context.children()[index])
					.fadeOut("normal", function() {
						jomresJquery(this).remove();
						});
				
				get_existing_images();
				}
			//
			});
		
    }).on('fileuploadfail', function (e, data) { // This doesn't seem to work, moved to up a few lines
        jomresJquery.each(data.files, function (index, file) {
            var error = jomresJquery('<span/>').text(file.error);
            jomresJquery(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !jomresJquery.support.fileInput)
        .parent().addClass(jomresJquery.support.fileInput ? undefined : 'disabled');
	
});

function get_resource_ids_for_resource_type(resource_type)
	{
	hide_uploaded();
	jomresJquery('#existing_images').fadeOut();
	jomresJquery.get(ajax_url + '&task=media_centre_resources_ajax&resource_type=' + resource_type,
		function (data) {
			if (data != '')
				{
				populateDiv ( 'resource_id_dropdown' , data );
				}
			else
				{
				populateDiv ( 'resource_id_dropdown' , '<input type="hidden" id="resource_id" value="" />' );
				}
		get_existing_images();
		});
	}
	
jomresJquery( "#clearbutton" ).click(function() {
	jomresJquery("#files").fadeOut();
	jomresJquery('#files').html('');
	});

function hide_uploaded()
	{
	jomresJquery("#files").children().each(function(n, i) 
		{
		if ( jomresJquery(this).hasClass('uploaded') )
			{
			jomresJquery(this).fadeOut();
			jomresJquery(this).html('');
			}
		});
	}
	
function delete_file(url , id )
	{
	jomresJquery.get(url,function (data) 
		{
		if (data != '')
			{
			get_existing_images();
			jomresJquery("#"+id).fadeOut();
			jomresJquery("#"+id).html('');
			}
		});
	}

jomresJquery('#upload_all').click(function () {
	jomresJquery('.start').each(function () {
		jomresJquery(this).click();
		})
	});
	
function get_existing_images()
	{
	jomresJquery('#existing_images').fadeOut();
	var resource_type = jomresJquery('#resource_types').val();
	var resource_id = jomresJquery('#resource_id').val();
	if (resource_id == '') {
		resource_id=0;
		}
	jomresJquery.get(ajax_url + '&task=media_centre_resources_ajax_existing_images&resource_type=' + resource_type+'&resource_id='+resource_id,
		function (data) {
			populateDiv ( 'existing_images' , data );
			jomresJquery('#existing_images').fadeIn();
		});
    var link = window['preview_link_'+resource_type];
    if( typeof link !== 'undefined' ) {
        jomresJquery('#image_preview_button').show("slow");
        jomresJquery('#preview_modal_body').html('<i class="fa fa-spinner fa-spin fa-5x" aria-hidden="true"></i> ');
        jomresJquery("#image_preview_button").attr("href", link);
        }
    else {
        jomresJquery('#image_preview_button').hide("slow");
        }
	}
	
jomresJquery(document).ready(function () {

  jomresJquery('[data-toggle="popover"]').popover()

	get_resource_ids_for_resource_type(jomresJquery('#resource_types').val());
    
    // Fill modal with content from link href
    jomresJquery("#previewModal").on("show.bs.modal", function(e) {
        var link = jomresJquery(e.relatedTarget);
        jomresJquery(this).find(".modal-body").load(link.attr("href"));
        });
	});
</script>

<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            {% if (file.error) { %}
                <div><span class="label label-danger">Error</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <p class="size">{%=o.formatFileSize(file.size)%}</p>
            {% if (!o.files.error) { %}
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
            {% } %}
        </td>
        <td>
            {% if (!o.files.error && !i && !o.options.autoUpload) { %}
                <button class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start</span>
                </button>
            {% } %}
            {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview">
                {% if (file.thumbnailUrl) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                    <span>{%=file.name%}</span>
                {% } %}
            </p>
            {% if (file.error) { %}
                <div><span class="label label-danger">Error</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td>
            {% if (file.deleteUrl) { %}
                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Delete</span>
                </button>
                <input type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>


<div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="COMMON_CLOSE"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="previewModalLabel">{_JOMRES_FRONT_PREVIEW}</h4>
      </div>
      <div class="modal-body" id="preview_modal_body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">{COMMON_CLOSE}</button>
      </div>
    </div>
  </div>
</div>
</patTemplate:tmpl>