﻿/// <reference path="../Edentity.Global.js" />
/// <reference path="../External/jquery-1.3.2-vsdoc2.js" />

Edentity.RegisterNamespace("Whiskas.Modules");

(function(Modules, $) {

Modules.CommunityListing = function(mediaType, scrollableSelector, itemIDPrefix, jTemplateID, pageSize) {
    this.mediaType = mediaType;
    this.scrollable = $(scrollableSelector);
    this.itemIDPrefix = itemIDPrefix;
    this.jTemplateID = jTemplateID;
    this.pageSize = pageSize;
    this.loadedPages = [];
};

Modules.CommunityListing.prototype.Init = function() {
    var self = this;
    
    // configure the "scrollable" plugin
    this.scrollable.scrollable({
        item: ".Item",
        items: ".Items",
        size: this.pageSize,
        api: true,
        clickable: false,
        keyboard: false,
        onSeek: function (e, index) {
            var loadThis = !(_isPageLoaded.call(self, index));
            var loadNext = !(_isPageLoaded.call(self, index + self.pageSize));
            var pageNum = Math.ceil(index / self.pageSize);
            if (loadThis && loadNext) {
                _loadItems.call(self, pageNum, 2);
            } else if (loadThis) {
                _loadItems.call(self, pageNum, 1);
            } else if (loadNext) {
                _loadItems.call(self, pageNum + 1, 1);
            }
        }
    });
    
    // load first page
    _loadItems.call(self, 0, 2);
};

Modules.CommunityListing.prototype.ShowPage = function(pageNum) {
    this.scrollable.data("scrollable").seekTo(pageNum * this.pageSize, 400);
};

function _loadItems(index, loadFactor) {
    var self = this;
    $.ajax({
        type: "POST",
        url: AjaxServicesAsmxURL + '/GetCommunityContentList',
        data: "{ 'mediaType': '" + this.mediaType + "', 'pageIdx': " + index + ", 'pageSize': " + this.pageSize + ", 'loadFactor': " + loadFactor + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.d != null) {
                for (i = 0; i < result.d.length; i++) {
                    $('#' + self.itemIDPrefix + result.d[i].ID).setTemplateElement(self.jTemplateID);
                    $('#' + self.itemIDPrefix + result.d[i].ID).processTemplate(result.d[i]);
                }
            }
        },
        error: function(error) {
        
        }
    });
}

function _isPageLoaded(itemIndex) {
    return this.scrollable.find(".Item:eq(" + itemIndex + ") .LoadingIcon").length == 0;
}

})(Whiskas.Modules, jQuery);