/* ------------------
	JS - localStorage
--------------------*/
if (!localStorage.user) {
  window.location.href = 'login.html';
}
$(document).ready(function() {
  userDisplay();
  basketDisplay();
  categoriesDisplay();
  productsDisplayList();
  $('#category_filter').on('change', function() {
    filterSelection();	
    pagination();
  });
  $("#search_filter").keyup(delay(function (e) {
    filterSelection();
    pagination();
  }, 500));
  $("#price_filter").on("change", function() {
    filterSelection();
    pagination();
  });
  $("#itemspp_filter").on("change", function() {
    filterSelection();
    pagination();
  });
});

function delay(callback, ms) {
	var timer = 0;
	return function() {
		var context = this, args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function () {
			callback.apply(context, args);
		}, ms || 0);
  };
}

function pagination() {
	var category_filter = $("#category_filter").val().toLowerCase();
  var search_filter = $("#search_filter").val().toLowerCase();
  var price_filter = $("#price_filter").val();
  var numberOfItems = $(".product-item:visible").length;
  var limitPerPage = $("#itemspp_filter").val();
  var totalPages = Math.ceil(Number(numberOfItems / limitPerPage));
  var items = "";
  console.log(numberOfItems);
  $('.product-item:visible:gt(' + (limitPerPage - 1) + ')').hide();
  if (numberOfItems != 0) {
    items += '<div class="pager-item active"><p>1</p></div>';
  }
  for (var i = 2; i <= totalPages; i++) {
    items += '<div class="pager-item"><p>' + i + '</p></div>';
  }
  $('.pager').html(items);
  if(category_filter == ""){
  $(".pager-item").on("click", function() {
    if ($(this).hasClass('active')) {
      return false;
    } else {
      var currentPage = $(this).index() + 1;
      $(".pager-item").removeClass('active');
      $(this).addClass('active');
      $(".product-item").hide();
      var grandTotal = limitPerPage * currentPage;
      for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {
        $(".product-item:eq(" + i + ")").show();
      }
    }
  });
  }
  else {
	   $(".pager-item").on("click", function() {
    if ($(this).hasClass('active')) {
      return false;
    } else {
      var currentPage = $(this).index() + 1;
      $(".pager-item").removeClass('active');
      $(this).addClass('active');
      $(".product-item").hide();
      var grandTotal = limitPerPage * currentPage; 		
		for (var i = grandTotal - limitPerPage; i < grandTotal; i++) {	
         $(".product-item[data-name="+ category_filter +"]:eq("+ i +")").show();
      }
    }
  });
	  
  }
}

function filterSelection() {
	var category_filter = $("#category_filter").val().toLowerCase();
	var search_filter = $("#search_filter").val().toLowerCase();
	var price_filter = $("#price_filter").val();
  $(".jq-products-content .product-item").filter(function() {
		$(this).toggle($(this).attr('class').toLowerCase().indexOf(category_filter) > -1 && ($(this).find('.product-info p').text().toLowerCase().indexOf(search_filter) > -1 || $(this).find('.user-rating span').text().toLowerCase().indexOf(search_filter) > -1))
	});
	var alphabeticallyOrderedDivs = $(".product-item").sort(function(a, b) {
		if (price_filter == 0) {
    	return ($(a).find('p.text-header').text().toUpperCase().localeCompare($(b).find('p.text-header').text().toUpperCase()));
    } else if(price_filter == 1) {
    	return (parseFloat($(b).find('.price').text().substr(4)) - parseFloat($(a).find('.price').text().substr(4)));
    } else if(price_filter == 2) {
    	return (parseFloat($(b).find('.price').text().substr(4)) - parseFloat($(a).find('.price').text().substr(4)));
		} else {
			return (parseFloat($(b).attr('id').split('-').pop() - $(a).attr('id').split('-').pop()));
		}
	});
	$(".jq-products-content").html(alphabeticallyOrderedDivs);
	if (category_filter != "") {
		var styleOrderedDivs = $(".product-item").sort(function(a, b) {
			if ($(a).attr('class').indexOf(category_filter) != -1) {
				return -1
			} else if ($(b).attr('class').indexOf(category_filter) != -1) {
				return 1
			}
		});
		$(".jq-products-content").html(styleOrderedDivs);
		var alphabeticallyOrderedDivs1 = $(".product-item").sort(function(a, b) {
			if (price_filter == 0) {
				return ($(a).find('p.text-header').text().toUpperCase().localeCompare($(b).find('p.text-header').text().toUpperCase()));
			} else if(price_filter == 1) {
				return (parseFloat($(b).find('.price').text().substr(4)) - parseFloat($(a).find('.price').text().substr(4)));
			} else if(price_filter == 2) {
				return (parseFloat($(b).find('.price').text().substr(4)) - parseFloat($(a).find('.price').text().substr(4)));
			} else {
				return (parseFloat($(a).attr('id').split('-').pop() - $(b).attr('id').split('-').pop()));
			}
		});
		$(".jq-products-content").html(alphabeticallyOrderedDivs1);
	}
/*	if (search_filter != "") {
		var styleOrderedDivs = $(".product-item").sort(function(a, b) {
			if ($(a).find('.product-info p').text().toLowerCase().indexOf(search_filter) != -1 || $(a).find('.user-rating span').text().toLowerCase().indexOf(search_filter) != -1) {
				return -1
			} else if ($(b).find('.product-info p').text().toLowerCase().indexOf(search_filter) != -1 || $(b).find('.user-rating span').text().toLowerCase().indexOf(search_filter) != -1) {
				return 1
			}
		});
		$(".jq-products-content").html(styleOrderedDivs);
	}
	*/
}

