<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 *
 */

$is_update = isset($document_id);

global $post;

$insert_new_document = $post->post_type !== 'wiaas_doc';

?>

<style>

	#wiaas_document_form .form-group {
		margin-bottom:15px;
		min-height: 30px;
	}

	#wiaas_document_form .form-control {
		width: 100%;
		height: 34px;
		padding:6px 12px;
		border: 1px solid #d5d5d5;

	}

    #wiaas_document_form #plupload-browse-button {
		color: #444 !important;
		background-color: #FFFFFF !important;
		border-color: #CCCCCC !important;
		text-transform: uppercase !important;
		letter-spacing: 1px !important;
		border-radius: 2px !important;
	}

    #wiaas_document_form #plupload-upload-ui {
		height: 230px;
	}

    #wiaas_document_form #drag-drop-area {
		max-height: 200px;
	}

    #wiaas_document_form .drag-drop .drag-drop-inside {
		margin: 50px auto 0;
	}
</style>

<script>
    jQuery(document).ready(function ($) {
		<?php

            if ($insert_new_document) {
	            $nonce = wp_create_nonce('wiaas_quick_add_document');
	            $action = 'wiaas_quick_add_document';
            } else {
	            $nonce = wp_create_nonce('wiaas_upload_file');
	            $action = 'wiaas_upload_file';
            }

		$plupload_init = array(
			'runtimes'            => 'html5,silverlight,flash,html4',
			'browse_button'       => 'plupload-browse-button',
			'container'           => 'plupload-upload-ui',
			'drop_element'        => 'drag-drop-area',
			'file_data_name'      => 'wiaas_file',
			'multiple_queues'     => false,
			'url'                 => admin_url('admin-ajax.php'),
			'flash_swf_url'       => includes_url('js/plupload/plupload.flash.swf'),
			'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
			'filters'             => array(array(
			        'title' => __('Allowed Files'),
                    'extensions' => join(',', Wiaas_Document_Upload::allowed_extensions()))
            ),
			'multipart'           => true,
			'urlstream_upload'    => true,
			// additional post data to send to our ajax hook
			'multipart_params'    => array(
				'_ajax_nonce' => $nonce,
				'action'      => $action,
				'type' => 'wiaas_doc'
			),
		);

		if(get_option('__wpdm_chunk_upload',0) == 1){
			$plupload_init['chunk_size'] = get_option('__wpdm_chunk_size', 1024).'kb';
			$plupload_init['max_retries'] = 3;
		} else
			$plupload_init['max_file_size'] = wp_max_upload_size().'b';
		?>

        // create the uploader and pass the config from above
        var uploader = new plupload.Uploader(<?php echo json_encode($plupload_init); ?>);

        // checks if browser supports drag and drop upload, makes some css adjustments if necessary
        uploader.bind('Init', function(up){
            var uploaddiv = jQuery('#plupload-upload-ui');

            if(up.features.dragdrop){
                uploaddiv.addClass('drag-drop');
                jQuery('#drag-drop-area')
                    .bind('dragover.wp-uploader', function(){ uploaddiv.addClass('drag-over'); })
                    .bind('dragleave.wp-uploader, drop.wp-uploader', function(){ uploaddiv.removeClass('drag-over'); });

            }else{
                uploaddiv.removeClass('drag-drop');
                jQuery('#drag-drop-area').unbind('.wp-uploader');
            }
        });

        uploader.init();

        // a file was added in the queue
        uploader.bind('FilesAdded', function(up, files){
            //var hundredmb = 100 * 1024 * 1024, max = parseInt(up.settings.max_file_size, 10);

            <?php
                if ($insert_new_document) {
                    ?>
                        var params = uploader.getOption('multipart_params');
                        params['doc_title'] = $('#wiaas_new_doc_title').val();
                        params['doc_type'] = $('#wiaas_new_doc_type').val();
                        params['doc_visible'] = $('#wiaas_new_doc_visible').is(':checked');

                        uploader.setOption('multipart_params', params);

                        plupload.each(files, function(file){
                            jQuery('#wiaas_selected_file').val(file.name);
                        });
                    <?php
                }
            ?>

            uploader.refresh();
            uploader.start();
        });

        $("#wiaas_document_add_version").click(function(e) {
            e.preventDefault();

            uploader.start();
        });

        // a file was uploaded
        uploader.bind('FileUploaded', function(up, file, response) {

            response = response.response;

            if (response.substring(0, 6) === 'ERROR:') {
                jQuery('#wiaas_upload_errors').html('<span class="text-danger">' +
                    '<i class="fa fa-exclamation-triangle"></i>' +
                    ' &nbsp; ' + response.substring(6, response.length) +
                    '</span>');
                return;
            }

	        <?php
                if ($insert_new_document) {
                    ?>
                        $('#wiaas_attached_documents').find('tbody').append(response);
                    <?php
                } else {
                    ?>
                        $('#wiaas_uploaded_file').val(response);
                        jQuery('#publish').click();
                    <?php
                }
	        ?>
        });

    });
</script>

<div id="wiaas_document_form">

	<?php
	if ($insert_new_document) {
		?>
        <p class="form-group">
            <input
                    id="wiaas_new_doc_title"
                    type="text"
                    placeholder="Title"
                    class="form-control input-lg" />
        </p>
		<?php
	}
	?>

    <p class="form-group">
        <select
                id="wiaas_new_doc_type"
                name="wiaas_doc_type"
                class="form-control input-lg">
			<?php
			$all_doc_types = Wiaas_Document::get_available_doc_types();

			if (!$insert_new_document) {
				$selected_doc_type = Wiaas_Document::get_doc_type($post->ID);
				$selected_doc_type = is_array($selected_doc_type) ? $selected_doc_type['id'] : '';
			}

			foreach ($all_doc_types as $doc_type) {
				if (!$doc_type['is_special_type']) {
					?>
                    <option
                            value="<?php echo $doc_type['id'] ?>"
						<?php selected($doc_type['id'], $selected_doc_type, true)?>
                    >
						<?php  esc_html_e($doc_type['name'], 'wiaas') ?>
                    </option>
					<?php
				}
			}
			?>
        </select>
    </p>

    <p class="form-group">
        <input
                id="wiaas_new_doc_visible"
                name="wiaas_doc_visible"
			<?php if (!$insert_new_document)
				checked(Wiaas_Document::is_doc_visible($post->ID), true, true) ?>
                type="checkbox"
        />
        <label><?php echo __( 'Visible to customer?', 'wiaas' ); ?></label>
    </p>

    <input id="wiaas_uploaded_file" name="wiaas_doc_version" type="hidden">

    <div>
        <div id="plupload-upload-ui" class="hide-if-no-js">
            <div id="drag-drop-area" style="height:240px">
                <div class="drag-drop-inside">
                    <p class="drag-drop-info"><?php _e( 'Drop file here', 'wiaas' ); ?></p>

                    <p><?php echo _x( 'or', 'Drop file here *or* select file', 'wiaas' ); ?></p>

                    <p class="drag-drop-buttons"><input id="plupload-browse-button" type="button"
                                                        value="<?php esc_attr_e( 'Select File', 'wiaas' ); ?>"
                                                        class="button"/></p>
                </div>
            </div>
            </p>
        </div>
    </div>

    <div id="wiaas_upload_errors" style="color: darkred;">
    </div>

</div>
