<?php defined('_JEXEC') or die; 
$assets = juri::root().'plugins/system/vm_uploader/assets/';
$auto_upload = $this->params->get('auto_upload', 0);
$auto_insert = $this->params->get('auto_insert', 0);
$acceptFileTypes = 'gif|jpe?g|png';
if( $view == 'product' && $filter = $this->params->get('filter', null)) {
	$filter = preg_replace("/[^A-Za-z0-9,]/", '', $filter);
	$exts = explode(",", $filter);
	$valideExt = array();
	foreach($exts as $ext) {
		if(strlen($ext)) $valideExt[] = $ext;
	}
	if(!empty($valideExt)) $acceptFileTypes = implode ("|", $valideExt);
}
if (!class_exists( 'VmConfig' )) require(JPATH_ROOT.'/administrator/components/com_virtuemart/helpers/config.php');
VmConfig::loadConfig();
$VMmediaPath = '/images';
if($view == 'product' || $view == 'products'){
	$VMmediaPath = VmConfig::get('media_product_path');
}
else if($view == 'category' || $view == 'categories'){
	$VMmediaPath = VmConfig::get('media_category_path');
}
else if($view == 'shop'){
	$VMmediaPath = VmConfig::get('media_path');
}
else if($view == 'vendor' || $view == 'vendors'){
	$VMmediaPath = VmConfig::get('media_vendor_path');
}
else if($view == 'manufacturer' || $view == 'manufacturers'){
	$VMmediaPath = VmConfig::get('media_manufacturer_path');
} 
$subfolders = JFolder::folders(JPATH_ROOT . '/'.$VMmediaPath);
$folderList = array();
$folderList[] = JHTML::_('select.option',  '', '- select subfolder -');
foreach($subfolders as $subfolder) {
	if ($subfolder === 'resized') continue;
	$folderList[] = JHTML::_('select.option',  $subfolder,  $subfolder);

}
?>

<link rel="stylesheet" href="<?php echo $assets ?>css/jquery.fileupload.css">

<div class="container-fluid">
	<?php echo JHTML::_('select.genericlist', $folderList, '', '', 'value', 'text', '', 'subfolderimage'); ?><input id="addfolderimage" type="text">
	
	
   <!-- The fileinput-button span is used to style the file input field as button -->
    <span class="btn btn-success fileinput-button">
        <i class="icon icon-plus"></i>
        <span><?php echo jText::_('COM_MEDIA_BROWSE_FILES') ?></span>
        <!-- The file input field used as target for the file upload widget -->
        <input id="fileupload" type="file" name="files[]" multiple>
    </span>
    <br>
    <!-- The global progress bar -->
    <div id="progress" class="progress" style="margin-top: 5px;>
        <div class="progress-bar progress-bar-success bar"></div>
    </div>
    <!-- The container for the uploaded files -->
     <ul id="files" class="files thumbnails"></ul>
    <br>
</div>
<div style="display:none" id="uploaded_to_vm">
<div class="vm_thumb_image">
  <span>
	<a class="vm_thumb" rel="group1" title="classic_hat.jpg" href="">
	<img src="" alt="">
	</a>
	</span>
	<input type="hidden" name="" class="uploaded__media_id">
	<input class="ordering" type="hidden" >
	<div class="vmicon vmicon-16-remove 4remove" title="<?php echo jText::_('COM_VIRTUEMART_IMAGE_REMOVE') ?>"></div>
  <div title="<?php echo jText::_('COM_VIRTUEMART_IMAGE_EDIT_INFO') ?>" class="edit-24-grey"></div>