function categoriesDisplay() {
  var items = '';
  $.ajax({
    url: '../../../pmarket/api/index.php/categories',
    type: 'GET',
    dataType: "json",
    success: function(response) {
      var categories = response;
      $(categories).each(function(index) {
        items += '<option value="' + this.category + '">' + this.category + ' (' + this.count + ')</option>';
      });
      $('#category_filter').append(items);
    }
  })
}

function productsDisplayGrid() {
  $('.jq-products-content').removeClass('list');
  $('.jq-products-content').addClass('grid');
  $('.view-selector').removeClass('active');
  $('.view-selector.grid').addClass('active');
  $('.jq-products-content').empty();
  $('.pager').empty();
  var user = JSON.parse(localStorage.getItem('user'));
  var items = "";
  var tags = "";
  $.ajax({
    url: '../../../pmarket/api/products/' + user.id,
    type: 'GET',
    dataType: "json",
    success: function(response) {
      var products = response;
      $(products).each(function(index) {
        tags = "&nbsp;";
        $(this.tags).each(function(index) {
          if (index == 0) {
            tags += '<span>' + this + '</span>';
          } else {
            tags += ', <span>' + this + '</span>';
          }
        });
        if (this.isActive != 0) {
          items += '<div class="product-item column ' + this.category + '" data-name="'+ this.category +'">' + '<div class="product-preview-actions">' + '<figure class="product-preview-image">' + '<img src="images/items/image' + this.productId + '_m.jpg" alt="product-image" onerror="this.src=\'images/items/Default_m.jpg\'">' + '</figure>' + '<div class="preview-actions">' + '<div class="preview-action">' + '<a href="javascript:basketAddItem(' + this.productId + ')">' + '<div class="circle tiny primary">' + '<span class="icon-tag"></span>' + '</div>' + '<p>Ajouter au panier</p>' + '</a><input type="number" min="1" data-index="' + this.productId + '" value="1">' + '</div>' + '</div>' + '</div>' + '<div class="product-info">' + '<a href="item-v1.html">' + '<p class="text-header gridDisplay">' + this.designation + '</p>' + '</a>' + '<p class="product-description gridDisplay">' + this.description + '</p>' + '<a href="javascript:void(0)">' + '<p class="category">' + this.category + '</p>' + '</a>' + '<p class="price"><span>CHF </span>' + parseFloat(this.price).toFixed(2) + '</p>' + '</div>' + '<hr class="line-separator">' + '<div class="user-rating">' + '<p class="text-header-tiny">' + tags + '</p>' + '</div>' + '</div>';
        }
      });
      $('.jq-products-content').html(items);
      pagination();
    }
  })
}

