/* global wpjConfig showInfoMessage BigNumber */
// noinspection EqualityComparisonWithCoercionJS
/* eslint-disable max-len, no-empty */

export function priceVatDropdown($element, initialValue) {
   var $dropdown = $element.find('[data-dropdown]'),
       $dropdownState = $element.find('[data-dropdown-state]'),
       $price = $element.find('[data-price]'),
       $priceVat = $element.find('[data-price-vat]'),
       $Vat = $element.find('[data-vat]');

   $dropdown.on('click', 'li a', function() {
      $dropdownState.html($(this).html());

      var $this = $(this),
          value = $this.data('value'),
          oldValue = $priceVat.val(),
          vat = parseFloat($Vat.length ? $Vat.val() : $priceVat.data('price-vat'));

      $priceVat.val(value);

      if (oldValue != value) {
         if ($price.val() != '') {
            switch (value) {
            case 1:
               $price.val(formatPrice($price.val() * (100 + vat) / 100, 2));
               break;
            case 0:
               $price.val(formatPrice($price.val() * 100 / (100 + vat)));
               break;
            }
            $('input[name=data\\[discount\\]]').keyup();
         }
      }
   });

   if (initialValue !== undefined) {
      $dropdown.find('li a[data-value="' + initialValue + '"]').click();
   }
}

export function getWindowUrl(type, ID, param1, param2) {
   var winUrl = '';
   var winName = '';
   var winParam = 'toolbar=no,menubar=no,location=no,directories=no,scrollbars=yes,resizable=no,status=no';
   var sizeX = 1010;
   var sizeY = 700;

   if (param1 == undefined) {
      param1 = '';
   }

   if (type == 'stockInMissing') {
      type = 'product';
   }
   // ************************************** \\
   if (type == 'settings') {
      winUrl = 'launch.php?s=settings.php' + param1;
      winName = 'settings';
   } else
   // ************************************** \\
   if (type == 'pos') {
      winUrl = 'launch.php?s=pos.php&display=1' + param1;
      winName = 'pos';
   } else
   // ************************************** \\

   if (type == 'product') {
      winUrl = 'launch.php?s=products.php&acn=edit&ID=' + ID;
      if (param1 == 'noopener') {
         winUrl = winUrl + '&refresh=noopener';
      }
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=products.php&acn=add&' + param1;
      } else if (param1 == 'duplicate') {
         winUrl = 'launch.php?s=products.php&acn=add&Duplicate=1&ID=' + ID;
      } else if (param1 && param1 != 'noopener') {
         winUrl = winUrl + '&' + param1;
      }
      winName = 'product' + ID.toString();
      sizeX = 1050;
      sizeY = 750;
   } else
   // ************************************** \\
   if (type == 'order') {
      winUrl = 'launch.php?s=orders.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=orders.php&acn=add';
      }
      if (param1) {
         winUrl += '&' + param1;
      }
      winName = 'order' + ID.toString();
      sizeX = 1220;
      sizeY = 900;
   } else
   // ************************************** \\
   if (type == 'sections') {
      winUrl = 'launch.php?s=sections.php&acn=edit&ID=' + ID;
      if (ID == null || ID == '') {
         winUrl = 'launch.php?s=sections.php&acn=add';
      }
      winName = 'section' + (ID != null ? ID.toString() : '');
      if (param1 == 'remove') {
         winUrl = 'launch.php?s=sections.php&acn=remove&ID=' + ID;
         winName = 'sectionErase';
      } else if (param1 != null) {
         winUrl += '&' + param1;
      }
   } else
   // ************************************** \\
   if (type == 'producer') {
      winUrl = 'launch.php?s=producers.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=producers.php&acn=add';
      } else if (param1 == 'duplicate') {
         winUrl = 'launch.php?s=producers.php&acn=add&Duplicate=1&ID=' + ID;
      }
      winName = 'producer' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'user') {
      winUrl = 'launch.php?s=users.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=users.php&acn=add';
      }
      if (parseInt(param1) > 0) {
         winUrl += '&flap=' + param1;
      }
      winName = 'user' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'admin') {
      winUrl = 'launch.php?s=admins.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=admins.php&acn=add';
      }
      winName = 'admin' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'password') {
      winUrl = 'launch.php?s=admins.php&acn=passw';
      winName = 'password';
   } else
   // ************************************** \\
   if (type == 'settings') {
      winUrl = 'launch.php?s=settings.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=settings.php&acn=add';
      }
      winName = 'settings' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'delivery') {
      winUrl = 'launch.php?s=deliverytypes.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=deliverytypes.php&acn=add';
      }
      winName = 'delivery' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'menu') {
      winUrl = 'launch.php?s=menulinks.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=menulinks.php&acn=add';
      }
      winName = 'menu' + ID.toString();
      if (param1) {
         winUrl = 'launch.php?s=menulinks.php&acn=add&data[id_menu]=' + param1;
      }
   } else
   // ************************************** \\
   if (type == 'inquiry') {
      winUrl = 'launch.php?s=inquiries.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=inquiries.php&acn=add';
      }
      winName = 'inquiry' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'page') {
      sizeX = 750;
      sizeY = 600;
      winUrl = 'launch.php?s=pages.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=pages.php&acn=add';
      }
      winName = 'page' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'newsletter') {
      winUrl = 'launch.php?s=newsletter.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=newsletter.php&acn=add';
      }
      winName = 'newsletter' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'discount') {
      winUrl = 'launch.php?s=discounts.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=discounts.php&acn=add&condition_type=' + param1;
      }
      winName = 'discount' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'parameter') {
      winUrl = 'launch.php?s=parameters.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=parameters.php&acn=add';
      }
      winName = 'parameter' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'vat') {
      winUrl = 'launch.php?s=vats.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=vats.php&acn=add';
      }
      winName = 'vat' + ID.toString();
   }
   // ************************************** \\
   else if (type == 'comment') {
      winUrl = 'launch.php?s=comments.php&acn=edit&ID=' + ID;
      if ((ID == null || ID == 0) && param1 != null) {
         winUrl = 'launch.php?s=comments.php&acn=add&IDitem=' + param1;
      }
      winName = 'comment' + ID.toString();

   } else
   // ************************************** \\
   if (type == 'pricelevel') {
      winUrl = 'launch.php?s=pricelevels.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=pricelevels.php&acn=add';
      }
      winName = 'pricelevel' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'factorage') {
      winUrl = 'launch.php?s=factorages.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=factorages.php&acn=add';
      }
      winName = 'factorage' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'article') {
      winUrl = 'launch.php?s=articles.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=articles.php&acn=add';
      }
      winName = 'article' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'artsection') {
      winUrl = 'launch.php?s=artsections.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=artsections.php&acn=add';
      }
      winName = 'artsection' + ID.toString();
      if (param1 == 'erase') {
         winUrl = 'launch.php?s=artsections.php&acn=erase&ID=' + ID;
         winName = 'artsectionErase';
      }
   } else
   // ************************************** \\
   if (type == 'artauthor') {
      winUrl = 'launch.php?s=artauthors.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=artauthors.php&acn=add';
      }
      winName = 'artauthor' + ID.toString();
   } else
   // ************************************** \\
   if (type == 'photo') {
      winUrl = 'launch.php?s=photos.php&acn=edit&ID=' + ID;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=photos.php&acn=add';
      }

      if (param1 == 'erase') {
         winUrl = 'launch.php?s=photos.php&acn=erase&ID=' + ID;
      } else if (param1 == 'product' && parseInt(param2) > 0) {
         winUrl += '&ID=' + parseInt(param2);
      } else if (param1 == 'article' && parseInt(param2) > 0) {
         winUrl += '&IDa=' + parseInt(param2);
      }

      //winUrl += serverVars[2];
      winName = type + ID.toString();
   } else
   // ************************************** \\
   if (type == 'checktimeout') {
      winUrl = 'launch.php?s=checktimeout.php';
      winName = 'checktimeout';
   } else
   // ************************************** \\
   if (type == 'productOrders') {
      winUrl = 'launch.php?s=list.php&type=orders&window=1&productId=' + ID + '&variationId=' + param1;
      if (param2 != null) {
         winUrl += param2;
      }
      winName = 'productOrders';
   } else
   // ************************************** \\
   if (type == 'discountOrders') {
      winUrl = 'launch.php?s=list.php&type=orders&window=1&discount=' + ID;
      if (param2 != null) {
         winUrl += param2;
      }
      winName = 'discountOrders';
   } else
   // ************************************** \\
   if (type == 'orderDiscountOrders') {
      winUrl = 'launch.php?s=list.php&type=orders&window=1&order_discounts=' + ID;
      if (param2 != null) {
         winUrl += param2;
      }
      winName = 'orderDiscountOrders';
   } else
   // ************************************** \\
   if (type == 'userOrders') {
      winUrl = 'launch.php?s=list.php&type=orders&window=1&userId=' + ID + '&' + param1;
      winName = 'userOrders';
   } else
   // ************************************** \\
   if (type == 'orderPayments') {
      winUrl = 'launch.php?s=list.php&type=orderPayment&window=1&ID=' + ID;
      winName = 'orderPayments';
      sizeX = 1000;
      sizeY = 300;
   } else
   // ************************************** \\
   if (type == 'variationValueProducts') {
      winUrl = 'launch.php?s=list.php&type=products&window=1&IDvv=' + ID;
      winName = 'variationValueProducts';
   } else
   // ************************************** \\
   if (type == 'productsVarLabels') {
      winUrl = 'launch.php?s=' + type + '.php&acn=edit&ID=' + ID + '&' + param1;
      winName = 'productsVarLabels';
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=' + type + '.php&acn=add';
      }
      if (param1 == 'deleteValue') {
         winUrl = 'launch.php?s=productsVarLabels.php&acn=deleteValue&valueId=' + ID;
         winName = 'productsVarLabels';
      }
   } else
   // ************************************** \\
   if (type == 'productStockIn') {
      winUrl = 'launch.php?s=list.php&type=stockIn&IDp=' + ID;
      if (param1) {
         winUrl += '&IDv=' + param1;
      }
      winName = 'productStockIn';
   } else
   // ************************************** \\
   if (type == 'productCodes') {
      winUrl = 'launch.php?s=list.php&type=productsOfSuppliers&window=1&acn=edit&productId=' + ID;
      if (param1) {
         winUrl += '&variationId=' + param1;
      }
      winName = 'productCodes';
   } else
   // ************************************** \\
   if (type == 'inventoryMissing') {
      return getWindowUrl('product', ID.split(':')[0]);
   } else
   // ************************************** \\
   if (type == 'emailTest') {
      winUrl = 'launch.php?s=emails.php&acn=test&type=' + param1;
      winName = 'productsList';
   } else
   // ************************************** \\
   if (type == 'filtersList') {
      winUrl = 'launch.php?s=list.php&type=filters&window=1&pg=' + param1;
      winName = 'FiltersList';
   } else
   // ************************************** \\
   if (type == 'addFilter') {
      var list = window.location.href;
      if (param1 == 'productsMassModification' && param2) {
         list += '&' + param2;
      }
      var urlList = encodeURIComponent(list.substr(list.indexOf('?') + 1));
      if (ID == null || ID == '') {
         winUrl = 'launch.php?s=filters.php&acn=add&pg=' + param1 + '&ls=' + urlList;
      } else {
         winUrl = 'launch.php?s=filters.php&acn=edit&ID=' + ID + '&pg=' + param1 + '&ls=' + urlList;
      }
      winName = 'addFilter';
   } else
   // ************************************** \\
   if (type == 'productsList') {
      winUrl = 'launch.php?s=list.php&type=products&window=1&' + param1;
      winName = 'productsList';
   } else
   // ************************************** \\
   if (type == 'kcfinder') {
      if (ID == 'all') {
         winUrl = '/_ckfinder/browse/';
      } else if (ID == 'other') {
         winUrl = '/_ckfinder/browse/?rsrcType=Soubory';
      } else {
         winUrl = '/_ckfinder/browse/?rsrcType=Obrázky';
      }
   } else
   // ************************************** \\
   if (type == 'warehouse_positions') {
      winUrl = 'launch.php?s=list.php&type=positions&window=1&id_product=' + ID;
      if (param1) {
         winUrl += '&id_variation=' + param1;
      }
      if (param2) {
         winUrl += '&' + param2;
      }
      winName = 'positions';
   } else
   // ************************************** \\
   if (type == 'list') {
      winUrl = 'launch.php?s=list.php&type=' + ID;
      if (param1) {
         winUrl += '&' + param1;
      }
      if (param2) {
         winUrl += '&' + param2;
      }
      winName = 'list' + ID;
   } else {
      winUrl = 'launch.php?s=' + type + '.php&acn=edit&ID=' + ID + '&' + param1;
      if (ID == null || ID == 0) {
         winUrl = 'launch.php?s=' + type + '.php&acn=add' + '&' + param1;
      }
      winName = type;
      if (ID != null) {
         winName += ID.toString();
      }
   }

   return {
      'winUrl': winUrl,
      'winName': winName,
      'winParam': winParam,
      'sizeX': sizeX,
      'sizeY': sizeY,
      'type': type,
      'ID': ID,
      'param1': param1,
      'param2': param2
   };
}

