/*
 * @author Tomas Opekar <tomas.opekar@bohemiasoft.com>
 *
 */

var BS = BS || {};

BS.Basket = {
  /**
   *Ukazatel na tento objekt
   */
  $this: null,

  /**
  * Pritomnost qtip, zobrazujici obsah kosiku
  */
  $qtip_basket_info: true,

  /**
 * Sablona, ktera nema defaultni styl kosiku (horniho)
 */
  $default_top_basket: true,

  /*
   *Typ vkladani do kosiku
   */
  $variant: 5,

  /**
   *Default hláška, která se alertne, pokud není zboží skladem
   */
  $not_in_stock: "We are sorry, but there was some error.",

/**
   *Default hláška, která se alertne, pokud není objednáno minimální množství
   */
  $not_bought_minimum: "minimum",

/**
 *Možnost používat varianty i v detailu produktu
 */
  $detail_buy: false,

  $basket_show_items: "false",

  /**
   *Znefukcneni funkcionalit
   */
  $halt : false,

  $wait_text: "Čekejte",
  /**
 * Vrati variantu kosiku
 */
  variant: function()
  {
    return this.$variant;
  },

  refresh_small_basket: function()
  {
    var ebar_class = "";
    if(BS.Design.template.is_selected("platinum"))
    {
      this.$basket_show_items = true;
      ebar_class = ",#ebar"
    }

   $.get("/wa_script/basket_ajax.php?basket_variant_34_show_items=true&show_easy_content=1&id=" + uzivatel_id, function(data2) {
      jQuery("#ebar_right_content .img_cart, #basket_icon, #basket_icon a, #basket_icon2" + ebar_class).qtip('option', 'content.text', data2);
      BS.Design.recolor(jQuery('<input class="buy_btn">').hide().appendTo("body"), jQuery(".recolor"));
    });
    return true;
  },

  /**
 * Nacte data o cene / kusech
 */
  refresh_top_basket_data: function()
  {
    jQuery.ajax({
      url: "/wa_script/basket_ajax.php?method=refresh_info&id=" + uzivatel_id,
      type: "POST",
      dataType: "json",
      data: {
        method: "refresh_info",
        id: uzivatel_id
      }
    }).done(function(data){
      BS.Basket.refresh_top_basket_info(data.kusy, data.cena);
    }).fail(function(){
      console.log("Cannot update basket info.");
    });
  },

  refresh_top_basket_info: function (kusy, cena)
  {
    if($("body").hasClass("slider_available"))
    {
      //může přijít také deset. číslo
      var count = BS.Number.parse(kusy.split(' ')[0]);
      if(BS.Number.isNumber(count))
      {
        $('#quantity_tag .quantity_count').text(count);
        if(!$('#basket_icon').hasClass('basket-full') && count > 0)
        {
          $('#basket_icon').addClass('basket-full');
        }
        var infobox = $("#quantity_tag").next();
        if(infobox.length)
        {
          if(count > 0)
          {
            infobox
              .removeClass("basket_empty");
            infobox.html("");
          }
          else
          {
            infobox
              .addClass("basket_empty");
            infobox.html(this.basket_is_empty);
          }
        }
      }
    }
    else
    {
      if(this.$default_top_basket == false)
      {
        jQuery("#basket_tag_right").html(kusy);
      }
      if(jQuery("#basket_content_tag").length > 0)
      {
        jQuery("#basket_tag_right").html(kusy);
        jQuery("#quantity_tag").html(kusy + " / " + cena);
      }
      jQuery(".img_cart").find("a").html(kusy + " / " + cena);
    }

    return true;
  },

  delete_from_basket: function(id) {
    var that = this;
    if(this.$qtip_basket_info == true)
    {
      jQuery(".ajax-basket-easy").find(".top").html('<div class="empty_basket"><h2 style=""><span class="icon-spinner icon-2x icon-spin"></span> &nbsp;  &nbsp; '+BS.Basket.$wait_text+'</h2></div>');
    }
    $.get("/wa_script/basket_ajax.php?method=remove&id_record=" + id + "&id=" + uzivatel_id, function(data2) {
      BS.Conversion.getEvent('', '', '', 'remove_from_cart');
      that.fetchContents(that.updateBodyClass);
    });
    setTimeout("BS.Basket.refresh_small_basket()", 1000);
    return true;
  },
  register_close_event: function(){
    jQuery(".close-box").click(function(el){
      if($overlay != undefined){
        $overlay.fade_out();
      }
      jQuery("#ajax-basket").fadeOut(200);
      jQuery("#ajax-basket").remove();
      el.preventDefault();
      return false;
    });
  },

  close_qtip: function(){
    jQuery("#ebar_right_content .img_cart, #basket_icon, #basket_icon a, #ebar").qtip("hide");
  },

  explode: function(delimiter, string, limit) {

    if ( arguments.length < 2 || typeof delimiter == 'undefined' || typeof string == 'undefined' ) return null;
    if ( delimiter === '' || delimiter === false || delimiter === null) return false;
    if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object'){
      return {
        0: ''
      };
    }
    if ( delimiter === true ) delimiter = '1';

    // Here we go...
    delimiter += '';
    string += '';

    var s = string.split( delimiter );


    if ( typeof limit === 'undefined' ) return s;

    // Support for limit
    if ( limit === 0 ) limit = 1;

    // Positive limit
    if ( limit > 0 ){
      if ( limit >= s.length ) return s;
      return s.slice( 0, limit - 1 ).concat( [ s.slice( limit - 1 ).join( delimiter ) ] );
    }

    // Negative limit
    if ( -limit >= s.length ) return [];

    s.splice( s.length + limit );
    return s;
  },

  fetchContents: function(callback) {
    var r = $.ajax({
      url: "/wa_script/basket_ajax.php?",
      method: "GET",
      data: {
        show_easy_content: 1,
        cart: 1,
        id: BS.User.id
      }
    });
    r.done(function(response) {
      callback(JSON.parse(response));
    });
  },

  updateBodyClass: function(basketInfo) {
    var isEmpty = !!parseInt(basketInfo.empty);
    if(isEmpty) {
      document.body.classList.add("basket-empty");
    } else {
      document.body.classList.remove("basket-empty");
    }
  },

  calcMultiplesInc: function(el, count)
  {
    const submit_input = el.querySelectorAll('input[type=submit], button[type=submit], input[type=image]')[0];
    if(submit_input !== undefined && submit_input.dataset.hasOwnProperty('productInfo'))
    {
      const objProductData = JSON.parse(submit_input.dataset.productInfo);
      if( typeof objProductData.count_type !== undefined
          && typeof objProductData.multiples !== undefined
          && objProductData.count_type == 1) {
          return objProductData.multiples;
      }
    }
    return count;
  },
  notifyMultiplesInc: function(data)
  {
    if(data !== undefined && data.hasOwnProperty('count_type') && data.count_type == 1) {
      BS.ui.popMessage.warning(WA.Translation._multiples_inc_notify.replace('#inc#',data.multiples_inc + ".\n").replace(/(<([^>]+)>)/ig, ''));
    }

  }
}
