(function () {
    'use strict';

    var cssTaxZoneAdminClass = function (options) {
        this.init(options);
    };

    cssTaxZoneAdminClass.VERSION = '1.0.1';
    cssTaxZoneAdminClass.DEFAULTS = { 
  			showDebug : true,
			templateSelectors:  {
				'nova': {
					'default': {
						selector_position: "off",
						selector: "#content",
						selector_artikel_position: "append",
						selector_artikel: ".product-offer .vat_info"
					},
				},
				'snackys': {
					'default': {
						selector_position: "off",
						selector: "#content",
						selector_artikel_position: "append",
						selector_artikel: ".product-offer .vat_info"
					},
				},
				'admorris': {
					'default': {
						selector_position: "off",
						selector: "#content",
						selector_artikel_position: "append",
						selector_artikel: ".product-info-inner .vat_info"
					},
				},
				'salepix': {
					'default': {
						selector_position: "off",
						selector: "#content",
						selector_artikel_position: "append",
						selector_artikel: ".product-offer .vat_info"
					},
				},
				'easytemplate': {
					'default': {
						selector_position: "off",
						selector: "#content",
						selector_artikel_position: "append",
						selector_artikel: ".product-offer .vat_info"
					},
				},
			},
    };

    cssTaxZoneAdminClass.prototype = {

        constructor: cssTaxZoneAdminClass,

        init: function (options) {
            this.options = $.extend({}, cssTaxZoneAdminClass.DEFAULTS, options);
            var that = this;
            that.initFlagButtons();
            that.initGetGeoIP();
            that.codemirror();
        },

        register: function(options) {
        	var that=this;
        	this.debug("ich starte cssTaxZoneAdminClass.VERSION " +  this.__proto__.constructor.VERSION);
					that.initTemplateSelectors();
					that.docu();
					that.codemirror();
        },
        
        debug: function(s) {
        	if(this.options.showDebug) {
        		console.log(s);
        	}
        },

        _set: function(key,value) {
        	this.options.key = value;
        },
    		

        initGetGeoIP: function() {
        	var that=this;
        	that.debug("initialisiere geoIPImport");
        	$(document).on("click", ".geoIPImport", function() {
          	that.debug("starte geoIPImport");

      			var url = location.href;
      			var data = data = 'jtl_token=' + $(this).closest('form').find('.jtl_token').val() + '&cssAdminConfigAction=getGeoIP&token=' + $(this).closest('form').find('#maxMindUserKey').val();
      			that.post_data(url,data);		
        	});
        },
        
        initFlagButtons: function () {
        	var that = this;
        	$(document).on("click" , ".css-flag-button", function(e) {
        		e.preventDefault();
        		var data = 'jtl_token=' + $(this).closest('form').find('.jtl_token').val() + '&cssAdminConfigAction=' + 'showFlags&element=' +  $(this).attr("id");
        		that.post_data($(this).closest('form').attr('action'),data);
        	});
        },

			docu: function() {
				var that = this;
				$(document).on("click", "[data-section]", function () {
					var pluginID = $(this).closest("form").data('plugin');
					var data = "io=" + pluginID +  "&jtl_token=" + $(this).closest("form").data("session") + "&action=docu&section=" + $(this).data('section');
					var url = $(this).closest("form").data("io");
					that.post_data(url, data);
				});
			},


			initTemplateSelectors: function() {
				var that = this;
				$(document).on("click", "[data-template]", function() {
					var tSelectors = that.options.templateSelectors[$(this).data('template')];
					console.log(tSelectors);
					Object.entries(tSelectors).forEach(entry => {
						const [key, value] = entry;
						Object.entries(value).forEach(entry => {
							const [key, value] = entry;
							console.log(key,value);
							$("[name='" + key + "']").val(value);
						});
					});
				});
			},


			codemirror: function() {
				$(function() {
					var editorsSmarty = [],
						editorsSass = [],
						editorsHtml = [],
						editorsCSS = [],
						editorsJS = [],
						editorsSQL = [];


					function wc_hex_is_light(color) {
						const hex = color.replace('#', '');
						const c_r = parseInt(hex.substr(0, 2), 16);
						const c_g = parseInt(hex.substr(2, 2), 16);
						const c_b = parseInt(hex.substr(4, 2), 16);
						const brightness = ((c_r * 299) + (c_g * 587) + (c_b * 114)) / 1000;
						return brightness > 155;
					}

					$(document).ready(function () {
						var idListSmarty = $('.css-codemirror.smarty'),
							idListHTML = $('.css-codemirror.html'),
							idListSASS = $('.css-codemirror.sass'),
							idListSQL = $('.css-codemirror.sql'),
							idListCSS = $('.css-codemirror.css'),
							idListJavaScript = $('.css-codemirror.JavaScript'),
							codemirrorTheme = wc_hex_is_light($(':root').css('--body-bg')) ? 'default' : 'ayu-dark';
						idListHTML.each(function (idx, elem) {
							if (elem.id && elem.id.length > 0 && $("#" +elem.id ).hasClass("initialized") == false) {
								editorsHtml[elem.id] = CodeMirror.fromTextArea(document.getElementById(elem.id), {
									lineNumbers:    true,
									mode:           'htmlmixed',
									scrollbarStyle: 'simple',
									lineWrapping:   true,
									readOnly:	($("#"+elem.id).hasClass("readonly")) ? true : false,
									extraKeys:      {
										'Ctrl-Space': function (cm) {
											cm.setOption('fullScreen', !cm.getOption('fullScreen'));
										},
										'Esc':        function (cm) {
											if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
										}
									},
									theme: codemirrorTheme
								});
								$("#" +elem.id ).addClass("initialized");
								$("#cssExpertModus").on('shown.bs.collapse', function () {
									editorsHtml[elem.id].refresh();
								});
								$('#myModalInfo').on('shown.bs.modal', function (e) {
									editorsHtml[elem.id].refresh();
								});
								$('.tabs-nav a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
									editorsHtml[elem.id].refresh();
								});
							}
						});
						idListJavaScript.each(function (idx, elem) {
							if (elem.id && elem.id.length > 0 && $("#" +elem.id ).hasClass("initialized") == false) {
								editorsJS[elem.id] = CodeMirror.fromTextArea(document.getElementById(elem.id), {
									lineNumbers:    true,
									mode:           'javascript',
									scrollbarStyle: 'simple',
									lineWrapping:   true,
									readOnly:	($("#"+elem.id).hasClass("readonly")) ? true : false,
									extraKeys:      {
										'Ctrl-Space': function (cm) {
											cm.setOption('fullScreen', !cm.getOption('fullScreen'));
										},
										'Esc':        function (cm) {
											if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
										}
									},
									theme: codemirrorTheme
								});
								$("#" +elem.id ).addClass("initialized");
								$("#cssExpertModus").on('shown.bs.collapse', function () {
									editorsJS[elem.id].refresh();
								});
								$('#myModalInfo').on('shown.bs.modal', function (e) {
									editorsJS[elem.id].refresh();
								});
								$('.tabs-nav a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
									editorsJS[elem.id].refresh();
								});
							}
						});
						idListCSS.each(function (idx, elem) {
							if (elem.id && elem.id.length > 0 && $("#" +elem.id ).hasClass("initialized") == false) {
								editorsCSS[elem.id] = CodeMirror.fromTextArea(document.getElementById(elem.id), {
									lineNumbers:    true,
									mode:           'css',
									scrollbarStyle: 'simple',
									lineWrapping:   true,
									readOnly:	($("#"+elem.id).hasClass("readonly")) ? true : false,
									extraKeys:      {
										'Ctrl-Space': function (cm) {
											cm.setOption('fullScreen', !cm.getOption('fullScreen'));
										},
										'Esc':        function (cm) {
											if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
										}
									},
									theme: codemirrorTheme
								});
								$("#" +elem.id ).addClass("initialized");
								$("#cssExpertModus").on('shown.bs.collapse', function () {
									editorsCSS[elem.id].refresh();
								});
								$('#myModalInfo').on('shown.bs.modal', function (e) {
									editorsCSS[elem.id].refresh();
								});
								$('.tabs-nav a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
									editorsCSS[elem.id].refresh();
								});
							}
						});
						idListSASS.each(function (idx, elem) {
							if (elem.id && elem.id.length > 0 && $("#" +elem.id ).hasClass("initialized") == false) {
								editorsSass[elem.id] = CodeMirror.fromTextArea(document.getElementById(elem.id), {
									lineNumbers:    true,
									mode:           'sass',
									scrollbarStyle: 'simple',
									lineWrapping:   true,
									readOnly:	($("#"+elem.id).hasClass("readonly")) ? true : false,
									extraKeys:      {
										'Ctrl-Space': function (cm) {
											cm.setOption('fullScreen', !cm.getOption('fullScreen'));
										},
										'Esc':        function (cm) {
											if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
										}
									},
									theme: codemirrorTheme
								});
								$("#" +elem.id ).addClass("initialized");
								$("#cssExpertModus").on('shown.bs.collapse', function () {
									editorsSass[elem.id].refresh();
								});
								$('#myModalInfo').on('shown.bs.modal', function (e) {
									editorsSass[elem.id].refresh();
								});
								$('.tabs-nav a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
									editorsSass[elem.id].refresh();
								});
							}
						});
						idListSmarty.each(function (idx, elem) {
							if (elem.id && elem.id.length > 0 && $("#" +elem.id ).hasClass("initialized") == false) {
								editorsSmarty[elem.id] = CodeMirror.fromTextArea(document.getElementById(elem.id), {
									lineNumbers:    true,
									lineWrapping:   true,
									mode:           'smartymixed',
									scrollbarStyle: 'simple',
									readOnly:	($("#"+elem.id).hasClass("readonly")) ? true : false,
									extraKeys:      {
										'Ctrl-Space': function (cm) {
											cm.setOption('fullScreen', !cm.getOption('fullScreen'));
										},
										'Esc':        function (cm) {
											if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false);
										}
									},
									theme: codemirrorTheme
								});
								$("#" +elem.id ).addClass("initialized");
								$("#cssExpertModus").on('shown.bs.collapse', function () {
									editorsSmarty[elem.id].refresh();
								});
								$('#myModalInfo').on('shown.bs.modal', function (e) {
									editorsSmarty[elem.id].refresh();
								});
								$('.tabs-nav a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
									editorsSmarty[elem.id].refresh();
								});
							}
						});
						idListSQL.each(function (idx, elem) {
							if (elem.id && elem.id.length > 0 && $("#" +elem.id ).hasClass("initialized") == false) {
								var hint = $('#' + elem.id).data('hint');
								editorsSQL[elem.id] = CodeMirror.fromTextArea(document.getElementById(elem.id), {
									mode: 'text/x-mysql',
									scrollbarStyle: 'simple',
									lineWrapping:   true,
									smartIndent: true,
									lineNumbers: true,
									matchBrackets : true,
									autofocus: true,
									readOnly:	($("#"+elem.id).hasClass("readonly")) ? true : false,
									extraKeys: {"Ctrl-Space": "autocomplete"},
									hintOptions: hint,
									theme: codemirrorTheme
								});
							}
							$("#" +elem.id ).addClass("initialized");
							$("#cssExpertModus").on('shown.bs.collapse', function () {
								editorsSQL[elem.id].refresh();
							});
							$('#myModalInfo').on('shown.bs.modal', function (e) {
								editorsSQL[elem.id].refresh();
							});
							$('.tabs-nav a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
								editorsSQL[elem.id].refresh();
							});
						});
					});

					// Handler for .ready() called.
				});

			},

        post_data: function (url, data) {
        	console.log(data);
        	var that = this;	
	      	jQuery.ajax({
					type: 'POST',
					url: url,
					data: data,
					showNoSuggestionNotice: true,
					dataType: 'json',
			    beforeSend: function(jqXHR) {
		        jqXHR.overrideMimeType('text/json;charset=iso-8859-1');
			    },
					success: function(data,responseText,jqXHR) {
						if( jqXHR.status == 204 ) {
							that.debug('sorry, here is nothing to do for me. (Token problem?)')
							return false;
						}
						if( jqXHR.status == 404 ) {
							that.debug('sorry, here is nothing to show you.')
							return false;
						}
						if( jqXHR.status == 403 ) {
							that.debug('sorry, this is no place for you.')
							return false;
						}
						//debug(data);
						if( data.script )	{
							eval(data.script);
						}
					},
					error: function() {
						that.debug('something is wrong....anything buggy?');
					},
					complete: function() {
					}
			});
		},
   };

    $.cssTaxZoneAdmin = function(options) {
    	console.log("starte cssTaxZone");
    	$.cssTaxZoneAdmin = new cssTaxZoneAdminClass(options);
    	$.cssTaxZoneAdmin.register();
    	return $.cssTaxZoneAdmin;
    };
    $.cssTaxZoneAdmin();
})(jQuery);