export function nw(type, ID, param1, param2) {
   var params = getWindowUrl(type, ID, param1, param2);
   var nwin;

   // set 'itemPrevNext' in opener's sessionStorage
   // (because of chrome bug
   // - Failed to read the 'sessionStorage' property from 'Window': Access is denied for this document.
   // - if setWindowStorage for new window)
   initPrevNext(null, { 'type': type, 'ID': ID });

   if (wpjConfig.nwAsTab === true) {
      nwin = window.open(params['winUrl'], params['winName']);
   } else {
      nwin = window.open(params['winUrl'], params['winName'], params['winParam'] + ',width=' + params['sizeX'] + ',height=' + params['sizeY']);
   }

   nwin.itemType = type;
   nwin.itemID = ID;

   try {
      nwin.focus();
      centerWindow(nwin, [params['sizeX'], params['sizeY']]);
   } catch (e) {
   }

   setWindowStorage('itemPrevNextTmp', null);
}

export function openInlineEdit(id_block) {
   var url = '/_blocek/edit-block/' + id_block + '/?inlineEditable=1';
   var win = window.open(url, '', 'width=' + window.screen.width + ',height=' + window.screen.height);

   try {
      win.focus();
   } catch (e) {
   }
}

export function getWindowStorage(key, targetWindow) {
   if (!targetWindow) {
      targetWindow = window;
   }

   try {
      return (JSON.parse(targetWindow.sessionStorage.getItem('kupshop.windowStore')))[key];
   } catch (e) {
      return undefined;
   }
}

export function setWindowStorage(key, value, targetWindow) {
   if (!targetWindow) {
      targetWindow = window;
   }

   var data = {};
   try {
      data = JSON.parse(targetWindow.sessionStorage.getItem('kupshop.windowStore'));
   } catch (e) {
   }

   if (data == null) {
      data = {};
   }

   try {
      data[key] = value;
      targetWindow.sessionStorage.setItem('kupshop.windowStore', JSON.stringify(data));
   } catch (e) {
   }
}

export function getPrevNext(items, next) {
   var selected = undefined;
   var ret = [undefined, undefined, undefined];
   $.each(items, function(index, value) {
      if (value['type'] == next['type'] && value['ID'] == next['ID']) {
         selected = index;
         return false;
      }
   });

   if (selected != undefined) {
      if (selected > 0) {
         ret[0] = items[selected - 1];
      }
      if (selected < items.length) {
         ret[1] = items[selected + 1];
      }
      ret[2] = items[selected];
   }

   return ret;
}

export function getPrevNextArray($items) {
   var pattern = new RegExp('^javascript:nw\\s*\\(\\W*(\\w+)\\W*,\\D*(\\d+)\\D*');

   var ret = [];

   $items.each(function() {
      var href = $(this).attr('href');
      var matches = pattern.exec(href);
      if (matches) {
         ret.push({ 'type': matches[1], 'ID': matches[2], 'item': this });
      }
   });

   return ret;
}

export function initPrevNext(targetWindow, params) {
   var items = getPrevNextArray($('tr').find('A[href^=javascript]:first'));
   var prevNext = getPrevNext(items, params);
   setWindowStorage('itemPrevNextTmp', prevNext, targetWindow);

   if (prevNext[2]) {
      // Highlight row
      $(prevNext[2].item).parents('tr').siblings().removeClass('highRow');
      $(prevNext[2].item).parents('tr').addClass('highRow');
   }
}

export function moveToNext(bReverse) {
   if (!window.opener) {
      return false;
   }

   var items = getPrevNextArray(window.opener.$('tr').find('A[href^=javascript]:first'));

   var prevNext = getWindowStorage('itemPrevNext')[bReverse ? 0 : 1];

   /* end od page */
   if (prevNext === null) {
      return false;
   }

   var prevNextNew = getPrevNext(items, prevNext);
   prevNext = prevNextNew[2];

   if (prevNext) {
      window.opener.$('tr').removeClass('highRow');

      var $item = $(prevNext['item']);
      var href = $item.attr('href');
      var evalText = href.replace('javascript:nw', 'getWindowUrl');
      var params = eval(evalText);

      // Highlight row
      $item.parents('tr').addClass('highRow');

      setWindowStorage('itemPrevNext', prevNextNew);

      window.location = params['winUrl'];
   }
}

