/*
	Author: Solomon Manalili
	Filename: layoutview.js
	Description: Use for toggling the product views to either list or tile view.
	Dependencies:
		- jQuery
	How to use:
		- Create a element with a class of ".js-layoutview" with a content of buttons that has class "js-layoutview-button" plus ".js-layoutView-grid" for grid view and ".jslayoutView-list" for list view.
		- The default target is "#catalog-list" and will remove/add a class "card-product--listview" depending on what button you clicked. You can customize the target by adding data-target="[id name]" to the parent element.
	Example :
		<div class="js-layoutview">
			<div class="js-layoutview-button js-layoutview-grid">
				Grid View Toggler
			</div>

			<div class="js-layoutview-button js-layoutview-list">
				List View Toggler
			</div>
		</div>

		the default target
		<div id="catalog-list" class="card-product">
		</div>
*/

;(function($) {
  'use strict'

  B2C.layoutView = {
    init: function(option) {
      this._default = {
        target: '#catalog-list',
        buttonsContainer: '.js-layoutview',
        button: '.js-layoutview-button',
        gridLayout: '.js-layoutview-grid',
        listLayout: '.js-layoutview-list',
        classToUpdate: 'card-product--listview'
      }

      B2C.layoutView._option = $.extend(this._default, option)

      if (!$(B2C.layoutView._option.buttonsContainer).length) return

      this.eventListener()
    },

    eventListener: function() {
      let self = B2C.layoutView

      //   Click event for both buttons
      $(this._option.listLayout)
        .add(this._option.gridLayout)
        .on('click', self.changeView)
    },

    changeView: function() {
      let self = B2C.layoutView._option,
        targetVal = $(this)
          .parent(self.buttonsContainer)
          .data('target'),
        targetContainer = targetVal ? targetVal : self.target

      // toggle class for the current view
      $(self.button).removeClass('active')
      $(this).addClass('active')

      // Condition to know if it's a grid view or list view then add/remove class
      if ($(self.gridLayout).hasClass('active')) {
        $(targetContainer).removeClass(self.classToUpdate)
      } else {
        $(targetContainer).addClass(self.classToUpdate)
      }
    }
  }
  B2C.layoutView.init()
})(jQuery)
