'use strict';

var woosc pSearchTimer = 0;

jQuery(document).ready(function($) {
  woosc pLoadColor();
  woosc pChangeCount('first');
  woosc pCheckButtons();

  if (woosc pVars.open_bar == 'yes') {
    woosc pLoadCompareBar('first');
  }

  // settings
  $('body').on('click touch', '.woosc p-bar-settings', function() {
    $('.woosc p-settings').toggleClass('open');
  });

  // search
  $('body').on('click touch', '.woosc p-bar-search', function() {
    $('.woosc p-search').toggleClass('open');
  });

  $('body').on('keyup', '#woosc p_search_input', function() {
    if ($('#woosc p_search_input').val() != '') {
      if (woosc pSearchTimer != null) {
        clearTimeout(woosc pSearchTimer);
      }
      woosc pSearchTimer = setTimeout(woosc pAjaxSearch, 300);
      return false;
    }
  });

  $('body').on('click touch', '.woosc p-item-add', function() {
    var product_id = $(this).attr('data-id');
    $('.woosc p-search').toggleClass('open');
    woosc pAddProduct(product_id);
    woosc pLoadCompareBar();
    woosc pLoadCompareTable();
    woosc pOpenCompareTable();
  });

  $('body').on('click touch', '.woosc p-popup-close', function() {
    var _this_popup = $(this).closest('.woosc p-popup');
    _this_popup.toggleClass('open');
  });

  // compare variation
  $(document).on('found_variation', function(e, t) {
    var variable_id = $(e['target']).attr('data-product_id');
    $('.woosc p-btn-' + variable_id).attr('data-id', t.variation_id);
  });

  $(document).on('reset_data', function(e) {
    var variable_id = $(e['target']).attr('data-product_id');
    $('.woosc p-btn-' + variable_id).attr('data-id', variable_id);
  });

  // remove all
  $('body').on('click touch', '.woosc p-bar-remove', function() {
    var r = confirm(woosc pVars.remove_all);
    if (r == true) {
      woosc pRemoveProduct('all');
      woosc pLoadCompareBar();
      woosc pLoadCompareTable();
    }
  });

  // rearrange
  $(document).on('woosc pDragEndEvent', function() {
    woosc pSaveProducts();
  });

  // add
  $('body').on('click touch', '.woosc p-btn', function(e) {
    var product_id = $(this).attr('data-id');
    if ($(this).hasClass('woosc p-btn-added')) {
      if (woosc pVars.click_again == 'yes') {
        // remove
        woosc pRemoveProduct(product_id);
        woosc pLoadCompareBar();
        woosc pLoadCompareTable();
      } else {
        if ($('.woosc p-bar-items').hasClass('woosc p-bar-items-loaded')) {
          woosc pOpenCompareBar();
        } else {
          woosc pLoadCompareBar();
        }
        if (!$('.woosc p-table-items').hasClass('woosc p-table-items-loaded')) {
          woosc pLoadCompareTable();
        }
      }
    } else {
      $(this).addClass('woosc p-btn-adding');
      woosc pAddProduct(product_id);
      woosc pLoadCompareBar();
      woosc pLoadCompareTable();
    }
    if (woosc pVars.open_table == 'yes') {
      woosc pToggleCompareTable();
    }
    e.preventDefault();
  });

  // remove
  $('body').
      on('click touch', '#woosc p-area .woosc p-bar-item-remove', function(e) {
        var product_id = $(this).attr('data-id');
        $(this).parent().addClass('removing');
        woosc pRemoveProduct(product_id);
        woosc pLoadCompareBar();
        woosc pLoadCompareTable();
        woosc pCheckButtons();
        e.preventDefault();
      });

  // compare bar button
  $('body').on('click touch', '.woosc p-bar-btn', function() {
    woosc pToggleCompareTable();
  });

  // close compare
  $('body').on('click touch', function(e) {
    if ((
        woosc pVars.click_outside == 'yes'
    ) && (
        $(e.target).closest('.wpc_compare_count').length == 0
    ) && (
        $(e.target).closest('.woosc p-popup').length == 0
    ) && (
        $(e.target).closest('.woosc p-btn').length == 0
    ) && (
        $(e.target).closest('.woosc p-table').length == 0
    ) && (
        $(e.target).closest('.woosc p-bar').length == 0
    ) && (
        $(e.target).closest('.woosc p-menu-item a').length == 0
    ) && (
        (
            woosc pVars.open_button == ''
        ) || (
            $(e.target).closest(woosc pVars.open_button).length == 0
        )
    )) {
      woosc pCloseCompare();
    }
  });

  // close
  $('body').on('click touch', '#woosc p-table-close', function() {
    woosc pCloseCompareTable();
  });

  // open button
  if (woosc pVars.open_button != '') {
    $('body').on('click touch', woosc pVars.open_button, function() {
      if ((woosc pVars.open_button_action == 'open_page') &&
          (woosc pVars.page_url != '')) {
        // open compare page
        window.location.href = woosc pVars.page_url;
      } else {
        // open compare popup
        woosc pToggleCompare();
      }
    });
  }

  // change settings
  $(document).on('change', '.woosc p-settings-field', function() {
    woosc pSaveSettings();
  });

  $('.woosc p-settings-field-li').arrangeable({
    dragSelector: '.label',
    dragEndEvent: 'woosc pDragSettings',
  });

  $(document).on('woosc pDragSettings', function() {
    woosc pSaveSettings();
  });

  // menu item
  $('body').on('click touch', '.woosc p-menu-item a', function(e) {
    if ((woosc pVars.menu_action == 'open_page') &&
        (woosc pVars.page_url != '')) {
      // open compare page
      window.location.href = woosc pVars.page_url;
    } else {
      // open compare popup
      if ($('.woosc p-bar-items').hasClass('woosc p-bar-items-loaded')) {
        woosc pOpenCompareBar();
      } else {
        woosc pLoadCompareBar();
      }
      if (!$('.woosc p-table-items').hasClass('woosc p-table-items-loaded')) {
        woosc pLoadCompareTable();
      }
      woosc pOpenCompareTable();
    }
    e.preventDefault();
  });
});