export function openDialog(url, name) {
   var dlg = window.top.$('<iframe src=\'' + url + '\' style=\'width: 100%;\'></iframe>').dialog({
      dragStart: function() {
         window.top.$('iframe').each(
            function(index, element) {
               var d = $('<div class="iframeCover" style="z-index:99;position:absolute;width:100%;top:0px;left:0px;height:' + $(element).height() + 'px"></div>');
               $(element).after(d);
            }
         );
      },
      dragStop: function() {
         window.top.$('.iframeCover').remove();
      },
      resizeStart: function() {
         window.top.$('iframe').each(
            function(index, element) {
               var d = $('<div class="iframeCover" style="z-index:99;position:absolute;width:100%;top:0px;left:0px;height:' + $(element).height() + 'px"></div>');
               $(element).after(d);
            }
         );
      },
      resizeStop: function() {
         window.top.$('.iframeCover').remove();
      },
      close: function(event, ui) {
         $(this).dialog('destroy').remove();
      },
      title: name
   });

   // Store dialog handle
   dlg[0].contentWindow._dlg = dlg;
   dlg[0].contentWindow.close = function() {
      this._dlg.dialog('destroy').remove();
   };
   dlg[0].contentWindow.resize = null;
   dlg[0].contentWindow.opener = this;
}

//####################################//

window.searchWndCallbacks = [];

export function searchWnd(type, selector, inputValue, params) {
   var winParam = 'toolbar=no,menubar=no,location=no,directories=no,scrollbars=yes,resizable=no,status=no,width=1000,height=830';

   if (typeof (selector) == 'function') {
      var callback = selector;
      selector = '' + type + inputValue + params;
      window.searchWndCallbacks[selector] = callback;
      params = '' + params + '&function=1';
   }

   var winUrl = 'launch.php?s=search.php&type=' + type + '&selector=' + encodeURIComponent(selector) + '&inputValue=' + inputValue;
   if (params) {
      winUrl += '&' + params;
   }

   var winName = 'search' + type;

   if (winUrl != '') {
      var html = window.open(winUrl, winName, winParam);
      html.focus();
   }
}


//####################################//


export function help(type, section) {
   var winUrl = 'launch.php?s=help/index.php';
   var winName = 'help';
   var winParam = 'toolbar=no,menubar=no,location=no,directories=no,scrollbars=yes,resizable=yes,status=no';
   var top, left = 0;
   var sizeX = 1368;
   var sizeY = 600;

   if(type != null) {
      winUrl += '&type=' + type;
   }

   if (section != null) {
      winUrl += '&section=' + section;
   }

   top = 20;
   left = 0;
   winParam += ',top=' + top + ',left=' + left + ',width=' + sizeX + ',height=' + sizeY;

   var hlpWnd = window.open(winUrl, winName, winParam);

   try {
      hlpWnd.focus();
      centerWindow(hlpWnd, [sizeX, sizeY]);
   } catch (e) {
   }
}


//####################################//

export function sanitizeUrl(url) {
   if (!url) {
      return url;
   }

   var start = 'launch.php?';
   if (url.substr(0, start.length) == start) {
      url = url.substr(start.length);
   }

   return url.replace(/&/g, '|').replace(/=/g, ':');
}

var recursionAvoidance = 0;

export function nf(left, right, name, title) {
   if (top.window != window) {
      return top.window.nf(left, right, name, title);
   }

   if (recursionAvoidance > 0) {
      return false;
   }

   var framePointer;
   if (left === 'blank' || left === 'launch.php?blank') {
      window.top.showLeftPane(false);
   } else if (left) {
      framePointer = leftFrame;
      if (framePointer != null) {
         framePointer.location.replace(left);
      }
   } else {
      left = History.getState().data.left;
   }

   if (right) {
      framePointer = mainFrame;
      if (framePointer != null && right != 'launch.php?') {
         framePointer.location.replace(right);
      }
   } else {
      right = History.getState().data.right;
   }

   if (!name) {
      name = 'launch.php?s=main.php&l=' + sanitizeUrl(left) + '&r=' + sanitizeUrl(right);
   }

   var state = History.getState();

   if (title) {
      state.title = title;
   }

   if (state.data.left != left || state.data.right != right) {
      recursionAvoidance++;
      History.pushState({ left: left, right: right }, state.title, name);
      recursionAvoidance--;
   }
}

//####################################//

export function closeWindow() {
   if (window.opener != null && !window.opener.closed) {
      window.opener.focus();
   }

   window.close();
}


//####################################//


export function focusWindow() {
   if (window.opener != null) {
      window.opener.focus();
   }

   window.focus();
}


//####################################//


export function removeFromList(inptFrom) {
   if (inptFrom != null) {
      if (inptFrom.selectedIndex == -1) {
         return false;
      }

      inptFrom.options[inptFrom.selectedIndex] = null;
   }
}


//####################################//


export function addToList(inptTo, inptFrom, inptFromValue) {
   var h1 = '', h2 = '';

   if (inptFrom != null && inptTo != null) {
      if (typeof (inptTo) == 'undefined') {
         return false;
      }
      if (inptFromValue == null) {
         h1 = inptFrom.options[inptFrom.selectedIndex].value;
         h2 = inptFrom.options[inptFrom.selectedIndex].text;
      }
      if (h1 == '') {
         return false;
      }

      inptTo.options[inptTo.options.length] = new Option(h2, h1);

   }
}


//####################################//


export function refreshOpener(winOpener, url) {
   if (winOpener != null) {
      if (url == null) {
         url = winOpener.location;
      }

      if (typeof winOpener.customRefresh != 'undefined' && $.isFunction(winOpener.customRefresh)) {
         winOpener.customRefresh(url);
      }

      winOpener.history.pushState({}, '', url);
      winOpener.location.reload();

      return true;
   }

   return false;
}


//####################################//


export function display(id) {
   $('#' + id).slideToggle();
}


//####################################//

export function resizePopup(wnd, targetWidth, targetHeight) {
   var innerWidth = wnd.innerWidth || wnd.document.documentElement.clientWidth || wnd.document.body.clientWidth;
   var innerHeight = wnd.innerHeight || wnd.document.documentElement.clientHeight || wnd.document.body.clientHeight;
   window.resizeBy(targetWidth - innerWidth, targetHeight - innerHeight);

   centerWindow(wnd, [targetWidth, targetHeight]);
}

export function centerWindow(wnd, size) {
   var screenWidth = wnd.screen.width || wnd.screen.availWidth;
   var screenHeight = wnd.screen.height || wnd.screen.availHeight;

   var posX = Math.max(0, Math.ceil((screenWidth - size[0]) / 2));
   var posY = Math.max(0, Math.ceil((screenHeight - size[1]) / 2));

   wnd.moveTo(posX, posY);
}

//####################################//

export function checkInputData(type, event) {
   if (!event) {
      return;
   }

   if (type == 'int') {
      if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 13 && (event.keyCode < 96 || event.keyCode > 105)) {
         event.returnValue = false;
      }
   } else if (type == 'int-signed') {
      if ((event.keyCode < 48 || event.keyCode > 57) && event.keyCode != 13 && event.keyCode != 45 && (event.keyCode < 96 || event.keyCode > 105) && event.keyCode != 109 && event.keyCode != 8 && event.keyCode != 9) {
         event.returnValue = false;
      }
   } else if (type == 'float') {
      if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)
         && event.keyCode != 46 && event.keyCode != 44 && event.keyCode != 13) {
         event.returnValue = false;
      }
   } else if (type == 'float-signed') {
      if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)
         && event.keyCode != 46 && event.keyCode != 44 && event.keyCode != 13 && event.keyCode != 45 && event.keyCode != 109) {
         event.returnValue = false;
      }
   } else if (type == 'date') {
      if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)
         && event.keyCode != 45 && event.keyCode != 58 && event.keyCode != 32) {
         event.returnValue = false;
      }
   }
}

export function logout() {
   top.window.location = 'launch.php?s=logout.php';
}

export function newWindow() {
   window.open(document.location.href);
}

//####################################//
// POPIS: funkce najde hlavni okno Eshopu