function productsDisplayList() {
  $('.jq-products-content').removeClass('grid');
  $('.jq-products-content').addClass('list');
  $('.view-selector').removeClass('active');
  $('.view-selector.list').addClass('active');
  $('.jq-products-content').empty();
  $('.pager').empty();
  var user = JSON.parse(localStorage.getItem('user'));
  var items = "";
  var tags = "";
  $.ajax({
    url: '../../../pmarket/api/products/' + user.id,
    type: 'GET',
    dataType: "json",
    success: function(response) {
      var products = response;
      $(products).each(function(index) {
        tags = "&nbsp;";
        $(this.tags).each(function(index) {
          if (index == 0) {
            tags += '<span>' + this + '</span>';
          } else {
            tags += ', <span>' + this + '</span>';
          }
        });
        if (this.isActive != 0) {
          items += '<div id="product-' + this.productId + '" class="product-item ' + this.category + '" data-name="'+ this.category +'">' + '<a href="javascript:void(0);">' + '<figure class="product-preview-image small">' + '<img src="images/items/image' + this.productId + '_s.jpg" onerror="this.src=\'images/items/Default_s.jpg\'" alt="product-image">' + '</figure>' + '</a>' + '<div class="product-info">' + '<a href="javascript:void(0);">' + '<p class="text-header listDisplay">' + this.designation + '</p>' + '</a>' + '<p class="product-description listDisplay">' + this.description + '</p>' + '<a href="javascript:void(0);">' + '<p class="category primary">' + this.category + '</p>' + '</a>' + '<p class="text-header-tiny">' + tags + '</p>' + '</div>' + '<div class="author-data-reputation">' + '<input type="number" min="1" data-index="' + this.productId + '" value="1">' + '</div>' + '<div class="item-actions">' + '<a href="javascript:basketAddItem(' + this.productId + ')" class="tooltip" title="Ajouter au panier">' + '<div class="circle tiny primary">' + '<span class="icon-tag"></span>' + '</div>' + '</a>' + '</div>' + '<div class="price-info">' + '<p class="price medium"><span>CHF </span>' + parseFloat(this.price).toFixed(2) + '</p>' + '</div>' + '</div>';
        }
      });
      $('.jq-products-content').html(items);
      pagination();
    }
  })
}

function basketDisplay() {
  if (localStorage.basket) {
    var basket = JSON.parse(localStorage.getItem('basket'));
  } else {
    var basket = [];
  }
  var total = 0;
  var items = "";
  $('.jq-basket-count').html(basket.length);
  $(basket).each(function(index) {
    items += '<li class="dropdown-item">' + '<a class="link-to"></a>' + '<figure class="product-preview-image tiny">' + '<img src="images/items/image' + this.productId + '_s.jpg" alt="" onerror="this.src=\'images/items/Default_s.jpg\'">' + '</figure>' + '<p class="text-header tiny">' + this.designation + '</p>' + '<p class="category tiny primary">x ' + this.quantity + '</p>' + '<p class="price tiny">' + parseFloat(this.price * this.quantity).toFixed(2) + '<span> CHF</span></p>' + '</li>';
    total += this.price * this.quantity;
  });
  items += '<li class="dropdown-item">' + '<p class="text-header tiny">Total</p>' + '<p class="price">' + parseFloat(total).toFixed(2) + '<span> CHF</span></p>' + '<a href="cart.html" class="button primary">Aller au panier</a>' + '</li>';
  $('.jq-basket-content').html(items);
}

function basketAddItem(prductId) {
  var user = JSON.parse(localStorage.getItem('user'));
  var quantity = $('input[data-index='+prductId+']').val();
  $.ajax({
    url: '../../../pmarket/api/basket/' + prductId + '/' + user.id,
    type: 'POST',
    dataType: "json",
	contentType: "application/json; charset=utf-8",
    data: JSON.stringify({
        "quantity": quantity
    }),
    success: function(response) {
      if (localStorage.basket) {
        var basketStorage = JSON.parse(localStorage.getItem('basket'));
        var basketFilter = basketStorage.filter(function(n) {
          return n.productId == response.productId;
        });
      } else {
        var basketStorage = [];
        var basketFilter = [];
      }
      if (basketFilter.length == 0) {
        basketStorage.push(response);
      } else {
        var index = basketStorage.indexOf(basketFilter[0]);
        basketStorage[index].quantity = parseInt(basketStorage[index].quantity) + parseInt(quantity);
      }
      localStorage.setItem('basket', JSON.stringify(basketStorage));
      basketDisplay();
	  $('input[data-index='+prductId+']').val(1);
        $('body').xmalert({ 
            x: 'right',
            y: 'bottom',
            xOffset: 30,
            yOffset: 30,
            alertSpacing: 20,
            lifetime: 4000,
            fadeDelay: 0.3,
            template: 'messageSuccess',
            title: 'Success',
            paragraph: 'Le produit a bien été ajouté au panier.',
        });
    }
  })
}

function userDisplay() {
  var user = JSON.parse(localStorage.getItem('user'));
  $('.jq-username').html(user.username);
  $('.jq-company-name').html(user.companyName);
}

function logout() {
  localStorage.clear();
  window.location.href = 'login.html';
}
