﻿var webShopPagingProducts = function (intValue) {
    var pageIndex = 1;
    var pageSize = 10;
    var orderBy = 2;
    var totalItems = 0;
    var showedItems = 0;
    var onAddingProducts = null;
    var getMoreService = null;
    var criteria = null;
    var skipPages = 0;

    this.getMore = function () {
        getMoreService(getData(), pageIndex, pageSize, orderBy, onSuccess, null);
    }

    var getData = function () {
        var obj = new Object();

        criteria.each(function (i, item) {
            obj[item.name] = $(item).val();
        });

        return obj;
    }

    var getRemainingItems = function () {
        return Math.max(Math.min(totalItems - showedItems, pageSize), 0);
    }

    var parseTemplate = function (productData) {
        WebShopTemplate.BuildHTML('/ClientTemplates/CategoriesProductList.aspx', { products: productData }, addProducts, null);
        productData = null;
    }

    var onSuccess = function (result) {
        products = result.Products;
        if (products.length < 0) {
            return;
        }
        parseTemplate(products);
        totalItems = result.TotalItems;
        showedItems += products.length;
        pageIndex++;
    }

    var addProducts = function (html) {
        var skipThisPage = false;

        if (skipPages > 0) {
            skipThisPage = true;
        }

        if (onAddingProducts) {
            onAddingProducts(getRemainingItems(), html, skipThisPage);
        }

        skipPages = skipPages - 1;
    }

    var init = function (intValue) {
        // init value
        pageSize = intValue.pageSize;
        orderBy = intValue.orderBy;
        onAddingProducts = intValue.onAddingProducts;
        getMoreService = intValue.getMoreService;
        criteria = intValue.criteria;
        if (intValue.skipPages) {
            skipPages = intValue.skipPages;
        }
    } (intValue);
};