</div>
</div>
<script src="<?php echo $assets ?>/js/vendor/jquery.ui.widget.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="//blueimp.github.io/JavaScript-Load-Image/js/load-image.all.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="//blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="<?php echo $assets ?>/js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="<?php echo $assets ?>/js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="<?php echo $assets ?>/js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="<?php echo $assets ?>/js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="<?php echo $assets ?>/js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="<?php echo $assets ?>/js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="<?php echo $assets ?>/js/jquery.fileupload-validate.js"></script>
<script>
/*jslint unparam: true, regexp: true */
/*global window, $ */
jQuery(function ($) {
    'use strict';
    // Change this to the location of your server-side upload handler:
    var url = 'index.php?option=com_virtuemart&vm_upload=1&type=<?php echo $view ?>',
        uploadButton = $('<button/>')
            .addClass('btn btn-primary')
            .prop('disabled', true)
            .text('<?php echo jText::_('JTOOLBAR_BATCH') ?>...')
            .on('click', function () {
                var $this = $(this),
                    data = $this.data();
                $this
                    .off('click')
                    .text('<?php echo jText::_('JCANCEL') ?>')
                    .on('click', function () {
                        $this.remove();
                        data.abort();
                    });
                data.submit().always(function () {
                    $this.remove();
                });
            });
	$('#toolbar-upload').find('button').click(function (e) {
		e.preventDefault();
		e.stopPropagation();
		$('#fileupload').click();
		return false;
	}).attr('onclick',null);
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        autoUpload: <?php echo $auto_upload ? 'true' : 'false' ?>,
        acceptFileTypes: /(\.|\/)(<?php echo $acceptFileTypes ?>)$/i,
		maxChunkSize: <?php echo $chunksize ?>,
        maxFileSize: <?php echo $upload_max_filesize ?>, // 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: /Android(?!.*Chrome)|Opera/
            .test(window.navigator.userAgent),
<?php if ($resize) {
	if ($width) echo 'imageMaxWidth: '.$width.',';
	if ($height) echo 'imageMaxHeight: '.$height.',';

} ?>
        previewMaxWidth: 200,
        previewMaxHeight: 200,
        previewCrop: <?php echo $this->params->get($view.'_thumb_crop', 0) ? 'true' : 'false' ?>,
		messages: {
                maxNumberOfFiles: 'Maximum number of files exceeded',
                acceptFileTypes: '<?php echo jText::_('JLIB_MEDIA_ERROR_WARNFILETYPE',true) ?>',
                maxFileSize: '<?php echo jText::_('JLIB_MEDIA_ERROR_WARNFILETOOLARGE',true) ?>',
                minFileSize: 'File is too small'
            }
    }).on('fileuploadadd', function (e, data) {
        data.context = $('<li class="span3">').appendTo('#files');
        $.each(data.files, function (index, file) {
            var node = $('<div class="thumbnail">')
                    .append('<div class="caption"><h4>'+file.name+'</h4></div>');
            <?php if (!$auto_upload) { ?>
			if (!index) {
                node.find('.caption')
                    .append(uploadButton.clone(true).data(data));
            }
			<?php } ?>
            node.appendTo(data.context);
        });
    }).on('fileuploadsubmit', function (e, data) {
   // The example input, doesn't have to be part of the upload form:
		var addfolder = $('#addfolderimage').val(),
			subfolder = $('#subfolderimage').val();
		data.formData = { "addfolder": addfolder,"subfolder": subfolder};
    }).on('fileuploadprocessalways', function (e, data) {
        var index = data.index,
            file = data.files[index],
            node = $(data.context.children()[index]),
			copyButton;
        if (file.preview) {
            node
                // .prepend('<br>')
                .prepend(file.preview);
				
				
        }
        if (file.error) {
            node
                .append('<br>')
                .append($('<span class="text-danger"/>').text(file.error));
        } else {
		}
        if (index + 1 === data.files.length) {
            data.context.find('button')
                .text('<?php echo jText::_('COM_MEDIA_UPLOAD') ?>')
                .prop('disabled', !!data.files.error);
        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('#progress .progress-bar').css(
            'width',
            progress + '%'
        );
    }).on('fileuploaddone', function (e, data) {
        $.each(data.result.files, function (index, file) {
			var list,copyButton ;
			// console.log(file,data);
            if (file.url) {
                var link = $('<a>')
                    .attr('target', '_blank')
                    .attr('title', file.name)
                    .prop('href', file.url).fancybox({
						'type'				:'image',
						'hideOnContentClick'		: true,
						'transitionIn'			:'elastic',
						'transitionOut'			:'elastic',
						'speedIn'			:600, 
						'speedOut'			:200, 
						'overlayShow'			:false,
						'titleShow'			:true,
						'titlePosition'			:'over'
					});
                $(data.context.children()[index])
                    .wrapInner(link);

			// console.log(file);
			copyButton = $('<button/>')
				.addClass('btn btn-primary')
				.text('<?php echo jText::_('COM_VIRTUEMART_IMAGE_ATTACH_NEW', true) ?>')
				.on('click', function () {
					var $this = $(this),$to_vm = $('#uploaded_to_vm').children().clone(true);
					$to_vm.find('a').attr('href',file.url).attr('title',file.name).children('img').attr('src',file.resizedUrl).attr('alt',file.name);
					$to_vm.find('.uploaded__media_id').attr('name','virtuemart_media_id['+file.virtuemart_media_id+']').val(file.virtuemart_media_id)
						.next()
						.attr('name','mediaordering['+file.virtuemart_media_id+']');
					$to_vm.appendTo(ImagesContainer);
					$(data.context.children()[index]).parent().remove();
					// $this.remove();
				});
			$(data.context.children()[index])
                .append(copyButton);
			<?php if($auto_insert) { ?>copyButton.trigger('click'); <?php } ?>
            } else if (file.error) {
                var error = $('<span class="text-danger"/>').text(file.error);
                $(data.context.children()[index])
                    .append('<br>')
                    .append(error);
            }
        });
    }).on('fileuploadfail', function (e, data) {
        $.each(data.files, function (index) {
            var error = $('<span class="text-danger"/>').text('File upload failed.');
            $(data.context.children()[index])
                .append('<br>')
                .append(error);
        });
    }).prop('disabled', !$.support.fileInput)
        .parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>