/*
	Stempora Web Framework
	Copyright (c) 2002-2018 Stempora. 
	All rights reserved.
		web:  www.stempora.com
		mail: support@stempora.com				
*/

var STBGlobalFormsUploader = Object.create(STBModule.prototype);

STBGlobalFormsUploader.name		= "GlobalFormsUploader";
STBGlobalFormsUploader.script	= site.assets + "plugins/blueimp/plugin.js";

STBGlobalFormsUploader.initPluginCallback = function() {		

	var elements = $(".form-upload-item:not(.__done)");

	if (elements.length) {

		elements.each(function() {
			var element	= $(this),
				form = element.closest(".form"),
				name = element.attr("data-name"),
				//uploading = element.attr("data-name") || "Uploading...",

				token = element.find("input[name=" + name +"_token]").val();


				//fix the placeholder issue
				if (!form.hasClass("form-placeholder")) {
					element.find(".form-upload-item-button").text("");
				}

				element.find('input[type=file]').fileupload({
					formData : "token=" + token,
					dataType: 'json',
					done: function (e, data) {

						var file = data.result.files[0];


						if ( typeof file != "undefined" ) {

							if (typeof file.error != "undefined") {
								STBGlobalForms.formFieldError(
									form,
									name,
									file.error,
									false
								);
							} else {
								var filename = STBUtils.str_replace(token + "_" , "" , file.name);

								element.find("input[name=" + name + "_files]").val(filename);
								element.find(".form-upload-item-button").text(filename);
							}
						} else {
							STBGlobalForms.formFieldError(
								form,
								name,
								"Unknown error!",
								false
							);
						}

						setTimeout(function() {
							element.find('.file-progress .bar').css(
								'width',
								0
							);
						}, 1000);

					},

					change: function (e, data) {
						//element.find(".form-upload-item-button").text(uploading);
					},

					add: function (e, data) {
						var count = data.files.length;
						var i;
						for (i = 0; i < count; i++) {
							data.files[i].uploadName = token + '_' + data.files[i].name;
						}
						data.submit();
					},

					progressall: function (e, data) {
						var progress = parseInt(data.loaded / data.total * 100, 10);
						element.find('.file-progress .bar').css(
							'width',
							progress + '%'
						);
					}
				}).error(function (jqXHR, textStatus, errorThrown) {
					console.log(textStatus);
					console.log(errorThrown);
				});

			element.addClass("__done");

		});
	}
}

STBGlobalFormsUploader.initPlugin = function() {
	if ($(".form-upload-item:not(.__done)").length > 0) {

		STBUtils.loadScriptCallback(
			STBGlobalFormsUploader.script,
			STBGlobalFormsUploader.initPluginCallback,
			true
		);
	}
}

STBGlobalFormsUploader.runOnReady = function() {
	STBGlobalFormsUploader.initPlugin();
}

STBGlobalFormsUploader.runOnContentUpdate = function() {
	STBGlobalFormsUploader.initPlugin();
}

site.registerModule(STBGlobalFormsUploader);
