$.OrkaTools = {
	Defaults: {
		DateTimeFormat: "DD.MM.YYYY HH:mm",
		DateFormat: "DD.MM.YYYY",
		DateMMFormat:  "DD.MM.**** (dddd)",
		TimeFormat: "HH:mm",
	}
	,init: function () {

		var promise = new Promise(function (resolve, reject) {
			var OrkaApp = document.querySelector('[id=OrkaControl]');
			$(".m-select2").select2({
				placeholder: "Seçin",
				allowClear: true
			});

			$('body').tooltip({
				selector: '[data-toggle="tooltip"]',
				html: true,
				delay: { "show": 0, "hide": 500 }
			});

			bootbox.addLocale("tr-tr", {
				OK: 'Tamam',
				CANCEL: 'İptal',
				CONFIRM: 'Evet'
			});
			bootbox.setLocale("tr-tr");
			// Tüm bootbox onay/uyarı pencereleri Metronic arayüzüne uyumlu olsun
			bootbox.setDefaults({
				className: "orka-bootbox-modal"
			});

			(function ($) {
				$.SifreAlaniniGoster = function (ayarlar) {
					var s = $.extend({
						field: "#sifrealani",
						control: "#gizlegoster"
					}, ayarlar);

					var control = $(s.control);
					var field = $(s.field);

					control.bind('click', function () {
						if (control.is(':checked')) {

							field.attr('type', 'text');
						} else {
							field.attr('type', 'password');

						}
					});
				};
			}(jQuery));



			$(document).find('[data-toggle="tooltip"]:not([title=""])').each((_, e) => {
				$(document).foundation('tooltip', 'update', $(e));
			});

			$.OrkaTools.OrkaController = angular.element(OrkaApp).scope();
			$.OrkaTools.DatePickers.init();
			$.OrkaTools.SummerNote.init();
			$.OrkaTools.DataTable.init();
			$.OrkaTools.Scroll.initSlimScroll(".scroller");
			resolve(true);
		});
		return promise;


	}
	, Guid: function () {
		return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
			(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16).toUpperCase()
		);
	}
	, GridGetIndexByName: function (Grid, KolonAdi) {
		var toReturn;
		var Kolonlar = Grid.columns().dataSrc().toArray();
		$.each(Kolonlar, (index, Kol) => {
			if (Kol) {

				if (Kol == KolonAdi) {
					toReturn = index;
					return;
				}
			}
		});

		return toReturn;
	}
	, BlockUi: function (msg) {
		mApp.block("body ,.modal-content", {
			overlayColor: "#000000",
			type: "loader",
			state: "success",
			message: msg
		});
	}
	, SaateCevir: function (val, maxTime = '10:00', negatifTime = false) {

		if (val === "" || val === null)
			val = "";

		// Tarih formatı ile geliyorsa
		if (val)
			if (val !== "Invalid date")
				if (val.length > 6)
					val = this.TariheCevir(val, "DD.MM.YYYY HH:mm","HH:mm");

		if (!val.startsWith("-"))
			// Gelen Değer formatlanıyor..
			val = moment(val, "HH:mm").format("HH:mm");

		// Değerin uygunluğu kontrol ediliyor
		if (val === "Invalid date")
			val = "";
		//
		if (!negatifTime) {
			var Fark = moment(maxTime, "HH:mm").diff(moment(val, "HH:mm"));

			if (Fark < 0)
				val = "";
		}
		return val;

	}
	, TariheCevir: function (val, gelenFormat, cikisFormat) {

		gelenFormat = gelenFormat || this.Defaults.DateTimeFormat;

		val = moment(val, gelenFormat);

		if (cikisFormat)
			val = val.format(cikisFormat);
		//
		if (val === "Invalid date")
			val = "";
		//
		return val;
	}
	
	, UnBlock: function () {
		setTimeout(function () {
			mApp.unblock();
			mApp.unblock(".modal-content");
		}, 100);
	}

	, Format: {
		Tarih: function (tarih, formats) {
			if (formats == undefined)
				return moment(tarih).format('DD/MM/YYYY');
			else return moment(tarih).format(formats);
		},
		Sayi: function (sayi, format) {

			return 0;
		}

	}
	, DataTable: {
		init: function () {

			(function (factory) {
				if (typeof define === 'function' && define.amd) {
					// AMD
					define(['jquery', 'datatables', 'datatables-editor'], factory);
				}
				else if (typeof exports === 'object') {
					// Node / CommonJS
					module.exports = function ($, dt) {
						if (!$) { $ = require('jquery'); }
						factory($, dt || $.fn.dataTable || require('datatables'));
					};
				}
				else if (jQuery) {
					// Browser standard
					factory(jQuery, jQuery.fn.dataTable);
				}
			}(function ($, DataTable) {
				'use strict';


				if (!DataTable.ext.editorFields) {
					DataTable.ext.editorFields = {};
				}

				var _fieldTypes = DataTable.Editor ?
					DataTable.Editor.fieldTypes :
					DataTable.ext.editorFields;


				_fieldTypes.mask = {
					create: function (conf) {
						conf._input = $('<input/>').attr($.extend({
							id: DataTable.Editor.safeId(conf.id),
							type: 'text'
						}, conf.attr || {}));

						conf._input.mask(conf.mask, $.extend({
							placeholder: conf.placeholder || conf.mask.replace(/[09#AS]/g, '_')
						}, conf.maskOptions));

						return conf._input[0];
					},

					get: function (conf) {
						return conf._input.val();
					},

					set: function (conf, val) {
						conf._input
							.val(val)
							.trigger('change')
							.trigger('input.mask')
							.trigger('keyup.mask');
					},

					enable: function (conf) {
						conf._input.prop('disabled', false);
					},

					disable: function (conf) {
						conf._input.prop('disabled', true);
					},

					canReturnSubmit: function (conf, node) {
						return true;
					}
				};

				_fieldTypes.timemask = {
					create: function (conf) {
						conf._input = $('<input/>').attr($.extend({
							id: DataTable.Editor.safeId(conf.id),
							type: 'text'
						}, conf.attr || {}));

						conf._input.mask(conf.mask, $.extend({
							placeholder: conf.placeholder || conf.mask.replace(/[09#AS]/g, '_')
						}, conf.maskOptions));

						return conf._input[0];
					},

					get: function (conf) {
						var val = conf._input.val();
						if (val === "" || val === null)
							val = "";

						// Tarih formatı ile geliyorsa
						if (val)
							if (val !== "Invalid date")
								if (val.length > 5)
									val = moment(val, 'DD.MM.YYYY HH:mm').format("HH:mm");

						// Gelen Değer formatlanıyor..
						val = moment(val, "HH:mm").format("HH:mm");

						// Değerin uygunluğu kontrol ediliyor
						if (val === "Invalid date")
							val = "";
						//
						var Fark = moment(conf.maskOptions.maxtime, "HH:mm").diff(moment(val, "HH:mm"));

						if (Fark < 0)
							val = "";

						return val;
					},

					set: function (conf, val) {
						//
						if (val === "00:00")
							val = "";

						// Tarih formatı ile geliyorsa
						if (val)
							if (val !== "Invalid date") {
								if (val.length > 5)
									val = moment(val, 'DD.MM.YYYY HH:mm').format("HH:mm");
								//
								//conf._input
								//	.val(val)
								//	.trigger('change')
								//	.trigger('input.mask')
								//	.trigger('keyup.mask');
							}

						conf._input
							.val(val)
							.trigger('change')
							.trigger('input.mask')
							.trigger('keyup.mask');
					},

					enable: function (conf) {
						conf._input.prop('disabled', false);
					},

					disable: function (conf) {
						conf._input.prop('disabled', true);
					},

					canReturnSubmit: function (conf, node) {
						return true;
					}
				};


			}));
			var singleSelect = $('.datatable-selection-single').DataTable();
			$('.datatable-selection-single tbody').on('click', 'tr', function () {
				if ($(this).hasClass('table-success')) {
					$(this).removeClass('table-success');
				}
				else {
					$('tr.table-success').removeClass('table-success');
					$(this).addClass('table-success');
				}
			});

			$('.datatable-selection-multiple').DataTable();
			$('.datatable-selection-multiple tbody').on('click', 'tr', function () {
				$(this).toggleClass('table-success');
			});
		}
		, Olustur: function (Tablo_Adi, Veri, Kolonlar, Standart_Arama_Aktif, arama_alani, siralamaalani, $compile, $scope, domKullan, $editor) {
			return new Promise((r, s) => {
				if (!$().DataTable) {
					console.warn('Hata - datatables.min.js yüklenemedi...');
					return;
				}


				$.fn.dataTable.ext.errMode = 'none';

				if (Standart_Arama_Aktif === undefined)
					Standart_Arama_Aktif = true;

				if (domKullan === undefined)
					domKullan = true;

				var domz = "";
				//
				if (domKullan) {
					if (!Standart_Arama_Aktif)
						domz = "<'row'<'col-sm-12 hidden-sm text-right'B>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>";
					else domz = "<'row'<'col-sm-6 hidden-sm text-left 'f><'col-sm-6 text-right'B><'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>";
				}
				else {
					domz = "<'row'<'col-sm-6 hidden-sm text-left '><'col-sm-6 text-right'><'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'><'col-sm-12 col-md-7 dataTables_pager'lp>>";
				}
				if (siralamaalani.length === 0)
					siralamaalani = [];

				var Buttons = [
					{
						extend: 'excelHtml5',
						text: '<i class="fa fa-file-excel label-medium font-parlamentmavisi"></i>',
						titleAttr: 'Excel',
						title: 'RAPOR',
						exportOptions: {
							columns: ':visible'
						}

					},

					{
						extend: 'pdfHtml5',
						text: '<i class="fa fa-file-pdf label-medium font-parlamentmavisi"></i>',
						//className: 'btn m-btn--sm btn-danger m-btn m-btn--air m-btn--icon m-btn--pill',
						titleAttr: 'PDF',
						exportOptions: {
							columns: ':visible'
						}
					},
					{
						text: '<i class="fa fa-compress"></i>',
						action: function (e, dt, node, config) {
							$.fn.dataTable.tables({ visible: true, api: true }).columns.adjust().responsive.recalc().scroller.measure();
						}
					},

					{
						extend: 'colvis',
						text: '',
						className: 'btn m-btn m-btn--air m-btn--icon m-btn--pill',
						collectionLayout: 'fixed two-column'
					}];
				//if ($editor !== undefined) {

				//	Buttons.push({ extend: 'create', editor: $editor });
				//	Buttons.push({ extend: 'edit', editor: $editor });
				//	Buttons.push({ extend: 'remove', editor: $editor });

				//}

				$.extend(true, $.fn.dataTable.Editor.defaults, {
					"i18n": {
						"create": {
							"button": "Yeni",
							"title": "<h5 class=\"modal-title\">Yeni kayıt oluştur</h5>",
							"submit": "Oluştur"
						},
						"edit": {
							"button": "Düzelt",
							"title": "<h5 class=\"modal-title\">Düzelt</h5>",
							"submit": "Güncelle"
						},
						"remove": {
							"button": "Sil",
							"title": "<h5 class=\"modal-title\">Sil</h5>",
							"submit": "Sil",
							"confirm": {
								"1": "Seçilen satır silinecek, Onaylıyor musunuz?",
								"_": "%d satır silinecek, Onaylıyor musunuz?"
							}
						},
						"error": {
							"system": "Sistem hatası ile karşılaşıldı.)."
						},
						"multi": {
							"title": "Çoklu değerler",
							"info": "The selected items contain different values for this input. To edit and set all items for this input to the same value, click or tap here, otherwise they will retain their individual values.",
							"restore": "Değişikliği geri al",
							"noMulti": "This input can be edited individually, but not part of a group."
						},
						"datetime": {
							"previous": "Geri",
							"next": "İleri",
							"months": [
								"Ocak",
								"Şubat",
								"Mart",
								"Nisan",
								"Mayıs",
								"Hazır",
								"Temmuz",
								"Ağustos",
								"Eylül",
								"Ekim",
								"Kasım",
								"Aralık"
							],
							"weekdays": [
								"Pzr",
								"Pzt",
								"Sal",
								"Çrs",
								"Prş",
								"Cum",
								"Cts"
							],
							"amPm": [
								"am",
								"pm"
							],
							"hours": "Saat",
							"minutes": "Dak.",
							"seconds": "San.",
							"unknown": "-"
						}
					}
				});

				var orkDataTable = $(Tablo_Adi).DataTable({
					language: {

						"sDecimal": ",",
						"sEmptyTable": "Veri yok",
						"sInfo": "(_TOTAL_) _START_ - _END_ listeleniyor",
						"sInfoEmpty": "Kayıt yok",
						"sInfoFiltered": "(_MAX_ kayıt içerisinden bulunan)",
						"sInfoPostFix": "",
						"sInfoThousands": ".",
						"sLengthMenu": "_MENU_ göster",
						"sLoadingRecords": "Yükleniyor...",
						"sProcessing": "İşleniyor...",
						"sSearch": "Ara:",
						"sZeroRecords": "Eşleşen kayıt bulunamadı",
						"oPaginate": {
							"sFirst": "İlk",
							"sLast": "Son",
							"sNext": ">",
							"sPrevious": "<"
						},
						"oAria": {
							"sSortAscending": ": artan sütun sıralamasını aktifleştir",
							"sSortDescending": ": azalan sütun sıralamasını aktifleştir"
						},
						"select": {
							"rows": {
								"0": "",
								"1": "1 kayıt seçildi",
								"_": "%d kayıt seçildi"
							}
						}
					}
					//,select: {
					//    style: 'multi',
					//    selector: 'td:first-child'
					//}
					, order: siralamaalani
					, "destroy": true
					, scrollY: "50vh"
					, scrollX: true
					, scrollCollapse: true
					, autoWidth: false
					, info: Veri.length > 5
					, paging: Veri.length > 50
					, pageLength: 50
					, searching: true
					//, stateSave: true
					, colReorder: true
					//, rowReorder: true
					//, autoFill : true
					//, keys: true
					, dom: domz
					, buttons: Buttons
					, select: {
						style: 'os',
						//selector: 'td',
						blurable: false
					}
					, data: Veri
					, columns: Kolonlar
					, createdRow: function (row, data, dataIndex) {
						$compile(angular.element(row).contents())($scope);
					}
				});

				//$.fn.dataTable.tables({ visible: true, api: true }).columns.adjust().responsive.recalc().scroller.measure();

				if (arama_alani !== null || arama_alani !== undefined) {

					$(arama_alani).on('keyup', function () {

						var Deger = $(arama_alani).val();
						orkDataTable.search(Deger).draw();
					});
				}

				r(orkDataTable);
				//return orkDataTable;
			});
		}
	}
	, Servis: {}
	, OrkaController: {}
	, SummerNote: {
		init: function() {
			$(".summernote").summernote({
				lang:'tr-TR',
				height: 200,
				placeholder: 'Buraya yazınız...',
				tabsize: 2,
				codeviewFilter: false,
				codeviewIframeFilter: true,
				dialogsInBody: true,
				dialogsFade: true  // Add fade effect on dialogs


			});
			$(".summernote").on("summernote.enter", function (we, e) {
				$(this).summernote("pasteHTML", "<br><br>");
				e.preventDefault();
			});
		}
	}
	, DatePickers: {
		init: function () {
			var t = {
				leftArrow: '<i class="la la-angle-left"></i>',
				rightArrow: '<i class="la la-angle-right"></i>'
			};

		}

	}
	, Scroll: {
		initSlimScroll: function (el) {
			$(el).each(function () {
				if ($(this).attr("data-initialized")) {
					return; // exit
				}

				var height;

				if ($(this).attr("data-height")) {
					height = $(this).attr("data-height");
				} else {
					height = $(this).css('height');
				}

				$(this).slimScroll({
					allowPageScroll: true, // allow page scroll when the element scroll is ended
					size: '10px',
					color: ($(this).attr("data-handle-color") ? $(this).attr("data-handle-color") : '#363836'),
					wrapperClass: ($(this).attr("data-wrapper-class") ? $(this).attr("data-wrapper-class") : 'slimScrollDiv'),
					railColor: ($(this).attr("data-rail-color") ? $(this).attr("data-rail-color") : '#eaeaea'),
					position: 'right',
					height: height,
					axis: 'both',
					alwaysVisible: true,//($(this).attr("data-always-visible") == "1" ? true : false),
					railVisible: false,//($(this).attr("data-rail-visible") == "1" ? true : false),
					disableFadeOut: true
				});

				$(this).attr("data-initialized", "1");
			});
		}
		, destroySlimScroll: function (el) {
			$(el).each(function () {
				if ($(this).attr("data-initialized") === "1") { // destroy existing instance before updating the height
					$(this).removeAttr("data-initialized");
					$(this).removeAttr("style");

					var attrList = {};

					// store the custom attribures so later we will reassign.
					if ($(this).attr("data-handle-color")) {
						attrList["data-handle-color"] = $(this).attr("data-handle-color");
					}
					if ($(this).attr("data-wrapper-class")) {
						attrList["data-wrapper-class"] = $(this).attr("data-wrapper-class");
					}
					if ($(this).attr("data-rail-color")) {
						attrList["data-rail-color"] = $(this).attr("data-rail-color");
					}
					if ($(this).attr("data-always-visible")) {
						attrList["data-always-visible"] = $(this).attr("data-always-visible");
					}
					if ($(this).attr("data-rail-visible")) {
						attrList["data-rail-visible"] = $(this).attr("data-rail-visible");
					}

					$(this).slimScroll({
						wrapperClass: ($(this).attr("data-wrapper-class") ? $(this).attr("data-wrapper-class") : 'slimScrollDiv'),
						destroy: true
					});

					var the = $(this);

					// reassign custom attributes
					$.each(attrList, function (key, value) {
						the.attr(key, value);
					});

				}
			});
		}
	}
	, Iframe: function (adres, Raporadi, IframeDesignerShow) {
		$("#_Iframe").contents().find("body").html("");
		$('#_Iframe').attr('src', adres);
		$("#modalIFrame").modal('show');
		this.OrkaController.vm.IframeRaporBasligi = Raporadi;
		this.OrkaController.vm.IframeDesignerShow = IframeDesignerShow;
		this.OrkaController.vm.safeApply();
	}
	, Strings: {
		TurkceKarakterTemizle: function (_string) {
			var charMap = {
				Ç: 'C',
				Ö: 'O',
				Ş: 'S',
				İ: 'I',
				I: 'i',
				Ü: 'U',
				Ğ: 'G',
				ç: 'c',
				ö: 'o',
				ş: 's',
				ı: 'i',
				ü: 'u',
				ğ: 'g'
			};

			var str = _string;
			str_array = str.split('');

			for (var i = 0, len = str_array.length; i < len; i++) {
				str_array[i] = charMap[str_array[i]] || str_array[i];
			}

			str = str_array.join('');

			var clearStr = str.replace(" ", "").replace("-", "").replace(/[^a-z0-9-.çöşüğı]/gi, "");
			return clearStr;
		}
	}
};