export function findMainWindow() {
   var openerID = window.top.window.opener;

   if (openerID == null) {
      return openerID;
   } else if (openerID.top.window.name == 'EshopMainFrame') {
      return openerID.top.window;
   } else if (openerID == openerID.top.window.opener) {
      return openerID.top.window;
   } else {
      return openerID.top.window;
   }
}

//############### AUTOCOMPLETE #####################//
$.wpjAutoComplete = function(options) {
   var defaultOptions = {
      input: 'product_id',
      type: 'product_id',
      source: './launch.php?s=autocomplete.php&limit=50',
      input_name: null,
      params: ''
   };
   $.extend(true, this, defaultOptions, options);

   var $input = $(this.input);
   var $inputHidden = $input.clone();

   var textName = this.input_name;
   if (textName == null) {
      textName = $input.attr('name');
      if (textName.substr(-1, 1) == ']') {
         textName = textName.substr(0, textName.length - 1) + '_text' + ']';
      } else {
         textName = textName + '_text';
      }
   }
   $inputHidden.attr('name', textName);
   if (!$inputHidden.attr('placeholder')) {
      $inputHidden.attr('placeholder', 'Vyhledejte psaním ...');
   }
   $input.hide();
   $inputHidden.insertAfter($input);

   if ($input.data('text')) {
      $inputHidden.val($input.data('text'));
   }

   $inputHidden.autocomplete({
      minLength: 2,
      source: this.source + '&type=' + this.type + '&' + this.params,
      select: function(event, ui) {
         $input.val(ui.item.value);
         $inputHidden.val(ui.item.label);
         event.stopPropagation();
         return false;
      }
   });

   $inputHidden.data('uiAutocomplete')._renderItem = $.wpjAutoComplete.renderRow;

   this.inputHidden = $inputHidden;
};

$.wpjAutoComplete.renderRow = function(a, b) {
   var $row = $('<li></li>');

   if (b.exact_match == '1') {
      $row.attr('style', 'background-color:yellow');
   }

   if (b.from_supplier == '1') {
      $row.attr('style', 'background-color:#88FFFF');
   }

   if (b.visible == 'N') {
      $row.attr('style', 'background-color:#FF6666');
   }

   if (b.visible == 'O') {
      $row.attr('style', 'background-color:#FFAAD3');
   }

   return $row.data('item.autocomplete', b).append($('<a></a>').text(b.label)).appendTo(a);
};


$.wpjAutoCompleteVariation = function(options) {
   var me = this;

   var defaultOptions = { inputProduct: '', inputVariation: '', inputFields: '', callbacks: {}, productOptions: { params: '' } };
   $.extend(true, this, defaultOptions, options);
   me.productOptions.params = `${me.productOptions.params}&${$(me.inputProduct).data('autocomplete-params')}`

   this.productAutocomplete = new $.wpjAutoComplete($.extend({}, { 'input': me.inputProduct, 'type': 'product_id' }, me.productOptions));

   let $inputProduct = this.productAutocomplete.inputHidden;
   let id_product = null;

   $inputProduct.bind('autocompleteselect', function(event, ui) {
      var id_variation = 0;
      if (parseInt(ui.item.from_variation) != 0) {
         id_variation = ui.item.value_variation;
      }

      id_product = ui.item.value;

      me.setProduct(ui.item.value, id_variation);
   });

   $($(me.inputVariation)[0].form).submit(function() {
      if ($(me.inputVariation).val() != -1 || id_product == null) {
         return true;
      }

      window.alert('Vyber variantu!');
      return false;
   });

   $(me.inputVariation).change(function() {
      me.setVariation($(me.inputProduct).val(), $(me.inputVariation).val());
   });

   this.setVariation = function(id_product, id_variation) {
      $.getJSON('launch.php?s=ajax.php&type=product_info&id_product=' + id_product + '&id_variation=' + id_variation + me.productOptions.params, function(data) {
         if (data.length > 0 && id_variation != -1) {
            data = data[0];
         } else {
            data = [];
         }

         for (var input in me.inputFields) {
            $(me.inputFields[input]).val(data[input]);
            $(me.inputFields[input]).keyup();
         }
      });

      if (me.callbacks && me.callbacks['selectVariation']) {
         me.callbacks['selectVariation'].call(me, id_product, id_variation);
      }
   };

   this.setProduct = function(id_product, id_variation) {
      $.getJSON('launch.php?s=autocomplete.php&type=variation_id&limit=500&term=&id_product=' + id_product + me.productOptions.params, function(data) {
         var $inputVariation = $(me.inputVariation);
         $inputVariation.empty();

         if (data.length == 0) {
            data.unshift({ value: '', label: 'Bez variant' });
         } else {
            data.unshift({ value: '-1', label: '!Vyber variantu!' });
         }

         $.each(data, function(index, val) {
            $inputVariation.append('<option value="' + val.value + '">' + val.label + '</option>');
         });

         if (parseInt(id_variation) != 0) {
            $inputVariation.val(id_variation);
         } else {
            $inputVariation.val(data[0].value);
         }

         $inputVariation.change();

         if (me.callbacks && me.callbacks['selectProduct']) {
            me.callbacks['selectProduct'](id_product);
         }

         if ($inputVariation.is('.selecter')) {
            $inputVariation.trigger('chosen:updated');
         }
      });
   };
};

export function initAutocomplete(input, type) {
   return new $.wpjAutoComplete({ 'input': input, 'type': type });
}

export function initAutocompleteVariation(inputProduct, inputVariation, inputFields, callbacks) {
   return new $.wpjAutoCompleteVariation({
      'inputProduct': inputProduct,
      'inputVariation': inputVariation,
      'inputFields': inputFields,
      'callbacks': callbacks
   });
}
export function initAutocompleteBatches(inputProduct, inputVariation, inputBatch) {
   const $prodInput = $(inputProduct);
   const $varInput = $(inputVariation);
   const $batchInput = $(inputBatch);

   $varInput.on('change', function() {
      const id_product = $prodInput.val()
      const id_variation = $varInput.val()

      $.getJSON('launch.php?s=autocomplete.php&type=batches&limit=500&term=&id_product=' + id_product + '&id_variation=' + id_variation, function(data) {

         $batchInput.empty();
         data.unshift({ value: '', text: 'Bez šarže' });

         $.each(data, function(index, val) {
            $batchInput.append('<option value="' + val.value + '">' + val.text + '</option>');
         });

         $batchInput.change();
         if ($batchInput.is('.selecter')) {
            $batchInput.trigger('chosen:updated');
         }
      });
   });


}