function woosc pAjaxSearch() {
  jQuery('.woosc p-search-result').html('').addClass('woosc p-loading');
  // ajax search product
  woosc pSearchTimer = null;
  var data = {
    action: 'woosc p_search',
    keyword: jQuery('#woosc p_search_input').val(),
    nonce: woosc pVars.nonce,
  };
  jQuery.post(woosc pVars.ajaxurl, data, function(response) {
    jQuery('.woosc p-search-result').
        html(response).
        removeClass('woosc p-loading');
  });
}

function woosc pSetCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + (
      exdays * 24 * 60 * 60 * 1000
  ));
  var expires = 'expires=' + d.toUTCString();
  document.cookie = cname + '=' + cvalue + '; ' + expires + '; path=/';
}

function woosc pGetCookie(cname) {
  var name = cname + '=';
  var ca = document.cookie.split(';');
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return decodeURIComponent(c.substring(name.length, c.length));
    }
  }
  return '';
}

function woosc pGetProducts() {
  var woosc pCookieProducts = 'woosc p_products';
  if (woosc pVars.user_id != '') {
    woosc pCookieProducts = 'woosc p_products_' + woosc pVars.user_id;
  }
  if (woosc pGetCookie(woosc pCookieProducts) != '') {
    return woosc pGetCookie(woosc pCookieProducts);
  } else {
    return '';
  }
}

function woosc pSaveProducts() {
  var woosc pCookieProducts = 'woosc p_products';
  if (woosc pVars.user_id != '') {
    woosc pCookieProducts = 'woosc p_products_' + woosc pVars.user_id;
  }
  var woosc pProducts = new Array();
  jQuery('.woosc p-bar-item').each(function() {
    var eID = jQuery(this).attr('data-id');
    if (eID != '') {
      woosc pProducts.push(eID);
    }
  });
  var woosc pProductsStr = woosc pProducts.join();
  woosc pSetCookie(woosc pCookieProducts, woosc pProductsStr, 7);
  woosc pLoadCompareTable();
}

