(function ($) {
	var params;
	var labelSaveTimeOut = null;
	var currentSlide = null;
	var lockSlideAppend = false;
	var lockOptionAppend = false;
	var lockPlay = false;
	var lockOptionAppend = false;
	var slidesNextIndex = 0;

	$.fn.presentation = function (paramsInit) {
		params = $.extend({
			url: null,
			identifier: null
		}, paramsInit);

		$.fn.presentation.init();
	};

	$.fn.presentation.appendEmptySlide = function () {
		if (lockSlideAppend) {
			return false;
		}

		$.fn.presentation.labelSave("preview", "start");

		$.post(params.url + "/slajdy/dodaj/" + params.identifier, {}, function (response) {
			if (response.status == true) {
				var html = $(".template-slide").html();
				html = html.replace("[slide-id]", response.board_id);
				html = html.replace("[slide-id]", response.board_id);
				html = html.replace("[slide-index]", slidesNextIndex);
				html = html.replace("[slide-index]", slidesNextIndex);
				html = html.replace("[slide-type]", "empty");
				html = html.replace("[slide-preview]", "");

				$("*[data-presentation='slides-list']").append(html);

				$.fn.presentation.initSlides();
				slidesNextIndex++;

				$.fn.presentation.labelSave("preview", "success");

				$.fn.presentation.slideActive($("*[data-presentation='slide'][data-slide-id='" + response.board_id + "']"));
			} else {
				$.fn.presentation.labelSave("preview", "error");
			}
		}, "json");
	}

	$.fn.presentation.init = function () {
		$.fn.presentation.initSettings();
		$.fn.presentation.initSlides();

		$.fn.presentation.slideActive($("*[data-presentation='slides-list'] *[data-presentation='slide']").first());

		$("*[data-presentation='slide-add']").on("click", function () {
			$.fn.presentation.appendEmptySlide();
		});

		$("*[data-presentation='presentation-play']").on("click", function () {
			if (lockPlay) {
				return false;
			}

			location.href = params.url + "/prezentacje/uruchom/" + params.identifier;
		});

		$("*[data-presentation='slide-type']").on("click", function () {
			if ($(this).hasClass("disabled")) {
				return false;
			}

			$.fn.presentation.slideType($(this).data("type-id"), true);
		});

		$("*[data-presentation='presentation-remove-results']").on("click", function () {
			$("#modal_all_remove_results form").attr("action", params.url + "/prezentacje/usun-wyniki/" + params.identifier);
			$("#modal_all_remove_results").modal("show");

			$("#modal_all_remove_results form").off("submit").on("submit", function (event) {
				event.preventDefault();

				$.post($(this).attr("action"), { __action: "" }, function (response) {
					if (response.status == "success") {
						location.href = response.url;
					}
				}, "json");
			});
		});

		$("#modal_slide_options_limit, #modal_slide_remove, #modal_remove_results, #modal_remove_reactions, #modal_all_remove_results").modal({
			backdrop: "static",
			keyboard: false,
			show: false
		});
	};

	$.fn.presentation.initSlides = function () {
		if ($(".wrapper_ct_l .slides").hasClass("ui-sortable") == true) {
			$(".wrapper_ct_l .slides").sortable("destroy");
		}

		var listSlides = $("*[data-presentation='slides-list']");
		var slideIndex = 1;

		$.fn.presentation.playLockAdd();
		$("*[data-presentation='slide']", listSlides).each(function (index, value) {
			var slide = $(this), slideId = $(this).data("slide-id"), slideType = $(this).data("slide-type");

			$.fn.presentation.slideLockAdd();
			if (slideType != "empty") {
				$.fn.presentation.slideUnLockAdd();
				$.fn.presentation.playUnLockAdd();
			}

			$(slide).data("slide-index", slideIndex);
			$("*[data-presentation='slide-index']", slide).text(slideIndex);

			if ($(slide).hasClass("active")) {
				$("*[data-presentation='slides-statistics'] .current").text(slideIndex);
			}

			$.fn.presentation.slideIcon(slideId, slideType);

			slideIndex++;
		});

		slidesNextIndex = slideIndex;

		$("*[data-presentation='slide']", listSlides).off("click").on("click", function () {
			$.fn.presentation.slideActive($(this));
		});

		$("*[data-presentation='slide'] *[data-presentation='slide-remove']", listSlides).off("click").on("click", function () {
			var slide = $(this).closest(".slide"), slideId = $(slide).data("slide-id"), slideIndex = $(slide).data("slide-index"), slidePreview = $(slide).data("slide-preview");

			$("#modal_slide_remove form").attr("action", params.url + "/slajdy/usun/" + params.identifier + "/" + slideId);
			$("#modal_slide_remove *[data-presentation='slide-remove-index']").text(slideIndex);

			$("#modal_slide_remove .info_slide_preview_w").hide();

			if (slidePreview) {
				$("#modal_slide_remove .info_slide_preview_w").show();
				$("#modal_slide_remove .info_slide_preview_w img").attr("src", slidePreview);
			}

			$("#modal_slide_remove").modal("show");

			$("#modal_slide_remove form").off("submit").on("submit", function (event) {
				event.preventDefault();

				var form = $("#modal_slide_remove form"), dataPost = $(form).serializeArray();
				dataPost[dataPost.length] = { name: "__action", value: true };

				$.post($(form).attr("action"), dataPost, function (response) {
					if (response.status == true) {
						slide.remove();

						if (slideId == currentSlide) {
							var firstSlide = $("*[data-presentation='slides-list'] *[data-presentation='slide']").first();
							if (firstSlide.length > 0) {
								$.fn.presentation.slideActive(firstSlide);
							} else {
								$.fn.presentation.appendEmptySlide();
							}
						}

						$("#modal_slide_remove").modal("hide");
					}

					$.fn.presentation.initSlides();
				}, "json");
			});
		});

		$("*[data-presentation='slide'] *[data-presentation='slide-duplicate']", listSlides).off("click").on("click", function () {
			var slide = $(this).closest(".slide"), slideId = $(slide).data("slide-id"), slideIndex = $(slide).data("slide-index"), slidePreview = $(slide).data("slide-preview");

			$.post(params.url + "/slajdy/kopiuj/" + params.identifier + "/" + slideId, function (response) {
				if (response.status == true) {
					var html = $(".template-slide").html();
					html = html.replace("[slide-id]", response.board.id);
					html = html.replace("[slide-id]", response.board.id);
					html = html.replace("[slide-index]", slidesNextIndex);
					html = html.replace("[slide-index]", slidesNextIndex);
					html = html.replace("[slide-type]", response.board.type);
					html = html.replace("[slide-preview]", response.board.preview);

					$("*[data-presentation='slides-list'] *[data-presentation='slide'][data-slide-id='" + slideId + "']").after(html);

					if (response.board.type != "empty") {
						var slide = $("*[data-presentation='slides-list'] *[data-presentation='slide'][data-slide-id='" + response.board.id + "']");

						$(slide).data("slide-preview", response.board.preview);
						$(".slide_ct_ct.bg", slide).attr("style", "background: url('" + response.board.preview + "') center center no-repeat;");
						$(".slide_title_w", slide).remove();
					}
				} else {

				}

				$.fn.presentation.initSlides();
			}, "json");
		});

		$("*[data-presentation='slides-statistics'] .total").text($("*[data-presentation='slide']", listSlides).length);

		$(".wrapper_ct_l .slides").sortable({
			items: "div.slide[data-slide-type!='empty']",
			axis: "y",
			tolerance: "pointer",
			forcePlaceholderSize: true,
			opacity: 0.8,
			placeholder: "placeholder",
			update: function (event, ui) {
				$(".wrapper_ct_l .slides").sortable("disable");

				$.fn.presentation.labelSave("preview", "start");

				$.post(params.url + "/prezentacje/porzadek/" + params.identifier, $(".wrapper_ct_l .slides").sortable("serialize", { expression: /(.+)[_](.+)/ }), function (response) {
					if (response.status == "success") {
						$.fn.presentation.initSlides();
						$.fn.presentation.labelSave("preview", "success");
					} else {
						$(".wrapper_ct_l .slides").sortable("enable");
						$.fn.presentation.labelSave("preview", "error");
					}
				}, "json");
			}
		}).disableSelection();
	};

	$.fn.presentation.initSlideForm = function () {
		var form = $("*[data-presentation='slide-form'] form");

		$(".fileinput", form).on("change.bs.fileinput", function () {
			var fileinput = $(this).closest(".fileinput"), fileName = $(this).data("uploader"), valueName = $(this).data("value"), valueFileName = $(this).data("filename");

			$(".fileinput_uploading", fileinput).removeClass("hide");

			$(form).ajaxSubmit({
				url: params.url + "/slajdy/obrazek/" + params.identifier + "/" + currentSlide,
				data: { fieldName: fileName },
				dataType: "json",
				success: function (response) {
					$("div[data-error='" + valueName + "']", form).text("").closest(".df_error").removeClass("hide").addClass("hide");

					if (response.status == "success") {
						$("input[name='" + valueName + "']").val(response.value);
						$("input[name='" + valueFileName + "']").val(response.name);

						$("input[name='" + valueName + "']").trigger("change");
					} else {
						$("div[data-error='" + valueName + "']", form).text(response.error).closest(".df_error").removeClass("hide");
					}

					$(".fileinput_uploading", fileinput).addClass("hide");
				}
			});
		}).on("clear.bs.fileinput", function () {
			var valueName = $(this).data("value"), valueFileName = $(this).data("filename");

			$("input[name='" + valueName + "']").val("");
			$("input[name='" + valueFileName + "']").val("");

			$("input[name='" + valueName + "']").trigger("change");
		});

		$.fn.presentation.initOptionImage(form);

		if ($(".df .sortable_options", form).length > 0) {
			if ($(".df .sortable_options").hasClass("ui-sortable")) {
				$(".df .sortable_options", form).sortable("destroy");
			}

			$(".df .sortable_options", form).sortable({
				axis: "y",
				tolerance: "pointer",
				forcePlaceholderSize: true,
				opacity: 0.8,
				placeholder: "placeholder",
				update: function (event, ui) {
					$.fn.presentation.slideSave();
				}
			}).disableSelection();

			$("*[data-presentation='slide-form-option-add']", form).off("click").on("click", function () {
				if (lockOptionAppend) {
					return false;
				}

				if ($(".df .sortable_options div.input-group", form).length >= 8) {
					$("#modal_slide_options_limit").modal("show");
					return false;
				}

				var template = ".template-option-text";
				if ($(this).data("type") == "with-max-length") {
					template = ".template-option-text-with-max-length";
				} else if ($(this).data("type") == "with-max-length-correct") {
					template = ".template-option-text-with-max-length-correct";
				} else if ($(this).data("type") == "with-image") {
					template = ".template-option-text-with-image";
				}

				var templateHtml = $(template).html();

				var date = new Date();
				var index = date.getTime();

				templateHtml = templateHtml.replaceAll("[index]", index);

				$(".df .sortable_options", form).append(templateHtml);

				$.fn.presentation.slideFormOnChange();
				$.fn.presentation.slideFormOptionAction();
				$.fn.presentation.initOptionImage(form);

				data_max_length();
			});

			$.fn.presentation.slideFormOptionAction();
		};

		$("*[data-presentation='slide-remove-results']").off("click").on("click", function () {
			$("#modal_remove_results form").attr("action", params.url + "/slajdy/usun-wyniki/" + params.identifier + "/" + currentSlide);
			$("#modal_remove_results").modal("show");

			$("#modal_remove_results form").off("submit").on("submit", function (event) {
				event.preventDefault();

				$.post($(this).attr("action"), { __action: "" }, function (response) {
					if (response.status == true) {
						$.fn.presentation.slidePreview("", response.preview);

						$("*[data-presentation='slide-remove-results-layer']").addClass("hidden");
						$("#modal_remove_results").modal("hide");

						$.fn.presentation.slideFormUnLock();
					}
				}, "json");
			});
		});

		$("*[data-presentation='slide-remove-reactions']").off("click").on("click", function () {
			$("#modal_remove_reactions form").attr("action", params.url + "/slajdy/usun-wyniki/" + params.identifier + "/" + currentSlide);
			$("#modal_remove_reactions").modal("show");

			$("#modal_remove_reactions form").off("submit").on("submit", function (event) {
				event.preventDefault();

				$.post($(this).attr("action"), { __action: "" }, function (response) {
					if (response.status == true) {
						$.fn.presentation.slidePreview("", response.preview);

						$("*[data-presentation='slide-remove-results-layer']").addClass("hidden");
						$("#modal_remove_reactions").modal("hide");
					}
				}, "json");
			});
		});

		data_max_length();
		window.ct_scroll();
		window.tooltips();
	};

	$.fn.presentation.initOptionImage = function (form) {
		$("*[data-presentation='optionImage'] input[type='file']").off("change").on("change", function () {
			var boxUploader = $(this).closest(".input-group-bg-image");
			var fileObject = $(this);
			var fileName = $(this).attr("name");
			var valueName = $(boxUploader).data("file");

			$(form).ajaxSubmit({
				url: params.url + "/slajdy/obrazek/" + params.identifier + "/" + currentSlide,
				data: { fieldName: fileName },
				dataType: "json",
				success: function (response) {
					if (response.status == "success") {
						boxUploader.css("background", "url('" + response.path + "') center center no-repeat");

						$("svg", boxUploader).remove();

						$("input[name='" + valueName + "']").val(response.value);
						$("input[name='" + valueName + "']").trigger("change");
					}

					$(fileObject).val("");
				}
			});
		});
	};

	$.fn.presentation.slideActive = function (slide) {
		var slideId = $(slide).data("slide-id"), slideType = $(slide).data("slide-type"), slideIndex = $(slide).data("slide-index");

		if (slideId == currentSlide) {
			return false;
		}

		$("*[data-presentation='slides-list'] *[data-presentation='slide']").removeClass("active");

		currentSlide = slideId;
		$(slide).addClass("active");

		$("*[data-presentation='slides-statistics'] .current").text(slideIndex);

		$.fn.presentation.slideType(slideType, false);
	};

	$.fn.presentation.slideType = function (type, update) {
		var formSlide = $("*[data-presentation='slide-form'] form");

		$("*[data-presentation='slide-type']").removeClass("active");

		if (type == "empty") {
			$("*[data-dtab-link='basic']").trigger("click");
			$("*[data-rtab-link='theme']").trigger("click");
			$("*[data-rtab-link='content']").addClass("disabled");
			$(formSlide).html("");
			$.fn.presentation.slidePreview(type, "");
			$.fn.presentation.slideFormUnLock(true);
			return true;
		}

		if (update) {
			$.fn.presentation.labelSave("preview", "start");
		}

		$.fn.presentation.slideFormUnLock();

		$.post(params.url + "/slajdy/typ/" + params.identifier + "/" + currentSlide, { type: type }, function (response) {
			if (response.status == true) {
				$(formSlide).html(response.view);

				$.fn.presentation.initSlideForm();
				$.fn.presentation.slidePreview(type, response.preview);
				$.fn.presentation.slideFormOnChange();

				var typeElement = $("*[data-presentation='slide-type'][data-type-id='" + type + "']");

				$("*[data-dtab-link='" + $(typeElement).closest(".dtab_ct").data("dtab-ct") + "']").trigger("click");
				$(typeElement).addClass("active");

				$("*[data-rtab-link='content']").removeClass("disabled");
				$("*[data-rtab-link='content']").trigger("click");

				if (response.lock == true) {
					$.fn.presentation.slideFormLock();
				}

				if (update == true) {
					$("*[data-presentation='slides-list'] *[data-presentation='slide'][data-slide-id='" + currentSlide + "']").data("slide-type", type);
					$("*[data-presentation='slides-list'] *[data-presentation='slide'][data-slide-id='" + currentSlide + "']").attr("data-slide-type", type);

					$.fn.presentation.initSlides();
					$.fn.presentation.labelSave("preview", "success");
				}
			} else {
				if (update == true) {
					$.fn.presentation.labelSave("preview", "error");
				}
			}
		}, "json");

	};

	$.fn.presentation.slideSave = function () {
		var formSlide = $("*[data-presentation='slide-form'] form");

		var dataPost = formSlide.serializeArray();
		dataPost[dataPost.length] = { name: "__action", value: true };

		$.fn.presentation.labelSave("preview", "start");

		$.post(params.url + "/slajdy/zapisz/" + params.identifier + "/" + currentSlide, dataPost, function (response) {
			if (response.status == true) {
				$.fn.presentation.slidePreview("no-empty", response.preview);
				$.fn.presentation.labelSave("preview", "success");
			} else {
				$.fn.presentation.labelSave("preview", "error");
			}
		}, "json");
	};

	$.fn.presentation.labelSave = function (tabName, status) {
		if (status == "start") {
			clearTimeout(labelSaveTimeOut);
		}

		var labelSave = $("*[data-presentation='" + tabName + "-icon-saving']");
		var labelSaveError = $("*[data-presentation='" + tabName + "-icon-saving-error']");
		var labelSaveSuccess = $("*[data-presentation='" + tabName + "-icon-saving-success']");

		switch (status) {
			case "start":
				labelSave.show();
				labelSaveError.hide();
				labelSaveSuccess.hide();
				break;
			case "error":
				labelSave.hide();
				labelSaveError.show();
				labelSaveSuccess.hide();

				labelSaveTimeOut = setTimeout(function () {
					labelSaveError.hide();
				}, 1500);
				break;
			case "success":
				labelSave.hide();
				labelSaveError.hide();
				labelSaveSuccess.show();

				labelSaveTimeOut = setTimeout(function () {
					labelSaveSuccess.hide();
				}, 1500);
				break;
		}
	};

	$.fn.presentation.slideLockAdd = function () {
		lockSlideAppend = true;
		$("*[data-presentation='slide-add']").addClass("disabled");
	};

	$.fn.presentation.slideUnLockAdd = function () {
		lockSlideAppend = false;
		$("*[data-presentation='slide-add']").removeClass("disabled");
	};

	$.fn.presentation.playLockAdd = function () {
		lockPlay = true;
		$("*[data-presentation='presentation-play']").addClass("disabled");
	};

	$.fn.presentation.playUnLockAdd = function () {
		lockPlay = false;
		$("*[data-presentation='presentation-play']").removeClass("disabled");
	};

	$.fn.presentation.initSettings = function () {
		var formSettings = $("form[data-presentation='settings']");

		$("input", formSettings).on("change", function () {
			$.fn.presentation.labelSave("settings", "start");

			var dataPost = formSettings.serializeArray();
			dataPost[dataPost.length] = { name: "__action", value: true };

			$.post(params.url + "/prezentacje/zapisz/" + params.identifier, dataPost, function (response) {
				$("div[data-error]", formSettings).each(function () {
					$(this).text("");
				});

				if (response.status == "success") {
					$.fn.presentation.labelSave("settings", "success");
				} else {
					$.fn.presentation.labelSave("settings", "error");

					for (var key in response.errors) {
						$("div[data-error='" + key + "']", formSettings).text(response.errors[key]);
					}
				}
			}, "json");
		});
	};

	$.fn.presentation.slidePreview = function (type, preview) {
		if (type == "empty") {
			preview = $(".template-slide-preview-empty").html();
		}

		$("*[data-presentation='slide-preview']").html(preview);

		hidden_image();
	};

	$.fn.presentation.slideFormOnChange = function () {
		var formSlide = $("*[data-presentation='slide-form'] form");

		$("input[type!='file'], textarea, select", formSlide).off("change");
		$("input[type!='file'], textarea, select", formSlide).on("change", function () {
			$.fn.presentation.slideSave();
		});
	};

	$.fn.presentation.slideFormLock = function () {
		var formSlide = $("*[data-presentation='slide-form'] form");

		if ($("*[data-presentation='elementDisabled']", formSlide).length == 0) {
			return;
		}

		$("*[data-presentation='slide-type']").addClass("disabled");

		$("*[data-presentation='elementDisabled']", formSlide).each(function () {
			$("input[type!='file'], textarea, select", this).attr("readonly", "readonly");

			$(".sortable_options", this).addClass("disabled");
			$(".btn", this).addClass("disabled");

			$(".sortable_options", this).sortable("disable");

			lockOptionAppend = true;
		});
	}

	$.fn.presentation.slideFormUnLock = function (ignoreDisabled) {
		var formSlide = $("*[data-presentation='slide-form'] form");

		if (typeof ignoreDisabled === "undefined") {
			ignoreDisabled = false;
		}

		if ($("*[data-presentation='elementDisabled']", formSlide).length == 0 && !ignoreDisabled) {
			return;
		}

		$("*[data-presentation='slide-type']").removeClass("disabled");

		$("*[data-presentation='elementDisabled']", formSlide).each(function () {
			$("input[type!='file'], textarea, select", this).removeAttr("readonly");

			$(".sortable_options", this).removeClass("disabled");
			$(".btn", this).removeClass("disabled");

			$(".sortable_options", this).sortable("enable");

			lockOptionAppend = false;
		});
	}

	$.fn.presentation.slideFormOptionAction = function () {
		var formSlide = $("*[data-presentation='slide-form'] form");

		$("*[data-presentation='slide-form-option-remove']", formSlide).off("click").on("click", function () {
			$(this).closest(".input-group").remove();

			$.fn.presentation.slideSave();
		});
	};

	$.fn.presentation.slideIcon = function (slideId, slideType) {
		if (slideType == "empty") {
			return false;
		}

		var template = $(".template_box_details_w", $("*[data-type-id='" + slideType + "']")).html();

		$("*[data-slide-id='" + slideId + "'] *[data-presentation='slide-icon']").html('<div class="template_box_details_w">' + template + '</div>');
	};
})(jQuery);