export function calcPrices(options) {
   if (typeof (options) != 'object') {
      options = { selector: options };
   }

   options = $.extend({
      multiplier: null
   }, options);

   $(options.selector).on('keyup change', ':input[data-calculate]', function() {
      var $this = $(this),
          $panel = $this.closest('.panel, .well, [data-calculate=wrap]'),
          $pieces = $panel.find(':input[data-calculate=pieces]'),
          $piece_price = $panel.find(':input[data-calculate=piece_price]'),
          $piece_price_vat = $panel.find(':input[data-calculate=piece_price_vat]'),
          $piece_price_rate = $panel.find(':input[data-calculate=piece_price_rate]'),
          $vat = $panel.find(':input[data-calculate=vat]'),
          $total_price = $panel.find(':input[data-calculate=total_price]'),
          $total_price_vat = $panel.find(':input[data-calculate=total_price_vat]'),
          $total_price_rate = $panel.find(':input[data-calculate=total_price_rate]'),
          $last_discount = $panel.find(':input[data-calculate=last_discount]');

      var value = $this.val();
      var action = $this.data('calculate');
      var setValue = null;
      var multiplier = 1;

      if (options.multiplier) {
         multiplier = $(options.multiplier).val();
      }

      // prenastaveni poctu kusu
      if (action == 'pieces') {
         if (isNaN(value)) {
            value = 0;
         }

         // prenastaveni celkove ceny BEZ DPH
         let price = $piece_price.val();
         setValue = Number(value * price);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));

         // prenastaveni celkove ceny S DPH
         price = $piece_price_vat.val();
         setValue = Number(value * price);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_vat.val(roundPrice(setValue));

         // prenastaveni celkove ceny dle meny

         setValue = ($piece_price_rate.val() * $pieces.val());
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_rate.val(roundPrice(setValue));
      }
      // prenastaveni ceny BEZ DPH
      else if (action == 'piece_price') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         // prenastaveni celkove ceny BEZ DPH
         let pieces = $pieces.val();
         setValue = Number(value * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));

         let vat = $vat.val();
         // prenastaveni ceny / ks S DPH
         setValue = Number(value * (1 + (vat / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_vat.val(roundPrice(setValue));

         //prednastaveni ceny ks dle meny
         setValue = Number(value / multiplier);
         setValue = Math.round(setValue * 100) / 100;
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_rate.val(roundPrice(setValue));

         // prenastaveni celkove ceny S DPH
         setValue = Number(pieces * roundPrice(value * (1 + (vat / 100))));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_vat.val(roundPrice(setValue));
      }
      // prenastaveni ceny S DPH
      else if (action == 'piece_price_vat') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         let pieces = $pieces.val();

         // prenastaveni celkove ceny S DPH
         setValue = Number(value * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_vat.val(roundPrice(setValue));

         let vat = $vat.val();
         // prenastaveni ceny / ks BEZ DPH
         setValue = Number(value / (1 + (vat / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price.val(roundPrice(setValue));

         //prednastaveni ceny ks dle meny
         setValue = Number(value / multiplier / (1 + (vat / 100)));
         setValue = Math.round(setValue * 100) / 100;
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_rate.val(roundPrice(setValue));

         // prenastaveni celkove ceny BEZ DPH
         let price = $piece_price.val();
         setValue = Number(price * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));
      } else if (action == 'vat') {
         value = value.replace(',', '.');
         if (isNaN(value)) {
            value = 0;
         }


         // prenastaveni ceny / ks S DPH
         let price = $piece_price.val();
         setValue = Number(price * (1 + (value / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_vat.val(roundPrice(setValue));

         // prenastaveni celkove ceny S DPH
         let pieces = $pieces.val();
         price = $piece_price_vat.val();
         setValue = Number(price * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_vat.val(roundPrice(setValue));

      } else if (action == 'total_price') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         var pieces = $pieces.val();
         setValue = Number(value / pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price.val(roundPrice(setValue));

         var vat = $vat.val();
         var price = $piece_price.val();
         setValue = Number(price * (1 + (vat / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_vat.val(roundPrice(setValue));

         setValue = Number(pieces * roundPrice(price * (1 + (vat / 100))));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_vat.val(roundPrice(setValue));
      } else if (action == 'total_price_vat') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         let pieces = $pieces.val();
         setValue = Number(value / pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_vat.val(roundPrice(setValue));

         let vat = $vat.val();
         let price = $piece_price_vat.val();
         setValue = Number(price / (1 + (vat / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price.val(roundPrice(setValue));

         // prenastaveni celkove ceny BEZ DPH
         setValue = Number(value / (1 + (vat / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));
      } else
      //prednastaveni celkove ceny dle meny
      if (action == 'total_price_rate') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         let pieces = $pieces.val();
         //prednastaveni ceny ks dle meny
         setValue = Number(value / pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_rate.val(roundPrice(setValue));

         //prednastaveni ceny ks bez dph
         setValue = Number((value * multiplier) / pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price.val(roundPrice(setValue));

         // prenastaveni celkove ceny BEZ DPH
         setValue = Number(value * multiplier);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));
      } else
      //prednastaveni ceny dle meny
      if (action == 'piece_price_rate') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         let pieces = $pieces.val();
         // prenastaveni ceny / ks bez DPH
         let vat = $vat.val();
         setValue = Number(value * multiplier);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price.val(roundPrice(setValue));

         // prenastaveni ceny / ks S DPH
         setValue = Number(value * multiplier * (1 + (vat / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_vat.val(roundPrice(setValue));

         // prenastaveni celkove ceny dle meny
         setValue = Number(value * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_rate.val(roundPrice(setValue));

         // prenastaveni celkove ceny BEZ DPH
         let price = $piece_price.val();
         pieces = $pieces.val();
         setValue = Number(price * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));

      } else
      //prednastaveni ceny podle slevy
      if (action == 'discount') {
         value = parseFloat(value.replace(',', '.'));
         if (isNaN(value)) {
            value = 0;
         }

         var origin_price_perc = new BigNumber(100).minus($last_discount.val());
         var origin_price = new BigNumber($piece_price.val()).dividedBy(origin_price_perc);

         $last_discount.val(value);

         var new_price_perc = new BigNumber(100).minus(value);
         value = new BigNumber(origin_price).mul(new_price_perc);

         let pieces = $pieces.val();
         // prenastaveni ceny / ks bez DPH
         setValue = Number(value * multiplier);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price.val(roundPrice(setValue));

         // prenastaveni celkove ceny dle meny
         setValue = Number(value * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_rate.val(roundPrice(setValue));

         // prenastaveni celkove ceny BEZ DPH
         let price = $piece_price.val();
         setValue = Number(price * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price.val(roundPrice(setValue));

         // prenastaveni ceny / ks S DPH
         price = $piece_price.val();
         setValue = Number(price * (1 + ($vat.val() / 100)));
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $piece_price_vat.val(roundPrice(setValue));

         // prenastaveni celkove ceny S DPH
         price = $piece_price_vat.val();
         setValue = Number(price * pieces);
         if (isNaN(setValue)) {
            setValue = 0;
         }
         $total_price_vat.val(roundPrice(setValue));

      }
   });
}

export function roundPrice(value) {
   var bigNumber = new BigNumber(value);

   return bigNumber.round(4);
}

//############### CONFIRMATION #####################//
export function makeSure(obj, msg, callback) {
   if (msg == null) {
      msg = obj.title || obj.value || 'provést tuto akci';
      msg = msg[0].toLowerCase() + msg.substr(1);
      msg = 'Opravdu ' + msg + '?';
   }

   if (confirm(msg)) {
      if (callback != null) {
         callback();
      }

      return true;
   } else {
      return false;
   }
}

export function makeSure_(e) {
   return makeSure(e.currentTarget);
}

$(function() {
   $('.confirm').click(makeSure_);
});

export function submitAll(selector, action, idSelector) {
   var items = {};
   $(selector).each(function(index, item) {
      var subitems = {};
      $.each($(item).find('input').serializeArray(), function(i, field) {
         subitems[field.name] = field.value;
      });
      items[$(item).find(idSelector).val()] = subitems;
   });
   jQuery.post(document.location, {
      'acn': action,
      'items': items
   }, function() {
      document.location.reload();
   });
}

//############### COUNT CHARACTERS REMAINING #####################//
export function charCounter($input, $count) {
   let max_chars;

   if ($input.attr('maxlength')) {
      max_chars = parseInt($input.attr('maxlength'));
   } else if ($count.data('maxlength')) {
      max_chars = parseInt($count.data('maxlength'));
   } else {
      max_chars = 0;
   }

   $input.on('input', function() {
      let count = $input.val().length;

      if (max_chars === 0) {
         $count.text('Zadáno ' + (max_chars - count) + ' znaků.');
      } else {
         $count.text('Zbývá ' + (max_chars - count) + ' znaků.');
      }
   });

   $input.trigger('input');
}

export function initCharCounter() {
   $('.charCounter').each(function(index, el) {
      const $counter = $(el);
      const $input = $('[name=' + $counter.attr('rel').replace(/([\[\]])/g, '\\$1') + ']');

      charCounter($input, $counter);
   });
}

$(function() {
   initCharCounter();
});

//####### STYLED BOOTFLAT SELECT, CHECKBOX, UPLOADFILE ##########//
export function styleFormInputs(selector, skipUnstyled) {
   var $selector = $(selector);

   var $selecter = $selector.find('.selecter');
   if (skipUnstyled) {
      $selecter = $selecter.not('.unstyled .selecter');
   }
   if ($selecter.length) {

      $selecter.each(function(index, value) {
         let $value = $(value);
         $value.chosen({
            width: '100%',
            disable_search_threshold: 10,
            placeholder_text_single: $value.data('text-single') ? $value.data('text-single') : 'Vyberte možnost',
            placeholder_text_multiple: 'Vyberte několik možností',
            search_contains: true,
            hide_results_on_select: $value.data('hide-on-select') ?? true,
         });
      });

      $selecter.chosenSortable();
   }

   var $filestyle = $selector.find('.filestyle');
   if (skipUnstyled) {
      $filestyle = $filestyle.not('.unstyled .filestyle');
   }

   if ($filestyle.length) {
      $filestyle.each(function() {
         var $this = $(this), options = {
            'input': $this.attr('data-input') !== 'false',
            'icon': $this.attr('data-icon') !== 'false',
            'buttonBefore': $this.attr('data-buttonBefore') === 'true',
            'disabled': $this.attr('data-disabled') === 'true',
            'size': $this.attr('data-size'),
            'buttonText': $this.attr('data-buttonText'),
            'buttonName': $this.attr('data-buttonName'),
            'iconName': $this.attr('data-iconName'),
            'badge': $this.attr('data-badge') !== 'false'
         };

         $this.filestyle(options);
      });
   }
}

export function unstyleFormInputs(selector) {
   var $selector = $(selector);

   var $selecter = $selector.find('.selecter');
   if ($selecter.length) {
      $selecter.chosen('destroy');
   }

   var $filestyle = $selector.find('.filestyle').not('.unstyled .filestyle');
   if ($filestyle.length) {
      $filestyle.filestyle('destroy');
   }
}

$(function() {
   styleFormInputs(document, true);
});

//#################### BOOTSTRAP TREE #########################//
$(function() {
   $('.tree').on('click', 'i', function() {
      var $this = $(this), $li = $this.closest('li');
      $li.toggleClass('collapsed');
      if ($li.is('.collapsed')) {
         $this.removeClass('glyphicon-minus').addClass('glyphicon-plus');
      } else {
         $this.removeClass('glyphicon-plus').addClass('glyphicon-minus');
      }
      return false;
   });
});

//########################## TOOLTIPS ################################//
$(function() {
   $('.help-tip.help-tip-left').tooltip({
      placement: 'left',
      delay: { show: 200, hide: 100 },
      container: 'body',
      template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner tooltip-inner-help"></div></div>'
   });
});

$(function() {
   $('body').tooltip({
      selector: '[data-toggle="tooltip"]',
      placement: 'bottom',
      delay: { show: 200, hide: 100 },
      container: 'body',
      template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner tooltip-inner-help"></div></div>'
   });
});

$(function() {
   $('[data-hotkey]').tooltip({
      placement: 'bottom',
      delay: { show: 200, hide: 100 },
      container: 'body',
      template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner tooltip-inner-help-hotkey"></div></div>'
   });
});

//#################### CALENDAR #########################//
export function openCalenderIFrame(selector, dateFormat, timeFormat) {
   if (timeFormat) {
      $(selector).datetimepicker({
         dateFormat: dateFormat,
         timeFormat: timeFormat
      });
   } else {
      $(selector).datepicker({
         dateFormat: dateFormat
      });
   }
}

export function formatPrice(price, places = 4) {
   let c = Math.pow(10, places);

   return Math.round(price * c) / c;
}

//#################### List Tree #########################//
export function initListTree(name, url, selector) {
   var $tree = $(selector ? selector : '.treeDragDrop');

   $tree.treeDragDrop({
      updateUrl: url
   });

   function getClosedBranches(name) {
      try {
         return JSON.parse(localStorage.getItem('list-tree-' + name + '-closed')) || {};
      } catch (e) {
         return {};
      }
   }

   function setClosedBranches(name, value) {
      localStorage.setItem('list-tree-' + name + '-closed', JSON.stringify(value));
   }

   $tree.on('click', 'li .opener', function() {
      var $li = $(this).closest('li');
      var $this = $(this);
      var $ul = $li.find('ul').first();
      if ($ul.length > 0) {
         var id = $li.data('id');
         var closedBranches = getClosedBranches(name);
         if (!$this.is('.plus')) {
            closedBranches[id] = 1;
         } else {
            delete closedBranches[id];
         }
         setClosedBranches(name, closedBranches);

         $ul.toggleClass('collapsed');
         $this.toggleClass('plus');
      }
      return false;
   });

   var closedBranches = getClosedBranches(name);
   if (typeof closedBranches != 'object') {
      setClosedBranches(name, {});
   } else {
      for (var branch in closedBranches) {
         $tree.find('li[data-id=' + branch + '] .opener').click();
      }
   }
}

export function showProductCodes(IDp, IDv) {
   var url = 'launch.php?s=stockInOrder.php&IDp=' + IDp,
       options = { width: '400', height: '400', 'title': 'Dodavatelé produktu', 'autosize': true };
   if (IDv) {
      url += '&IDv=' + IDv;
   }

   openDialog_(url, options);
}

export function showWpjHintText(ID, file, title) {
   var url = 'https://napoveda.wpj.cz/kupshop-detail?' + file + '=' + ID,
       options = { width: '50%', height: '400', 'title': title, 'autosize': false };

   openDialog_(url, options);
}

export function openDialog_(url, options) {
   if (!url) {
      return;
   }

   options = $.extend({}, options);

   var $dialog = $('#admin_dialog'), $iframe;
   if (!$dialog.length) {
      $dialog = $('\
      <div class="modal" tabindex="-1" role="dialog" id="admin_dialog" aria-hidden="true">\
         <div class="modal-dialog boxFlex box">\
            <div class="modal-content boxFlex box">\
               <div class="modal-header">\
                  <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>\
                  <h4 class="modal-title"></h4>\
               </div>\
               <div class="modal-body boxFlex box">\
                  <iframe src=""></iframe>\
               </div>\
            </div>\
         </div>\
      </div>');

      $('body').append($dialog);

      $('html').on('click', '.modal-open', function() {
         $dialog.modal('hide');
      });

      $dialog.click(function() {
         return false;
      });

      $iframe = $dialog.find('iframe');
      $iframe.on( 'load', function() {
         var options = $dialog.data('options');

         if (options.autosize) {
            var doc = $iframe[0].contentDocument,
                height = $(doc.body).height() + 10;
            $iframe.height(height);

            $dialog.modal({
               backdrop: false
            });

            $dialog.find('.modal-dialog').css('visibility', 'visible');
         }
      });
   } else {
      $iframe = $dialog.find('iframe');
   }


   if (options.autosize) {
      $dialog.find('.modal-dialog').width(options.width);
   } else if (options.width) {
      $dialog.find('.modal-dialog').width(options.width).height(options.height);
   }

   $dialog.find('.modal-title').text(options.title || '');
   $dialog.data('options', options);

   $iframe.attr('src', url);

   if (options.autosize) {
      $dialog.find('.modal-dialog').css('visibility', 'hidden');
   }

   $dialog.modal({
      backdrop: true
   });
}

$.dataField = function(name, context) {
   var selector = '[name=\'data[' + name + ']\']';
   if (!context) {
      return $(selector);
   }

   return context.find(selector);
};

$.fn.dataField = function(name) {
   $.dataField(name, this);
};

export function switchTab(tabName) {
   if ($.isNumeric(tabName)) {
      return $('#windowTables a').eq(tabName).click();
   }

   return $(`[href="#${tabName}"]`).click();
}

export function replaceAttribute(selector, attribute, find, replace) {
   $(selector).filter('[' + attribute + ']').each(function() {
      var $this = $(this);
      var name = $this.attr(attribute);

      name = name.replace(find, replace);

      $this.attr(attribute, name);
   });
}

export function addNewItem($item, $after = null) {
   if (!$after) {
      $after = $item;
   }

   var index = $item.data('form-index');

   if (!index) {
      index = 1;
      unstyleFormInputs($item);
   } else {
      index++;
   }

   var $newItem = $item.clone();

   $newItem.removeAttr('data-form-new').attr('data-form-item', '');
   var find = '0';
   if ($newItem.find(':input').eq(0).attr('name') && $newItem.find(':input').eq(0).attr('name').indexOf('[@]') > -1) {
      find = '@';
   }
   replaceAttribute($newItem.find(':input'), 'name', '[' + find + ']', '[-' + index + ']');
   replaceAttribute($newItem.find(':input'), 'id', '[' + find + ']', '[-' + index + ']');
   replaceAttribute($newItem.find('label'), 'for', '[' + find + ']', '[-' + index + ']');
   replaceAttribute($newItem.find('.charCounter'), 'rel', '[' + find + ']', '[-' + index + ']');

   $after.after($newItem);

   $newItem.slideDown();
   styleFormInputs($newItem);

   $item.data('form-index', index);

   initCharCounter();

   if ($.isFunction($.fn.wpj_markChanged)) {
      $.fn.wpj_markChanged();
   }

   return $newItem;
}

export function deleteItem($item, remove = false) {
   $item.find('[data-form-delete] input').prop('checked', true).change();

   $item.slideUp(function() {
      if (remove) {
         $item.remove();
      }
   });

   if ($.isFunction($.fn.wpj_markChanged)) {
      $.fn.wpj_markChanged();
   }
}

export function initForm(options) {
   var default_options = {
      selector: '[data-form]',
      beforeAdd: null,
      afterAdd: null,
      beforeDelete: null,
      afterDelete: null,
      jsonFriendly: false
   };

   options = $.extend(default_options, options);

   var $form = $(options.selector);
   var $newItem = null;
   var $placeholder = null;

   if (options.jsonFriendly) {
      $placeholder = $('<div>').hide();
      $newItem = $form.find('[data-form-new]').eq(0);
      $newItem.after($placeholder);
      $newItem.detach();
   }

   function _addItem() {
      if (options.jsonFriendly) {
         return addNewItem($newItem, $placeholder);
      } else {
         return addNewItem($form.find('[data-form-new]').eq(0));
      }


   }

   function _deleteItem() {
      return deleteItem($(this).closest('[data-form-item]'), options.jsonFriendly);
   }

   $form.on('keydown', null, 'ctrl+enter', function(e) {
      var data = e.data;
      if (data.modif == 'ctrl+' && data.special == 'return') {
         $form.find('[data-form-add]').click();

         return false;
      }
   });

   $form.on('click', '[data-form-add]', function() {
      options.beforeAdd ? options.beforeAdd(_addItem) : _addItem();

      return false;
   });

   $form.on('click', '[data-form-delete]', function() {
      options.beforeDelete ? options.beforeDelete.call(this, _deleteItem.bind(this)) : _deleteItem.bind(this)();

      return false;
   });

   $form.on('click', '[data-form-mass-open]', function() {
      var $this = $(this),
          opened = $this.data('toggle');
      if (opened == undefined) {
         opened = true;
      }

      $form.find('[data-form-item] .collapse').collapse(opened ? 'show' : 'hide');

      $this.data('toggle', !opened);
      $this.find('.glyphicon').removeClass('glyphicon-plus-sign').removeClass('glyphicon-minus-sign').addClass(!opened ? 'glyphicon-plus-sign' : 'glyphicon-minus-sign');

      return false;
   });
}

// Redirect with POST
$.extend({
   unserialise: function(Data) {
      var DataParts = Data.split('&');
      var Serialised = {};
      $.each(DataParts, function(index, value) {
         var Properties = value.split('=');
         if (Properties.length == 2) {
            Serialised[Properties[0]] = decodeURIComponent(Properties[1].replace(/\+/g, ' '));
         }
      });
      return Serialised;
   },
   redirectPost: function(options) {
      options = $.extend({
         url: document.location.href,
         data: {},
         target: null
      }, options);

      var attrs = {};
      if (options.target) {
         attrs['target'] = options.target;
      }
      attrs['action'] = options.url;
      attrs['method'] = 'POST';

      var $form = $('<form></form>');
      $form.attr(attrs);

      if (typeof options.data === 'string') {
         options.data = $.unserialise(options.data);
      }

      if (options.data instanceof Array) {
         $.each(options.data, function(key, value) {
            $form.append($('<input type="hidden">').attr({ name: value.name, value: value.value }));
         });
      } else {
         $.each(options.data, function(key, value) {
            $form.append($('<input type="hidden">').attr({ name: decodeURIComponent(key), value: value }));
         });
      }

      $form.appendTo($(document.body)).submit();
   }
});

export function throwMessage(str, type) {
   var $row = $('.alert-inforow');
   var $newRow = $row.clone();
   $row.after($newRow);
   $newRow.removeClass('alert-inforow');
   $newRow.css('display', 'inline');
   $newRow.find('#data-alert-text').text(str);
   $newRow.find('#data-alert-type').addClass('alert-' + type).css('position', 'fixed');
   $newRow.find('#data-alert-icon').addClass('glyphicon-' + ((type == 'success') ? 'ok' : 'remove'));

   setTimeout(function() {
      $newRow.find('.alert.autoclose').alert('close');
      $newRow.remove();
   }, 2000);
}

window.somethingChanged = false;

export function checkUnsavedChanges(frame) {

   var changedMessagee = 'Máte neuložené změny, které budou odchodem ze stránky ztraceny.\nPokud chcete změny uložit, zústaňte na této stránce a stiskněte tlačitko uložit.';
   if (frame) {
      changedMessagee = 'Máte neuložené změny v některé záložce.\nPokud chcete změny uložit, stiskněte v dané záložce tlačitko uložit.';
   }

   $.fn.wpj_markChanged = function() {
      if (counter == 0) {
         window.somethingChanged = true;

      }

   };
   $.fn.wpj_markSaved = function() {
      window.somethingChanged = false;

   };

   $(function() {
      //$(':input').on('change', $.fn.wpj_markChanged);
      //$(':input').on('keydown', $.fn.wpj_markChanged);
      $('form').on('submit', $.fn.wpj_markSaved).on('change', ':input:not([data-no-change])', $.fn.wpj_markChanged);
      if (typeof CKEDITOR != 'undefined') {
         for (var i in CKEDITOR.instances) {
            CKEDITOR.instances[i].on('change', $.fn.wpj_markChanged);
         }
      }
   });

   window.onbeforeunload = function(e) {
      if (window.somethingChanged) {
         if (!e) {
            e = window.event;
         }

         e.cancelBubble = true;
         e.returnValue = changedMessagee;

         if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
         }

         if (/Firefox[/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
            alert(changedMessagee);
         }
         return changedMessagee;
      }
   };
}

var counter = 0;

export function UnsavedOff() {
   counter = counter + 1;
}

export function UnsavedOn() {
   counter = counter - 1;
}

export function focusInvalid(form) {
   let inputs = $(form).find(':input');
   let invalidInputs = [];

   for (let i = 0; i < inputs.length; i++) {
      if (inputs[i].checkValidity() === false) {
         let blueprint = $(inputs[i]).closest('[data-form-new]')
         if(blueprint.length === 0)
         {
            invalidInputs.push(inputs[i]);
         }
      }
   }
   for(let i = 0; i < invalidInputs.length; i++) {
      let tab = $(`a[href="#${$(invalidInputs[i]).parents('.tab-pane').attr('id')}"]`);
      let panel = $(invalidInputs[i]).parents('.panel').children('.panel-heading');
      let collapse = null;
      if (tab) {
         tab.click();
      }

      if (panel.length > 0) {
         if (panel[0].classList.contains('collapsed')) {
            collapse = panel[0].parentElement.children[1];
            collapse.classList.add('no-transition');
            panel[0].click();
         }
      }
      if (collapse) {
         collapse.classList.remove('no-transition');
      }
      if($(invalidInputs[i]).is(':visible'))
      {
         invalidInputs[i].scrollIntoView(true);
         invalidInputs[i].reportValidity();
         return true;
      }
   }
   return false;
}

export function checkFormSaved(button) {
   // Check HTML 5 forms are valid
   let $button = $(button);
   let form = $button.closest('form')[0];
   if (form) {
      if (form.checkValidity() === false) {
         if(focusInvalid(form))
         {
            form.reportValidity();
            return true;
         }
      }
   }

   // Submit all on-demand loaded frames
   var requests = [];
   var iframes = $('.on-demand');
   for (var i = 0; i < iframes.length; i++) {
      if (iframes[i].contentWindow.somethingChanged === true) {

         requests.push(iframes[i].contentWindow.saveFormAjax());
      }
   }

   $.when.apply($, requests).done(function() {
      var error = '';
      for (var i = 0; i < arguments.length; i++) {
         if (arguments[i] != false) {
            error += arguments[i] + ' ';
         }
      }

      if (error != '') {
         if (error.indexOf('html-error') === -1) {
            alert(error);
         }
         return true;
      }

      let form = $button.closest('form')[0];
      if (form) {
         $(form).submit(function(e) {
            if (!e.isPropagationStopped()) {
               $button.addClass('is-submitting');
            }
         })
      }

      $button.off('click');

      // Dement Chrome minimálně v131+ nespustil nativní event handler (po volání off), pokud se to takhle neohackovalo
      setTimeout(function() {
         $button.trigger('click');
      })
   });
}

export function saveFormAjax() {

   $('body').addClass('loading');
   var editformEl = $('[name=\'editform\']');

   return $.ajax({
      type: 'POST',
      url: editformEl.attr('action'),
      data: editformEl.serialize()
   }).then(function(data, status, xhr) {
      window.somethingChanged = false;

      var error = xhr.getResponseHeader('admin-error'),
          htmlError = xhr.getResponseHeader('admin-html-error');

      if (error !== null) {
         return decodeURIComponent(error.replace(/\+/g, '%20'));
      }

      if (htmlError !== null) {
         window.somethingChanged = true;

         $('body').removeClass('loading');
         $('#errorModal').find('.modal-body').html(decodeURIComponent(htmlError.replace(/\+/g, '%20')));
         $('#errorModal').modal('show');

         return 'html-error';
      }

      return false;
      //$('body').removeClass('loading');
   });
}

//#################### Sortable list #########################//
export function sortableList(name, saveCallback = savePositions) {
   $('.table-striped tbody').sortable({
      helper: function(e, row) {
         UnsavedOff();
         var $row = $(row);
         var $helper = $row.clone().addClass('drag-drop');
         return $helper[0];
      },
      stop: function(event, ui) {
         let minVal = Infinity;
         $(this).children().each(function(index, item) {
             const val = parseInt($(item).find('[data-sort]').val(), 10);
             if (!isNaN(val) && val < minVal) {
                 minVal = val;
             }
         });

         if(minVal === Infinity) {
            minVal = 0;
         }

         $(this).children().each(function(index, item) {
            $(item).find('[data-sort]').val(minVal).change();
            minVal++;
         });
         saveCallback(ui.item, ui.position, ui.originalPosition, name);
         UnsavedOn();
      },
      handle: '.handle',
   });
}

export function savePositions(item, position, original_position, name) {
   var direction = 'down';

   if (original_position.top - position.top > 0) {
      direction = 'up';
   }

   var data = {
      id: item.find('.sort').prop('name'),
      position: item.find('.sort').val(),
      direction: direction
   };
   $.ajax({
      type: 'POST',
      url: 'launch.php?s=list.php&acn=drag&type=' + name,
      dataType: 'json',
      data: { moved_item: data, url: window.location.href },
      success: function() {
         showInfoMessage('Uloženo', 'success');
      },
      error: function() {
         showInfoMessage('Chyba', 'danger');
      }
   });
}

var activeTimers = {};

export function resetTimer(id, timeout, callback) {
   var timer = activeTimers[id];
   if (timer) {
      clearTimeout(timer);
   }

   activeTimers[id] = setTimeout(function() {
      delete activeTimers[id];
      callback();
   }, timeout);
}

export function addTabClass(tab_id, alert_class) {
   var selector = 'a[data-tab=' + tab_id + ']';
   $(selector).parent().addClass(alert_class);
}

export function checkBankAccountNumber(input) {
   var $input = $(input);

   $(document).ready(function() {
      checkInput($input);
   });

   $input.on('keyup', function() {
      checkInput($input);
   });

   function checkInput($input) {
      if ($input.val() != '' && !checkBankAccountNumberFormat($input.val())) {
         $input.attr('data-bac-has-error', true);
         $input.css('border-color', 'red');
         $('[data-bacc-error]').show();
      } else {
         $input.removeAttr('data-bac-has-error');
         $input.removeAttr('style');
         $('[data-bacc-error]').hide();
      }
   }

   function checkBankAccountNumberFormat(account) {
      var matches = /^(([0-9]{0,6})-)?([0-9]{1,10})\/([0-9]{4,6})$/.exec(account);

      if (!matches) {
         return false;
      }

      if (matches[2]) {
         return checkDigit11(matches[2]) && checkDigit11(matches[3]);
      } else {
         return checkDigit11(matches[3]);
      }
   }

   function checkDigit11(n) {

      var l = n.length - 1, v = 0;
      var weights = [1, 2, 4, 8, 5, 10, 9, 7, 3, 6];

      for (var i = 0; i <= l; i++) {
         //console.log(i, n[l-i], weights[i], );
         v += parseInt(n[l - i], 10) * weights[i];
      }

      return v % 11 == 0;
   }
}

window.preloadAutocompletes = function($context) {
   if (!$context) {
      $context = $(document);
   }

   $context.find('select.selecter[data-autocomplete]').each(function(index, el) {
      var $el = $(el);
      $el.ajaxChosen({
         minTermLength: 0,
         dataType: 'json',
         type: 'GET',
         url: 'launch.php?s=autocomplete.php&type=' + $el.data('autocomplete') + '&' + ($el.data('autocomplete-params') || '')
      }, function(data) {
         if ($el.data('autocomplete-empty')) {
            data.unshift({
               value: '',
               text: $el.data('autocomplete-empty') != "1" ? $el.data('autocomplete-empty') : "Nevyplněno"
            });
         }
         return data;
      }, {
         width: '100%',
         allow_single_deselect: true,
         placeholder_text_single: 'Vyberte možnost',
         placeholder_text_multiple: 'Vyberte několik možností'
      });
      $el.chosenSortable();
   });

   // preload names for selected values
   var preloadSelectNames = {};
   $context.find('select.selecter[data-preload],input[data-preload]').each(function(index, el) {
      var $el = $(el);
      var selected = $el.val();
      if (selected !== null && selected.length) {
         if (!Array.isArray(selected)) {
            selected = [selected];
         }
         // support for multiple selectors with same type
         if (preloadSelectNames.hasOwnProperty($el.data('preload'))) {
            selected = selected.concat(preloadSelectNames[$el.data('preload')]);
         }
         preloadSelectNames[$el.data('preload')] = selected;
      }
   });

   if (Object.keys(preloadSelectNames).length) {
      $.ajax({
         type: 'POST',
         url: 'autocomplete-preload',
         data: { 'types': preloadSelectNames },
         success: function(data) {
            $.each(data, function(type, items) {
               var $selecter = $('select.selecter[data-preload=' + type + ']');
               $.each(items, function(index, item) {
                  $selecter.find('option[value=' + item.id + ']').text(item.name);
               });
               $selecter.trigger('chosen:updated');
               $.each(items, function(index, item) {
                  $('input[data-preload][value=' + item.id + ']').val(item.name);
               });
            });
         },
         dataType: 'json'
      });
   }
};

$(function() {
   function goToPage(goToPageForm) {
      var pageInput = goToPageForm.find('input[name="goToPagePage"]');
      var url = pageInput.data('url');
      var page = pageInput.val();
      if (url && page && pageInput[0].checkValidity()) {
         url = url + '&page=' + page;
         window.somethingChanged = false;
         document.location = url;
      } else {
         pageInput.val('');
      }
   }

   $('.go-to-page input[name="goToPagePage"]').keydown(function(e) {
      if (e.keyCode == 13) {
         e.preventDefault();
         goToPage($(e.target).closest('.go-to-page'));
      }
   });

   $('.go-to-page input[name="goToPageButton"]').click(function(e) {
      e.preventDefault();
      goToPage($(e.target).closest('.go-to-page'));
   });
});

export function activateWysiwyg(field, type, config = {}, index='') {
   window[`editor${index}`] = CKEDITOR.replace(field,
      {
         customConfig: '/admin/static/js/ckeditor.js?v1',
         toolbar : type,
         filebrowserBrowseUrl: '/_ckfinder/browse/',
         filebrowserImageBrowseUrl: '/_ckfinder/browse/?rsrcType=Obrázky',
         filebrowserUploadUrl: '/ckfinder/connector?command=QuickUpload&type=Soubory',
         filebrowserImageUploadUrl: '/ckfinder/connector?command=QuickUpload&type=Obrázky',
         ...config
   })
}

$(function() {
   $('body').on('change', '[data-input-overwrite] [name^="empty"]', function() {
      $(this).closest('[data-input-overwrite]').toggleClass('disabled', $(this).prop('checked'));
   }).on('input', '[data-input-overwrite] [name^="data"]', function() {
      $(this).closest('[data-input-overwrite]').toggleClass('active', $(this).val() !== '');
   });

   $('[data-input-overwrite]').each(function(index, el) {
      if (!$(el).find('[name^="empty"]').length) {
         return;
      }

      const isEmpty = $(el).find('[name^="empty"]:checked').length;
      const isActive = $(el).find('[name^="data"]').filter(function() {
         return $(this).val() !== '';
      }).length;

      $(el).toggleClass('disabled', !!isEmpty);
      $(el).toggleClass('active', !!isActive);
   });
});


function formatCodes(text) {
   const regex = /( )*[,;\r\n\t]+( )*/g;

   if (text.search(regex) >= 0) {
      text = text.replaceAll(regex, ',');
   }

   if (text.search(',') === -1 && text.search(' ') >= 0) {
      text = text.replaceAll(' ', ',');
   }

   return text;
}

function formatCodesOnPaste(input) {
   const target = document.querySelector(input);

   if (!target) {
      return;
   }

   target.addEventListener('paste', (event) => {
      event.preventDefault();

      let pastedText = (event.clipboardData || window.clipboardData).getData('text');

      target.value += formatCodes(pastedText);
   });
}

export function initCodesModal(input, textarea, modal) {
   formatCodesOnPaste(textarea);

   const $modal = $(modal);
   const $input = $(input);
   const $textarea = $(textarea);

   $modal.on('show.bs.modal', function() {
      $textarea.val(formatCodes($input.val()));
   }).on('click', '[data-save]', function() {
      $input.val(formatCodes($textarea.val()));
      $modal.modal('hide');
   });
}