function woosc pSaveSettings() {
  var woosc pFields = Array();
  var woosc pCookieFields = 'woosc p_fields';
  if (woosc pVars.user_id != '') {
    woosc pCookieFields = 'woosc p_fields_' + woosc pVars.user_id;
  }

  jQuery('.woosc p-settings-field').each(function() {
    var _val = jQuery(this).val();
    if (jQuery(this).prop('checked')) {
      woosc pFields.push(_val);
      jQuery('.woosc p_table .tr-' + _val).removeClass('tr-hide');
    } else {
      jQuery('.woosc p_table .tr-' + _val).addClass('tr-hide');
    }
  });

  woosc pSetCookie(woosc pCookieFields, woosc pFields.join(','), 7);
  woosc pLoadCompareTable();
}

function woosc pAddProduct(product_id) {
  var woosc pLimit = false;
  var woosc pLimitNotice = woosc pVars.limit_notice;
  var woosc pCookieProducts = 'woosc p_products';
  var woosc pCount = 0;
  if (woosc pVars.user_id != '') {
    woosc pCookieProducts = 'woosc p_products_' + woosc pVars.user_id;
  }
  if (woosc pGetCookie(woosc pCookieProducts) != '') {
    var woosc pProducts = woosc pGetCookie(woosc pCookieProducts).split(',');

    if (woosc pProducts.length < woosc pVars.limit) {
      woosc pProducts = jQuery.grep(woosc pProducts, function(value) {
        return value != product_id;
      });
      woosc pProducts.unshift(product_id);
      var woosc pProductsStr = woosc pProducts.join();
      woosc pSetCookie(woosc pCookieProducts, woosc pProductsStr, 7);
    } else {
      woosc pLimit = true;
      woosc pLimitNotice = woosc pLimitNotice.replace('{limit}',
          woosc pVars.limit);
    }

    woosc pCount = woosc pProducts.length;
  } else {
    woosc pSetCookie(woosc pCookieProducts, product_id, 7);
    woosc pCount = 1;
  }

  woosc pChangeCount(woosc pCount);
  jQuery(document.body).trigger('woosc p_added', [woosc pCount]);

  if (woosc pLimit) {
    jQuery('.woosc p-btn-' + product_id).removeClass('woosc p-btn-adding');
    alert(woosc pLimitNotice);
  } else {
    jQuery('.woosc p-btn-' + product_id).
        removeClass('woosc p-btn-adding').
        addClass('woosc p-btn-added').
        html(woosc pVars.button_text_added);
    jQuery(document.body).
        trigger('woosc p_change_button_text',
            [product_id, woosc pVars.button_text_added]);
  }
}

function woosc pRemoveProduct(product_id) {
  var woosc pCookieProducts = 'woosc p_products';
  var woosc pCount = 0;

  if (woosc pVars.user_id != '') {
    woosc pCookieProducts = 'woosc p_products_' + woosc pVars.user_id;
  }

  if (product_id != 'all') {
    // remove one
    if (woosc pGetCookie(woosc pCookieProducts) != '') {
      var woosc pProducts = woosc pGetCookie(woosc pCookieProducts).split(',');
      woosc pProducts = jQuery.grep(woosc pProducts, function(value) {
        return value != product_id;
      });
      var woosc pProductsStr = woosc pProducts.join();
      woosc pSetCookie(woosc pCookieProducts, woosc pProductsStr, 7);
      woosc pCount = woosc pProducts.length;
    }
    jQuery('.woosc p-btn-' + product_id).removeClass('woosc p-btn-added').
        html(woosc pVars.button_text);
    jQuery(document.body).
        trigger('woosc p_change_button_text',
            [product_id, woosc pVars.button_text]);
  } else {
    // remove all
    if (woosc pGetCookie(woosc pCookieProducts) != '') {
      woosc pSetCookie(woosc pCookieProducts, '', 7);
      woosc pCount = 0;
    }
    jQuery('.woosc p-btn').
        removeClass('woosc p-btn-added').
        html(woosc pVars.button_text);
    jQuery(document.body).
        trigger('woosc p_change_button_text',
            ['all', woosc pVars.button_text]);
  }
  woosc pChangeCount(woosc pCount);
  jQuery(document.body).trigger('woosc p_removed', [woosc pCount]);
}

