/*jshint -W065 */
jQuery(document).ready(function ($) {

	'use strict';

	// Reading WordPress Options
	var wpas_json_str = wpas.replace(/&quot;/g, '"');
	var wpas_obj = $.parseJSON(wpas_json_str);

	// Convert size in bytes to human readable format (JavaScript)
	function bytesToSize(bytes, precision) {
		var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
		var posttxt = 0;
		if (bytes === 0) return 'n/a';
		while( bytes >= 1024 ) {
			posttxt++;
			bytes = bytes / 1024;
		}
		return parseInt(bytes).toFixed(precision) + " " + sizes[posttxt];
	}

	// File Attachements: FilePicker (https://developers.inkfilepicker.com/docs/web/)
	if (typeof filepicker !== 'undefined') {
		filepicker.setKey(wpas_obj.attachments.fpApiKey);

		// Security Enabled
		if (typeof wpas_obj.attachments.fpPolicy !== 'undefined' || typeof wpas_obj.attachments.fpSignature !== 'undefined' ) {
			$('.filepicker').click(function (e){
				filepicker.pickMultiple({
					policy: wpas_obj.attachments.fpPolicy,
					signature: wpas_obj.attachments.fpSignature,
					extensions: wpas_obj.attachments.allowedExtensions,
					services: wpas_obj.attachments.allowedServices,
					maxSize: wpas_obj.attachments.maxSize
				},
				function(InkBlob){
					$('input[name="attachments"]').val(encodeURIComponent(JSON.stringify(InkBlob)));
					$.each(InkBlob, function(i, item) {
						$('.wpas-attachments-list').append('<li class="list-group-item"><a href="'+item.url+'?signature='+wpas_obj.attachments.fpSignature+'&policy='+wpas_obj.attachments.fpPolicy+'" target="_blank">'+item.filename+'</a> <span class="badge">'+bytesToSize(item.size)+'</span></li>');
					});
					$('#wpas-reply-wysiwyg').prop('required',true);
					$('#wpas-reply-textarea').prop('required',true);
					$('#wpas-reply-mobile').prop('required',true);
					$('.filepicker').html('<i class="glyphicon glyphicon-plus-sign" aria-hidden="true"></i> Add more files');
				}
				);
			});
		}

		// Security disabled
		else {
			$('.filepicker').click(function (e){
				filepicker.pickMultiple({
					extensions: wpas_obj.attachments.allowedExtensions,
					services: wpas_obj.attachments.allowedServices
				},
				function(InkBlob){
					$('input[name="attachments"]').val(encodeURIComponent(JSON.stringify(InkBlob)));
					$.each(InkBlob, function(i, item) {
						$('.wpas-attachments-list').append('<li class="list-group-item"><a href="'+item.url+'" target="_blank">'+item.filename+'</a> <span class="badge">'+bytesToSize(item.size)+'</span></li>');
					});
				}
				);
			});
		}
	}
	else {
		if ($('.filepicker').length > 0){
			$('.filepicker').replaceWith('<div class="alert alert-danger"><strong>Oh snap!</strong> We were unabled to load the uploader script. Please <a href="#" onClick="window.location.reload()">refresh the page</a> if you want to attach files.</div>');
		}
	}

});