function woosc pCheckButtons() {
  var woosc pCookieProducts = 'woosc p_products';

  if (woosc pVars.user_id != '') {
    woosc pCookieProducts = 'woosc p_products_' + woosc pVars.user_id;
  }

  if (woosc pGetCookie(woosc pCookieProducts) != '') {
    var woosc pProducts = woosc pGetCookie(woosc pCookieProducts).split(',');
    jQuery('.woosc p-btn').removeClass('woosc p-btn-added').
        html(woosc pVars.button_text);
    jQuery(document.body).
        trigger('woosc p_change_button_text',
            ['all', woosc pVars.button_text]);
    woosc pProducts.forEach(function(entry) {
      jQuery('.woosc p-btn-' + entry).addClass('woosc p-btn-added').
          html(woosc pVars.button_text_added);
      jQuery(document.body).
          trigger('woosc p_change_button_text',
              [entry, woosc pVars.button_text_added]);
    });
  }
}

function woosc pLoadCompareBar(open) {
  var data = {
    action: 'woosc p_load_compare_bar',
    products: woosc pGetProducts(),
    nonce: woosc pVars.nonce,
  };
  jQuery.post(woosc pVars.ajaxurl, data, function(response) {
    if ((
        woosc pVars.hide_empty == 'yes'
    ) && (
        (
            response == ''
        ) || (
            response == 0
        )
    )) {
      jQuery('.woosc p-bar-items').removeClass('woosc p-bar-items-loaded');
      woosc pCloseCompareBar();
      woosc pCloseCompareTable();
    } else {
      if ((
          typeof open == 'undefined'
      ) || (
          (
              open == 'first'
          ) && (
              woosc pVars.open_bar == 'yes'
          )
      )) {
        jQuery('.woosc p-bar-items').
            html(response).
            addClass('woosc p-bar-items-loaded');
        woosc pOpenCompareBar();
      }
    }
  });
}

function woosc pOpenCompareBar() {
  jQuery('.woosc p-bar').addClass('woosc p-bar-open');
  jQuery('.woosc p-bar-item').arrangeable({
    dragSelector: 'img',
    dragEndEvent: 'woosc pDragEndEvent',
  });
  jQuery(document.body).trigger('woosc p_bar_open');
}

function woosc pCloseCompareBar() {
  jQuery('.woosc p-bar').removeClass('woosc p-bar-open');
  jQuery(document.body).trigger('woosc p_bar_close');
}

function woosc pLoadCompareTable() {
  jQuery('.woosc p-table-inner').addClass('woosc p-loading');
  var data = {
    action: 'woosc p_load_compare_table',
    products: woosc pGetProducts(),
    nonce: woosc pVars.nonce,
  };
  jQuery.post(woosc pVars.ajaxurl, data, function(response) {
    jQuery('.woosc p-table-items').
        html(response).
        addClass('woosc p-table-items-loaded');
    if (jQuery(window).width() >= 768) {
      if ((woosc pVars.freeze_column == 'yes') &&
          (woosc pVars.freeze_row == 'yes')) {
        // freeze row and column
        jQuery('#woosc p_table').tableHeadFixer({'head': true, left: 1});
      } else if (woosc pVars.freeze_column == 'yes') {
        // freeze column
        jQuery('#woosc p_table').tableHeadFixer({'head': false, left: 1});
      } else if (woosc pVars.freeze_row == 'yes') {
        // freeze row
        jQuery('#woosc p_table').tableHeadFixer({'head': true});
      }
    } else {
      if (woosc pVars.freeze_row == 'yes') {
        // freeze row
        jQuery('#woosc p_table').tableHeadFixer({'head': true});
      }
    }
    jQuery('.woosc p-table-items').perfectScrollbar({theme: 'wpc'});
    jQuery('.woosc p-table-inner').removeClass('woosc p-loading');
    woosc pHideEmptyRow();
  });
}

function woosc pOpenCompareTable() {
  jQuery('.woosc p-table').addClass('woosc p-table-open');
  jQuery('.woosc p-bar-btn').addClass('woosc p-bar-btn-open');
  if (!jQuery.trim(jQuery('.woosc p-table-items').html()).length) {
    woosc pLoadCompareTable();
  }
  jQuery(document.body).trigger('woosc p_table_open');
}

function woosc pCloseCompareTable() {
  jQuery('#woosc p-area').removeClass('woosc p-area-open');
  jQuery('.woosc p-table').removeClass('woosc p-table-open');
  jQuery('.woosc p-bar-btn').removeClass('woosc p-bar-btn-open');
  jQuery(document.body).trigger('woosc p_table_close');
}

function woosc pToggleCompareTable() {
  if (jQuery('.woosc p-table').hasClass('woosc p-table-open')) {
    woosc pCloseCompareTable();
  } else {
    woosc pOpenCompareTable();
  }
}

function woosc pOpenCompare() {
  jQuery('#woosc p-area').addClass('woosc p-area-open');
  woosc pLoadCompareBar();
  woosc pLoadCompareTable();
  woosc pOpenCompareBar();
  woosc pOpenCompareTable();
  jQuery(document.body).trigger('woosc p_open');
}

function woosc pCloseCompare() {
  jQuery('#woosc p-area').removeClass('woosc p-area-open');
  woosc pCloseCompareBar();
  woosc pCloseCompareTable();
  jQuery(document.body).trigger('woosc p_close');
}

function woosc pToggleCompare() {
  if (jQuery('#woosc p-area').hasClass('woosc p-area-open')) {
    woosc pCloseCompare();
  } else {
    woosc pOpenCompare();
  }
  jQuery(document.body).trigger('woosc p_toggle');
}

function woosc pLoadColor() {
  var bg_color = jQuery('#woosc p-area').attr('data-bg-color');
  var btn_color = jQuery('#woosc p-area').attr('data-btn-color');
  jQuery('.woosc p-table').css('background-color', bg_color);
  jQuery('.woosc p-bar').css('background-color', bg_color);
  jQuery('.woosc p-bar-btn').css('background-color', btn_color);
}

function woosc pChangeCount(count) {
  if (count == 'first') {
    var products = woosc pGetProducts();
    if (products != '') {
      var products_arr = products.split(',');
      count = products_arr.length;
    } else {
      count = 0;
    }
  }
  jQuery('.woosc p-menu-item').each(function() {
    if (jQuery(this).hasClass('menu-item-type-woosc p')) {
      jQuery(this).find('.woosc p-menu-item-inner').attr('data-count', count);
    } else {
      jQuery(this).
          addClass('menu-item-type-woosc p').
          find('a').
          wrapInner(
              '<span class="woosc p-menu-item-inner" data-count="' + count +
              '"></span>');
    }
  });
  jQuery('.woosc p-bar').attr('data-count', count);
  jQuery(document.body).trigger('woosc p_change_count', [count]);
}

function woosc pHideEmptyRow() {
  jQuery('#woosc p_table > tbody > tr').each(function() {
    var _td = 0;
    var _td_empty = 0;
    jQuery(this).children('td').each(function() {
      if ((
          _td > 0
      ) && (
          jQuery(this).html().length > 0
      )) {
        _td_empty = 1;
      }
      _td++;
    });
    if (_td_empty == 0) {
      jQuery(this).hide();
    }
  });
}