function scPaging(variable, storeId) {
    $.sc.registerModule("scPaging", 3);
    this.defaultPagingOptions = {
        enabled: true,
        addToCartButton: "",
        arrowPrev: "",
        arrowNext: "",
        arrowPrevOff: "",
        arrowNextOff: "",
        arrowFirst: "",
        arrowLast: "",
        arrowFirstOff: "",
        arrowLastOff: "",
        gridColumns: 3,
        navigationVisible: true,
        bottomNavigationVisible: true,
        defaultItemsPerPage: "12",
        pagesNavigationVisible: true,
        navigateToPageControlVisible: true,
        navigateToPageControlReadOnly: true,
        navigateToPagePrefix: "page&nbsp;",
        navigateToPagePagesVisible: true,
        itemsPerPageVisible: true,
        itemsPerPagePrefix: "Items Per Page:",
        itemsPerPage: "15,90,180,300",
        itemsPerPageLinkSeparator: "&nbsp;&nbsp;|&nbsp;&nbsp;",
        itemsPerPageLayout: "links",
        pagesLinksVisible: true,
        pagesLinksPrefix: "Pages",
        pagesLinksSeparator: "|",
        pagesLinksEllipsisAfter: 8,
        pagesLinksMax: "9",
        pagesLinksMaxPostfix: "",
        pagesLinksMaxPrefix: "",
        pagesLinksMode: "pages",
        pagesLinksShowAll: false,
        pagesLinksShowAllText: "Show All",
        totalItemsVisible: true,
        totalItemsPrefix: "showing products ",
        dataLayoutVisible: true,
        dataLayoutDefault: "grid",
        dataLayoutDelimiter: "|",
        filterVisible: true,
        filterPrefix: "Quick Search",
        filterFields: {},
        filterLayout: "horizontal",
        filterLabelAlign: "right",
        filterResetAllVisible: false,
        sortVisible: true,
        sortFields: [
            ["bi", "ASC", "Best Seller"],
            ["name", "ASC", "Name"],
            ["fp", "DESC", "Price High To Low"],
            ["fp", "ASC", "Price Low To High"]
        ],
        sortLayout: "select",
        sortPrefix: "Sort By:",
        sortFieldDefault: "initial",
        sortSeparator: "|",
        controlWidth: "",
        gridColumnWidth: "242px",
        gridSpacerWidth: "1",
        gridHorizontalSpacerVisible: true,
        gridVerticalSpacerVisible: true,
        listHorizontalSpacerVisible: true,
        gridItemImageTemplate: "",
        gridItemInfoTemplate: "${gridImage}${name}${regularPrice}${salePrice}",
        gridItemInfoTemplate2: "",
        listItemTemplate:'${gridImage}<div class="scpinfo">${name}${regularPrice}${salePrice}</div><div class="scpatc">${abstract}</div>',
        //listItemTemplate: '${listImage}<div class="scpinfo">${name}${code}${abstract}${keyIcons}${productReviews}</div><div class="scpatc">${regularPrice}${salePrice}${saveNow}${orderForm}</div>',
        topNavigationTemplate: '<table width=100% cellpadding=0 cellspacing=0>' +
'<tr>' +
'	<td><div id="scpTopSort" class="scpSort"></div></td>' +
'	<td><div id="scpTopItemsPerPage" class="scpItemsPerPage"></div></td>' +
'	<td align=right><div id="scpTopNumbers" class="scpNumbers"></div></td>' +
'</tr></table>' +
'<table width=100% cellpadding=0 cellspacing=0><tr>' +
'	<td width=400><div id="scpTopPages" class="scpPages"></div></td>' +
'	<td><div id="scpTopDataMode" class="scpDataMode"></div></td>' +
'	<td align=right><div id="scpTopArrows" class="scpArrows"></div></td>' +
'</tr>' +
'</table>',
        bottomNavigationTemplate: '<table width=100% cellpadding=0 cellspacing=0>' +
'<tr>' +
'	<td><div id="scpBottomSort" class="scpSort"></div></td>' +
'	<td><div id="scpBottomItemsPerPage" class="scpItemsPerPage"></div></td>' +
'	<td align=right><div id="scpBottomNumbers" class="scpNumbers"></div></td>' +
'</tr></table>' +
'<table width=100% cellpadding=0 cellspacing=0><tr>' +
'	<td width=400><div id="scpBottomPages" class="scpPages"></div></td>' +
'	<td><div id="scpBottomDataMode" class="scpDataMode"></div></td>' +
'	<td align=right><div id="scpBottomArrows" class="scpArrows"></div></td>' +
'</tr>' +
'</table>',
        noRowsTemplate: "No items",
        gridVerticalSpacerTemplate: "&nbsp;",
        gridHorizontalSpacerTemplate: "&nbsp;",
        listHorizontalSpacerTemplate: "&nbsp;",
        autoIntegrate: {
            snapShop: false,
            mapPricing: false,
            productReviews: false,
            googleAnalytics: true
        },
        autoCache: true,
        autoSaveState: true,
        regularPriceText: "Regular Price:",
        salePriceText: "Sale Price:",
        saveNowText: "Save Now:",
        outOfStockText: "Out Of Stock",
        clickToSeeOptionsText: "Click to See Options and to Order",
        quantityInputVisible: false,
        hasProductReviews: false
    };
    this.variable = variable;
    this.storeId = storeId;
    this.items = [];
    this.events = [];
    this.currentData = null;
    this.currentPage = 0;
    this.currentItemsTotal = 0;
    this.currentTotalPages = null;
    this.currentShowAll = false;
    this.dataLayout = null;
    this.filters = {};
    this.sortField = null;
    this.sortOrder = "ASC";
    this.pagingHtmlElement = null;
    this.contentsHtmlElement = null;
    this.filterHtmlElement = null;
    this.navTopHtmlElement = null;
    this.bottomTopHtmlElement = null;
    this.itemsPerPageText = null;
    this.itemsPerPage = null;
    this.publicConfig = null;
    this.renderTimes = 0;
    this.rendering = false;
    this.itemTemplates = {
        gridImage: function(index) {
            if (this.k1!=0 || this.k2!=0 || this.k3!=0) {
                var s="<div class=\"key-product-area\"><a class=img href=\"" + this.u + "\" title=\"" + this.n + "\" style=\"background-image:url(/I/yhst-10308730349237_" + this.i + ")\">&nbsp;</a><div class=\"key-prod-icon\">";
                s=s + "<img src=\"";
                
                if (this.k1==1) s=s+window.scpConfig.k1 
                else if (this.k2==1) s=s+window.scpConfig.k2
                else if (this.k3==1) s=s+window.scpConfig.k3;
                
                s=s + "\">";
                s=s+ "</div></div>";
                return s;
            } else
                return "<a class=img href=\"" + this.u + "\" title=\"" + this.n + "\" style=\"background-image:url(/I/yhst-10308730349237_" + this.i + ")\">&nbsp;</a>";
        },
        //listImage: ['<div class=scpimg>${gridImage}</div>', "listImage"],
        name: function(index) {
            return "<a class=name href=\"" + this.u + "\">" + this.n + "</a>";
        },
        "abstract": ["<div class=scpabstract>code:${abstract}</div>", "abstract"],
        //code: ["<div class=scpcode>code:${code}</div>", "code"],
        //keyIcons: ["", "keyicons"],
        /*productReviews: function (index) {
            if (window.scpConfig.hasProductReviews) {
                var html = '<div pid="' + this.id + '" class="productReviews"';
                if (this.reviewsRating) if (this.reviewsRating.averageRating) {
                    var styleDiv = "";
                    if (window.sprAverageStarsHeight) styleDiv += "height:" + window.sprAverageStarsHeight + ";";
                    if (window.sprStarColor) styleDiv += "background:url(" + window.sprStarColor + ") no-repeat center ";
                    if (this.reviewsRating["averageRating"] !== 0) styleDiv += this.reviewsRating["bgYPosition"];
                    else styleDiv += "0px";
                    return html + ' style="' + styleDiv + '">&nbsp;</div>'
                }
                html += ">&nbsp;</div>";
                return html
            }
            return ""
        },*/
        regularPrice: function (index) {
            if (this.m != 1) if (!$.isEmptyString(this.p) && this.p>0) return '<div class="' + (this.s ? "scpregprice price" : "scpregpriceonly price") + '">${config.regularPriceText}<span>${p:toPrice()}</span></div>';
            return ""
        },
        salePrice: function (index) {
            if (this.m != 1) if (!$.isEmptyString(this.s) && this.s>0) return '<div class="scpsaleprice sale-price">${config.salePriceText}<span>${s:toPrice()}</span></div>';
            return ""
        }/*,
        saveNow: function (index) {
            if (this.mapPrice != true) if (!$.isEmptyString(this.saveNow)) return "<div class=scpsavenow>${config.saveNowText}<span>${saveNow}</span></div>";
            return ""
        }*/
        //,
        //"abstract": ["<div class=scpabstract>${abstract}</div>", "abstract"],
        /*orderForm: function (index, args) {
            if (this.price && this.price > 0) if (this.orderable) if (this.options !== true) if (this.mapPrice) return '<span class=map><form action=${config.orderFormAction}><input id=mapinput type=submit value="Click for instant price quote" height=16 width=155 border=0><a href="javascript:makeMAPWin(300,350);">(Why?)</a><br>${config.addToCartButton}<input type=hidden name=vwitem value="${id}" /><input type=hidden name=vwcatalog value="${config.storeId}" /></form></span>';
            else return '<form action=${config.orderFormAction}>${config.addToCartButton}<input type=hidden name=vwitem value="${id}" /><input type=hidden name=vwcatalog value="${config.storeId}" />' + (args.config.quantityInputVisible ? "<br><input type=text class=scpquantity value=1 />" : "") + "</form>";
            else return "<a href=${url} class=moreoptions>${config.clickToSeeOptionsText}</a>";
            else return "<div class=outofstock>${config.outOfStockText}</div>";
            return ""
        }*/
    };
    this.init = function (configuration) {
        this.options = function (os, defaultPagingOptions) {
            options = os || {};
            var a = [];
            for (var p in defaultPagingOptions) a[p] = options[p] != null ? options[p] : defaultPagingOptions[p];
            return a
        }(configuration, this.defaultPagingOptions);
        
        
        
        $("#scpContents a").each(function(index) {
            
            var p=this.getAttribute("p");
            var s=this.getAttribute("s");
            var h=this.getAttribute("h");
            var w=this.getAttribute("w");
            var b=this.getAttribute("b");
            
            try {
                p=parseFloat(p);
            } catch(e) {
            }
            try {
                s=parseFloat(s);
            } catch(e) {
            }
            try {
                w=parseFloat(w);
            } catch(e) {
            }
            try {
                h=parseFloat(h);
            } catch(e) {
            }
            try {
                b=parseInt(b);
            } catch(e) {
            }
            
            P(
                this.href.replace(/\.html/gi,""),
                this.innerHTML,
                this.href,
                this.getAttribute("f"),
                this.getAttribute("i"),
                p,
                s,
                this.getAttribute("o"),
                this.getAttribute("mp"),
                this.getAttribute("m"),
                b,
                w,
                h,
                this.getAttribute("a")==null?index:this.getAttribute("a"),
                this.getAttribute("k1"),
                this.getAttribute("k2"),
                this.getAttribute("k3")
            );
            
        });
        
        this.filters["fp"]=this.filters["p"];
        
        this.filters["p"]=null;
        
        var ops = this.options;
        this.dataLayout = ops.dataLayoutDefault;
        this.itemsPerPageText = ops.defaultItemsPerPage;
        var vs = ops.sortFieldDefault.split("|");
        if (vs.length == 2) {
            this.sortField = vs[0];
            this.sortOrder = vs[1]
        } else this.sortField = ops.sortFieldDefault;
        this.currentItemsTotal = this.items.length;
        this.calculateItemsPerPage();
        this.calculateTotalPages();
        this.pagingHtmlElement = $("#scPaging").domElement();
        this.contentsHtmlElement = $("#scPaging #scpContents").domElement();
        this.filterHtmlElement = $("#scpFilter").domElement();
        this.navTopHtmlElement = $("#scPaging #scpTopControls").domElement();
        this.navBottomHtmlElement = $("#scPaging #scpBottomControls").domElement();
        this.publicConfig = {
            regularPriceText: ops.regularPriceText,
            salePriceText: ops.salePriceText,
            saveNowText: ops.saveNowText,
            clickToSeeOptionsText: ops.clickToSeeOptionsText,
            outOfStockText: ops.outOfStockText,
            storeId: this.storeId,
            addToCartButton: ops.addToCartButton,
            orderFormAction: "http://order.store.yahoo.net/cgi-bin/wg-order?" + this.storeId,
            quantityInputVisible: ops.quantityInputVisible,
            hasProductReviews: ops.hasProductReviews
        };
        if (ops.autoSaveState) 
            this.getStateFromCookie();
        this.runEvent("onInit");
        this.initIntigration();
        if (ops.navigationVisible) {
            var template = $.template(ops.topNavigationTemplate);
            $(this.navTopHtmlElement).html(template.apply())
        } else $(this.navTopHtmlElement).hide();
        var html = "";
        if (ops.bottomNavigationVisible) {
            var template = $.template(ops.bottomNavigationTemplate);
            $(this.navBottomHtmlElement).html(template.apply())
        } else $(this.navBottomHtmlElement).hide();
        if (ops.dataLayoutVisible) {
            html = '<a href=# class="scplistmode' + (this.dataLayout == "list" ? " selected" : "") + '" onclick="return ' + this.variable + ".changeDataLayout('list');\">List View</a>" + ops.dataLayoutDelimiter + '<a href=#  class="scpgridmode' + (this.dataLayout == "grid" ? " selected" : "") + '" onclick="return ' + this.variable + ".changeDataLayout('grid');\">Grid View</a>";
            $("#scPaging .scpDataMode").html(html)
        }
        if (ops.itemsPerPageVisible) {
            html = "";
            if (ops.itemsPerPagePrefix) html += "<span class=prefix>" + ops.itemsPerPagePrefix + "</span>";
            if (ops.itemsPerPageLayout == "select") html += '<select onchange="return ' + this.variable + '.changeItemsPerPage(this.options[this.selectedIndex].value);">';
            for (var iv = ops.itemsPerPage.split(","), i = 0; i < iv.length; i++) if (ops.itemsPerPageLayout == "select") html += '<option value="' + iv[i] + '" ' + (iv[i] == this.itemsPerPageText ? "selected" : "") + ">" + iv[i] + "</option>";
            else html += "<a href=# " + (iv[i] == this.itemsPerPageText ? 'class="selected"' : "") + ' onclick="' + this.variable + ".changeSelectClass(this, 'scpItemsPerPage'); return " + this.variable + ".changeItemsPerPage('" + iv[i] + "');\">" + iv[i] + "</a>" + (i < iv.length - 1 ? ops.itemsPerPageLinkSeparator : "");
            if (ops.itemsPerPageLayout == "select") html += "</select>";
            $("#scPaging .scpItemsPerPage").html(html)
        }!$.isEmptyString(ops.controlWidth) && $(this.pagingHtmlElement).css("width", ops.controlWidth);
        this.filterHtmlElement = $("#scpFilter").domElement();
        this.renderFilterbar();
        this.render()
    };
    this.initIntigration = function () {
        if (this.options.autoIntegrate.snapShop) if (window.scSnapShop && window.scSnapShop.convertImgLinks) {
            this.addEvent("onAfterRender", function () {
                try {
                    if (this.renderTimes == 0) $(function () {
                        window.scSnapShop.convertImgLinks()
                    });
                    else window.scSnapShop.convertImgLinks()
                } catch (e) {}
            });
            this.addEvent("onAfterItemRender", function (args) {
                if (args) {
                    var td = args["imageCell"] || args["infoCell"];
                    $("div.scpimg img", td).addClass("popImg-0036")
                }
            })
        }
        if (this.options.autoIntegrate.googleAnalytics) window._gat && window._gat._getTrackerByName("~0") && window._gat._getTrackerByName("~0")._trackEvent && this.addEvent("onAfterRender", function () {
            try {
                $("#scPaging form .scp-order-button").click(function () {
                    var item_id = $("input[name=vwitem]", $(this).parent("form").get(0)).value();
                    this.trackGoogleAnalyticsEvent("sc paging", "adding to the cart", item_id)
                });
                $("#scPaging a.moreoptions").click(function () {
                    this.trackGoogleAnalyticsEvent("sc paging", "open item page", this.href)
                })
            } catch (e) {}
        });
        if (this.options.autoIntegrate.productReviews) if (this.options["hasProductReviews"]) {
            var old = $("#scStarProductReviewsScriptWorker");
            old.length > 0 && $(old).remove();
            var script = document.createElement("script");
            script.id = "scStarProductReviewsScriptWorker";
            script.type = "text/javascript";
            for (var ids = "", i = 0; i < this.items.length; i++) {
                if (ids != "") ids = ids + "|";
                ids = ids + this.items[i].id
            }
            var url = "http://admin.starproductreviews.com/scripts/customAverageRating.php?";
            url += "store=" + this.storeId + "&";
            url += "id=" + ids + "&";
            url += "callback=scPaging.starProductReviewsCallback";
            script.src = url;
            var heads = window.document.getElementsByTagName("head");
            heads && heads[0] && heads[0].appendChild(script)
        }
    };
    this.trackGoogleAnalyticsEvent = function (category, action, opt_label, opt_value) {
        var trackerName = "~0";
        if (category == null) return window._gat && window._gat._getTrackerByName(trackerName) && window._gat._getTrackerByName(trackerName)._trackEvent ? true : false;
        if (window._gat && window._gat._getTrackerByName(trackerName) && window._gat._getTrackerByName(trackerName)._trackEvent) {
            window._gat._getTrackerByName(trackerName)._setVar($.yahoo.pageId);
            window._gat._getTrackerByName(trackerName)._trackEvent(category, action, opt_label, opt_value)
        }
    };
    this.starProductReviewsCallback = function () {
        if (window.sprItems) for (var p in window.sprItems) {
            for (var anyThing = false, i = 0; i < this.items.length; i++) if (this.items[i].id == p) {
                var sprItem = window.sprItems[p];
                this.items[i].averageReviewsRating = $.forceInt(sprItem.averageRating);
                this.items[i].reviewsRating = {
                    averageRating: $.forceInt(sprItem.averageRating),
                    bgYPosition: sprItem.bgYPosition
                };
                anyThing = true
            }
            if (!anyThing) this.items[i].reviewsRating = {
                averageRating: 0,
                bgYPosition: ""
            }
        }
        this.renderTimes > 0 && $(".productReviews").each(function () {
            this.getAttribute("pid") && window.sprItems[this.getAttribute("pid")] && $(this).css({
                height: window.sprAverageStarsHeight,
                "background-image": "url(" + window.sprStarColor + ")",
                "background-position": "center " + window.sprItems[this.getAttribute("pid")]["bgYPosition"]
            })
        })
    };
    this.calculateItemsPerPage = function () {
        if (this.itemsPerPageText == null) this.itemsPerPageText = this.options.itemsPerPage;
        if (this.itemsPerPageText.toLowerCase() == "all") this.itemsPerPage = this.currentItemsTotal;
        else this.itemsPerPage = $.forceInt(this.itemsPerPageText)
    };
    this.updateItemTemplate = function (name, value) {
        this.itemTemplates[name] = value
    };
    this.calculateTotalPages = function () {
        this.currentTotalPages = Math.floor(this.currentItemsTotal / this.itemsPerPage);
        if (this.currentItemsTotal % this.itemsPerPage != 0) this.currentTotalPages++
    };
    this.addEvent = function (eventName, func) {
        if (this.events[eventName] == null) this.events[eventName] = [];
        this.events[eventName].push(func)
    };
    this.runEvent = function (eventName, args) {
        if (this.events[eventName]) {
            for (var funcs = this.events[eventName], i = 0; i < funcs.length; i++) if ($.typeOf(funcs[i]) == "function") {
                args = args || [];
                args["sender"] = this;
                var result = funcs[i].call(this, args);
                if (funcs.length == 1) return result
            }
            return true
        }
    };
    this.addItem = function (x) {
        var a = [];
        for (var p in x) a[p] = x[p];
        a.paging = this;
        a.originalIndex = this.items.length;
        a.cache = null;
        this.items.push(a)
    };
    this.clearCache = function () {
        for (var i = 0; i < this.items.length; i++) this.items[i].cache = null
    };
    this.distinctItemValues = function (fieldName) {
        for (var a = [], i = 0; i < this.items.length; i++) if (this.items[i][fieldName] != null) for (var vs = this.items[i][fieldName].split("|"), u = 0; u < vs.length; u++) {
            for (var b = true, curr = vs[u], j = 0; j < a.length; j++) if (curr == a[j]) {
                b = false;
                break
            }
            b && curr != null && a.push(curr)
        }
        return a
    };
    this.matchFilters = function (item, index) {
        var filters = item.paging.filters;
        for (var fieldName in filters) if ($.typeOf(filters[fieldName]) != "function") {
            if (filters[fieldName]==null) continue;
            var value = item[fieldName];
            if (value != null) {
                for (var b = 0, i = 0, len = filters[fieldName].length; i < len; i++) {
                    var op = filters[fieldName][i][0],
                        x = filters[fieldName][i][1];
                    if (x != null && op != null) {
                        if (op != "-" && $.typeOf(value) != $.typeOf(x)) switch ($.typeOf(value).toLowerCase()) {
                        case "string":
                            x = new String(x);
                            break;
                        case "number":
                            x = $.forceFloat(x);
                            break
                        }
                        var ev = null;
                        switch (op) {
                        case "=":
                            ev = value == x;
                            break;
                        case "~":
                            ev = false;
                            for (var vs = value.split("|"), k = 0; k < vs.length; k++) if (vs[k] == x) {
                                ev = true;
                                break
                            }
                            break;
                        case ">":
                            ev = value > x;
                            break;
                        case "<":
                            ev = value <= x;
                            break;
                        case "-":
                            if (x.indexOf("-") > 0 && x.substring(x.length - 1) != "-") {
                                var x1 = $.forceFloat(x.substr(0, x.indexOf("-"))),
                                    x2 = $.forceFloat(x.substr(x.indexOf("-") + 1));
                                ev = value >= x1 && value <= x2
                            }
                            break
                        }
                        if (ev != null) if (ev == false) b = 1;
                        else {
                            b = 2;
                            break
                        }
                    }
                }
                if (b == 1) return false
            } else return false
        }
        return true
    };
    this.addFilter = function (field, operator, value) {
        if (this.filters[field] == null) this.filters[field] = [];
        this.filters[field].push([operator, value])
    };
    this.removeAllFilters = function () {
        this.filters = {};
    };
    this.removeFilter = function (field, value) {
        if (this.filters[field] != null) if (value == null) delete this.filters[field];
        else for (var i = 0, len = this.filters[field].length; i < len; i++) if (this.filters[field][i][1] == value) {
            this.filters[field].splice(i, 1);
            if (this.filters[field] != null && this.filters[field].length == 0) delete this.filters[field];
            break
        }
    };
    this.filterData = function (orig) {
        if (this.filters == null) {
            this.currentItemsTotal = orig.length;
            return orig
        }
        var a = $.grep(orig, this.matchFilters);
        this.currentItemsTotal = a.length;
        this.calculateTotalPages();
        return a
    };
    this.sortData = function (orig) {
        if (this.sortField == null || orig == null || orig.length == 0) return orig;
        var data = orig.slice(0);
        this.sortField != "initial" && data.sort(function (x, y) {
            var a = x[x.paging.sortField],
                b = y[y.paging.sortField];
            if (a == null && b == null) return 0;
            if (a != null && b != null) {
                if (a < b) return -1;
                if (a > b) return 1;
                if (a == b) return 0
            } else if (a != null) return 1;
            else return -1
        });
        this.sortOrder == "DESC" && data.reverse();
        return data
    };
    this.pageData = function (orig) {
        if (orig == null || orig.length < this.itemsPerPage || this.currentShowAll) return orig;
        var startItemIndex = this.currentPage * this.itemsPerPage;
        if (startItemIndex < 0 || startItemIndex >= orig.length) return [];
        var data = orig.slice(startItemIndex, startItemIndex + this.itemsPerPage);
        return data
    };
    this.getData = function () {
        var data = this.items;
        data = this.pageData(this.sortData(this.filterData(data)));
        if (data == null) data = [];
        this.currentData = data;
        return data
    };
    this.getPageId = function () {
        return document.location.href.substr(document.location.href.lastIndexOf("/") + 1)
    };
    this.getStateFromCookie = function () {
        var pageId = this.getPageId(),
            cookiePageId = $.cookie("scp-id");
        if (pageId == cookiePageId) {
            this.currentPage = $.cookie("scp-num");
            if (this.currentPage==null)
                this.currentPage=0;
            var cookieSort = $.cookie("scp-sort"),
                cookieFilter = $.cookie("scp-filter"),
                cookieDataLayout = $.cookie("scp-data-layout"),
                cookieItemsPerPage = $.cookie("scp-items-per-page");
            if (!$.isEmptyString(cookieSort)) {
                var vs = cookieSort.split("|");
                if (vs.length == 2) {
                    this.sortField = vs[0];
                    this.sortOrder = vs[1]
                } else this.sortField = cookieSort
            }
            if (!$.isEmptyString(cookieFilter)) this.filters = $.parseJSON(cookieFilter);
            if (!$.isEmptyString(cookieDataLayout)) this.dataLayout = cookieDataLayout;
            if (!$.isEmptyString(cookieItemsPerPage)) {
                this.itemsPerPageText = cookieItemsPerPage;
                this.calculateItemsPerPage();
            }
        }
        this.calculateTotalPages();
    };
    this.setStateInCookie = function () {
    
        var cConfig={
            domain:window.location.hostname,
            path:"/"
        };
    
        $.cookie("scp-id", this.getPageId(),cConfig);
        $.cookie("scp-num", this.currentPage,cConfig);
        $.cookie("scp-sort", this.sortField + "|" + this.sortOrder,cConfig);
        
        var s="";
        
        for (var f in this.filters) {
            if ($.isArray(this.filters[f])) {
                var a=$.toJSON(this.filters[f]);
                if (s!="") s=s + ",";
                s=s + "\"" + f + "\":" + a;
            }
        }
        
        $.cookie("scp-filter", "{" + s + "}",cConfig);
        $.cookie("scp-data-layout", this.dataLayout,cConfig);
        $.cookie("scp-items-per-page", this.itemsPerPageText,cConfig)
    };
    this.changeSelectClass = function (obj, insideClass) {
        $("#scPaging ." + insideClass + " a.selected").removeClass("selected");
        $(obj).addClass("selected")
    };
    this.navigateCtrlKeyed = function (e) {
        if (!e) e = window.event;
        var key = e.keyCode ? e.keyCode : e.which,
            target = e.target;
        if (e.srcElement) target = e.srcElement;
        key == 13 && target.blur()
    };
    this.navigateCtrlChanged = function (target, nV, oV) {
        if ($.isPositiveInt(nV)) {
            var x = $.forceInt(nV) - 1;
            if (x >= 0 && x < this.currentTotalPages) this.changePage(x);
            else target.value = oV
        } else target.value = oV
    };
    this.changePage = function (x) {
        var x = $.forceInt(x);
        this.options.autoIntegrate && this.options.autoIntegrate.googleAnalytics && this.trackGoogleAnalyticsEvent("sc paging", "change page", "page " + (x + 1));
        this.currentShowAll = false;
        this.currentPage = $.forceInt(x);
        this.render();
        return false
    };
    this.changeToShowAll = function () {
        this.options.autoIntegrate && this.options.autoIntegrate.googleAnalytics && this.trackGoogleAnalyticsEvent("sc paging", "change page", "all");
        this.currentShowAll = true;
        this.render();
        this.tryChangeItemsPerPage();
        return false
    };
    this.tryChangeItemsPerPage = function () {};
    this.changeItemsPerPage = function (x) {
        if (x == null) return;
        this.options.autoIntegrate && this.options.autoIntegrate.googleAnalytics && this.trackGoogleAnalyticsEvent("sc paging", "change items per page", x);
        this.currentShowAll = false;
        this.itemsPerPageText = x;
        this.calculateItemsPerPage();
        this.currentPage = 0;
        this.calculateTotalPages();
        this.render();
        return false
    };
    this.changeDataLayout = function (dataLayout) {
        this.options.autoIntegrate && this.options.autoIntegrate.googleAnalytics && this.trackGoogleAnalyticsEvent("sc paging", "change layout", dataLayout);
        $(".scpDataMode a.selected", this.pagingHtmlElement).removeClass("selected");
        $("a.scp" + dataLayout + "mode", this.pagingHtmlElement).addClass("selected");
        this.dataLayout = dataLayout;
        this.render();
        return false
    };
    this.changeSort = function (changeTo) {
        this.currentPage=0;
        var vs = changeTo.split("|");
        if (vs.length == 2) {
            this.sortField = vs[0];
            this.sortOrder = vs[1]
        } else {
            this.sortField = changeTo;
            if (this.sortOrder == "ASC") this.sortOrder = "DESC";
            else this.sortOrder = "ASC"
        }
        this.options.autoIntegrate && this.options.autoIntegrate.googleAnalytics && this.trackGoogleAnalyticsEvent("sc paging", "change sort", this.sortField + " | " + this.sortOrder);
        this.render();
        return false
    };
    this.changeFilter = function (fieldName, value, exclusive, clear) {
        this.options.autoIntegrate && this.options.autoIntegrate.googleAnalytics && this.trackGoogleAnalyticsEvent("sc paging", "change filter", fieldName + "=" + (value != null) ? value : "");
        var v = value,
            op = "=";
        if (v != null) if ($.startWith(v, "=") || $.startWith(v, ">") || $.startWith(v, "<") || $.startWith(v, "-") || $.startWith(v, "~")) {
            op = v.substr(0, 1);
            v = v.substr(1)
        }
        if (exclusive) this.removeFilter(fieldName);
        else clear && this.removeFilter(fieldName, v);
        clear != true && this.addFilter(fieldName, op, v);
        this.currentPage=0;
        this.calculateTotalPages();
        this.render();
        return false
    };
    this.render = function () {
        this.rendering = true;
        this.getData();
        if (this.options.autoSaveState)
            this.setStateInCookie();
        this.renderSortbar();
        this.renderNavbar();
        this.renderData();
        this.renderTimes++;
        this.rendering = false
    };
    this.getItemConfig = function (item, index) {
        var a = [],
            itemConfig = [];
        for (var p in item) {
            if (p == "paging") continue;
            itemConfig[p] = item[p]
        }
        itemConfig["config"] = this.publicConfig;
        itemConfig["index"] = index;
        for (var itemTemplate in this.itemTemplates) {
            var templateConfig = this.itemTemplates[itemTemplate],
                templateText = null;
            if ($.typeOf(templateConfig) == "string") templateText = templateConfig;
            else if ($.typeOf(templateConfig) == "function") {
                var test_func = templateConfig;
                templateText = test_func.call(item, index, itemConfig)
            } else if ($.typeOf(templateConfig) == "array") {
                templateText = templateConfig[0];
                var test_func = templateConfig[1],
                    false_template = templateConfig[2],
                    test_result = true;
                if (test_func) {
                    if ($.typeOf(test_func) == "function") test_result = test_func.call(item, index, itemConfig);
                    else if ($.typeOf(test_func) == "string") {
                        test_result = item[test_func];
                        if (test_result == null || test_result == "") test_result = false
                    }
                    if (test_result == false) templateText = false_template
                }
            }
            if (!$.isEmptyString(templateText)) {
                var template = $.template(templateText);
                a[itemTemplate] = template.apply(itemConfig)
            }
        }
        a["item"] = item;
        a["config"] = itemConfig;
        a["index"] = index;
        return a
    };
    this.renderData = function () {
        this.runEvent("onBeforeRender");
        var data = this.currentData,
            dc = this.currentData.length,
            ops = this.options;
        if (this.contentsHtmlElement == null) return;
        $(this.contentsHtmlElement).empty();
        $(this.contentsHtmlElement).removeClass("gridContents").removeClass("listContents").addClass(this.dataLayout + "Contents");
        for (var itemIndex = 0, assembledConfigs = [], itemIndex = 0; itemIndex < dc; itemIndex++) if (ops.autoCache) if (data[itemIndex].cache == null) {
            assembledConfigs[itemIndex] = this.getItemConfig(data[itemIndex], itemIndex);
            data[itemIndex].cache = assembledConfigs[itemIndex]
        } else assembledConfigs[itemIndex] = data[itemIndex].cache;
        else assembledConfigs[itemIndex] = this.getItemConfig(data[itemIndex], itemIndex);
        var tbody = $("<table>").attr({
            cellPadding: 0,
            cellSpacing: 0
        }).append("<tbody/>").domElement(),
            rowsIndex = 0;
        if (dc == 0) {
            var tr = $("<tr>").addClass("scpEmptyRow").appendTo(tbody),
                td = $("<td>").appendTo(tr);
            td.html(ops.noRowsTemplate)
        }
        
        if (this.dataLayout == "grid") {
            var totalRows = Math.floor(dc / ops.gridColumns);
            if (dc % ops.gridColumns != 0) totalRows = totalRows + 1;
            for (var rowsIndex = 0; rowsIndex < totalRows; rowsIndex++) {
                var tr1 = null,//$("<tr>").addClass("scpImageGridRow").appendTo(tbody),
                    tr2 = $("<tr>").addClass("scpInfoGridRow").appendTo(tbody),
                    tr3 = null;
                if (!$.isEmptyString(ops.gridItemInfoTemplate2)) tr3 = $("<tr>").addClass("scpInfoGridRow2").appendTo(tbody);
                var tr4 = null;
                if (ops.gridHorizontalSpacerVisible) tr4 = $("<tr>").addClass("scpHorizontalGridSpacerRow").appendTo(tbody);
                if (rowsIndex == totalRows - 1) {
                    tr1 && tr1.addClass("last");
                    tr2 && tr2.addClass("last");
                    tr3 && tr3.addClass("last");
                    tr4 && tr4.addClass("lastSpacer")
                }
                itemIndex = rowsIndex * ops.gridColumns;
                for (var i = 0, cols = ops.gridColumns; i < cols; i++) {
                    var td1 = td2 = td3 = td4 = td5 = td6 = null;
                    this.runEvent("onBeforeItemRender", [assembledConfigs[itemIndex]]);
                    if (!$.isEmptyString(ops.gridItemImageTemplate)) {
                        var template = $.template(ops.gridItemImageTemplate);
                        td1 = $("<td>").addClass("scpimgcell").appendTo(tr1);
                        if (assembledConfigs[itemIndex]) td1.html(template.apply(assembledConfigs[itemIndex]));
                        else td1.addClass("empty")
                    }
                    if (!$.isEmptyString(ops.gridItemInfoTemplate)) {
                        var template = $.template(ops.gridItemInfoTemplate);
                        td2 = $("<td>").addClass("scpinfocell").appendTo(tr2);
                        
                        if (assembledConfigs[itemIndex]) td2.html(template.apply(assembledConfigs[itemIndex]));
                        else td2.addClass("empty")
                    }
                    if (!$.isEmptyString(ops.gridItemInfoTemplate2)) {
                        var template = $.template(ops.gridItemInfoTemplate2);
                        td6 = $("<td>").addClass("scpinfocell").appendTo(tr3);
                        if (assembledConfigs[itemIndex]) td6.html(template.apply(assembledConfigs[itemIndex]));
                        else td6.addClass("empty")
                    }
                    if (ops.gridHorizontalSpacerVisible) {
                        td4 = $("<td>").addClass("gridHorizontalSpacer").appendTo(tr4);
                        td4.html(ops.gridHorizontalSpacerTemplate)
                    }
                    if (i + 1 < cols) {
                        if (ops.gridVerticalSpacerVisible) {
                            td3 = $("<td>").addClass("gridVerticalSpacer").appendTo(tr11=null?tr1:tr2);
                            if (!$.isEmptyString(ops.gridItemInfoTemplate2)) td3.html(ops.gridVerticalSpacerTemplate).attr("rowSpan", 3);
                            else td3.html(ops.gridVerticalSpacerTemplate)
                        }
                        if (ops.gridHorizontalSpacerVisible) {
                            td5 = $("<td>").addClass("gridHorizontalCrossSpacer").appendTo(tr4);
                            td5.html(ops.gridHorizontalCrossTemplate)
                        }
                    }
                    if (!$.isEmptyString(ops.gridColumnWidth)) {
                        var ws = ops.gridColumnWidth.toLowerCase();
                        if (ws == "px") {
                            var wc = null;
                            if (!$.isEmptyString(ops.controlWidth)) wc = $.forceInt(ops.controlWidth);
                            else wc = $(this.pagingHtmlElement).width();
                            if (wc) {
                                var wspacer = 0;
                                if (!$.isEmptyString(ops.gridSpacerWidth)) wspacer = $.forceInt(ops.gridSpacerWidth);
                                var calcWidth = ($.forceInt(wc) - wspacer * (cols - 1)) / cols;
                                if (td1!=null) td1.attr("width", calcWidth);
                                if (td2!=null) td2.attr("width", calcWidth)
                            }
                        } else if (ws == "%") {
                            if (td1!=null) td1.attr("width", $.forceInt(100 / cols) + "%");
                            if (td2!=null) td2.attr("width", $.forceInt(100 / cols) + "%")
                        } else {
                            if (td1!=null) td1.attr("width", ws);
                            if (td2!=null) td2.attr("width", ws)
                        }
                    }
                    this.runEvent("onAfterItemRender", {
                        imageCell: td1,
                        infoCell: td2,
                        infoCell2: td6
                    });
                    itemIndex++
                }
            }
        } else for (var totalRows = dc, rowsIndex = 0; rowsIndex < totalRows; rowsIndex++) if (!$.isEmptyString(ops.listItemTemplate)) {
            itemIndex = rowsIndex;
            var td = td4 = null;
            this.runEvent("onBeforeItemRender", [assembledConfigs[itemIndex]]);
            var tr = $("<tr>").addClass("scpListRow").appendTo(tbody),
                tr4 = null;
            if (ops.listHorizontalSpacerVisible) tr4 = $("<tr>").addClass("listHorizontalSpacerRow").appendTo(tbody);
            var template = $.template(ops.listItemTemplate);
            td = $("<td>").addClass("scpListCell").appendTo(tr);
            td.html(template.apply(assembledConfigs[itemIndex]));
            if (ops.listHorizontalSpacerVisible) {
                td4 = $("<td>").addClass("listHorizontalSpacer").appendTo(tr4);
                td4.html(ops.listHorizontalSpacerTemplate)
            }
            if (rowsIndex == totalRows - 1) {
                tr.addClass("last");
                tr4 && tr4.addClass("lastSpacer")
            }
            this.runEvent("onAfterItemRender", {
                infoCell: td
            })
        }
        $(this.contentsHtmlElement).append(tbody);
        this.runEvent("onAfterRender", {
            infoCell: td
        })
    };
    this.renderNavbar = function () {
        this.runEvent("onBeforeNavRender");
        
        var data = this.currentData,
            ops = this.options,
            htmlConfigs = {},
            min = this.currentPage * this.itemsPerPage + 1,
            max = min + this.itemsPerPage - 1 > this.currentItemsTotal ? this.currentItemsTotal : min + this.itemsPerPage - 1;
        if (this.currentItemsTotal == 0) min = 0;
        if (this.currentShowAll) {
            min = 1;
            max = this.currentItemsTotal
        }
        if (ops.pagesLinksVisible) {
            var html = "";
            if (this.currentTotalPages > 0) {
                var startPage = 0,
                    maxPages = this.currentTotalPages,
                    ellipseAfter = $.forceInt(ops.pagesLinksEllipsisAfter),
                    pagesLinksMax = $.forceInt(ops.pagesLinksMax),
                    exitFor = false;
                if (ops.pagesLinksEllipsisAfter != "none") {
                    startPage = this.currentPage - ellipseAfter + 2;
                    if (startPage > this.currentTotalPages - ellipseAfter) startPage = this.currentTotalPages - ellipseAfter
                } else if (ops.pagesLinksMax != "none") if (pagesLinksMax + this.currentPage < this.currentTotalPages) startPage = this.currentPage - 1;
                else {
                    startPage = this.currentTotalPages - pagesLinksMax;
                    if (this.currentPage == startPage) startPage = startPage - 1
                }
                if (startPage < 0) startPage = 0;
                if (ops.pagesLinksMax != "none") maxPages = startPage + pagesLinksMax;
                if (maxPages > this.currentTotalPages) maxPages = this.currentTotalPages;
                for (var i = startPage; i < maxPages && exitFor == false; i++) {
                    if (ops.pagesLinksEllipsisAfter != "none" && i - startPage >= ellipseAfter) {
                        html += '<span class="ellipse">...</span>';
                        i = maxPages - 1;
                        exitFor = true
                    }
                    var cssClass = i == this.currentPage && this.currentShowAll == false ? 'class="selected"' : "";
                    if (ops.pagesLinksMode == "items") {
                        var cMin = i * this.itemsPerPage + 1,
                            cMax = cMin + this.itemsPerPage - 1 > this.currentItemsTotal ? this.currentItemsTotal : cMin + this.itemsPerPage - 1;
                        html += "<a href=# " + cssClass + ' onclick="return ' + this.variable + ".changePage(" + i + ');">' + cMin + "-" + cMax + "</a>"
                    } else html += "<a href=# " + cssClass + ' onclick="return ' + this.variable + ".changePage(" + i + ');">' + (i + 1) + "</a>";
                    if (i < maxPages - 1 && !(ops.pagesLinksEllipsisAfter != "none" && i + 1 - startPage >= ellipseAfter)) html += ops.pagesLinksSeparator;
                    if (exitFor) break
                }
                if (ops.pagesLinksMax != "none") {
                    if (startPage > 0) html = "<span class=maxprefix>" + ops.pagesLinksMaxPrefix + "</span>" + html;
                    if (startPage + pagesLinksMax < this.currentTotalPages) html += "<span class=maxpostfix>" + ops.pagesLinksMaxPostfix + "</span>"
                }
                if (maxPages > 1) if (ops.pagesLinksShowAll) {
                    html += ops.pagesLinksSeparator;
                    html += "<a href=# " + (this.currentShowAll ? 'class="selected"' : "") + ' onclick="return ' + this.variable + '.changeToShowAll();">' + ops.pagesLinksShowAllText + "</a>"
                }
            } else html += "0";
            html = '<span class="prefix">' + ops.pagesLinksPrefix + "</span>" + html;
            $(".scpPages", this.pagingHtmlElement).html(html)
        }
        ops.totalItemsVisible && $(".scpNumbers", this.pagingHtmlElement).html('<span class="prefix">' + ops.totalItemsPrefix + '</span><span class="currentItems">' + min + "-" + max + '</span> of <span class="total">' + this.currentItemsTotal + "</span>");
        if (ops.pagesNavigationVisible) {
            html = "";
            if (this.currentPage != 0) {
                if (!$.isEmptyString(ops.arrowFirst)) html += '<a href=# class="scpFirst" onclick="return ' + this.variable + '.changePage(0);">' + ops.arrowFirst + "</a>";
                if (!$.isEmptyString(ops.arrowPrev)) html += '<a href=# class="scpPrev" onclick="return ' + this.variable + ".changePage(" + (this.currentPage - 1) + ');">' + ops.arrowPrev + "</a>"
            } else {
                if (!$.isEmptyString(ops.arrowFirstOff) || this.currentShowAll) html += ops.arrowFirstOff;
                if (!$.isEmptyString(ops.arrowPrevOff) || this.currentShowAll) html += ops.arrowPrevOff
            }
            if (ops.navigateToPageControlVisible) if (!this.currentShowAll) if (ops.navigateToPageControlReadOnly) {
                var pagesText = ops.navigateToPagePagesVisible ? this.currentPage + 1 + " of " + this.currentTotalPages : this.currentPage + 1;
                html += "<span class=scpNavigateToPage><span class=prefix>" + ops.navigateToPagePrefix + "</span>" + pagesText + "</span>"
            } else html += '<input type=text class=scpNavigateToPage value="' + (this.currentPage + 1) + '" onblur="if (this.orig!=this.value) ' + this.variable + '.navigateCtrlChanged(this, this.value, this.orig);" onfocus="this.orig=this.value" onkeyup="this.value=this.value;' + this.variable + '.navigateCtrlKeyed(event)" />';
            else html += "<span class=scpNavigateToPage><span class=prefix>" + ops.navigateToPagePrefix + "</span>Viewing all</span>";
            else html += "<span class=sep></span>";
            if (this.currentPage != this.currentTotalPages - 1) {
                if (!$.isEmptyString(ops.arrowNext)) html += '<a href=# class="scpNext" onclick="return ' + this.variable + ".changePage(" + (this.currentPage + 1) + ');">' + ops.arrowNext + "</a>";
                if (!$.isEmptyString(ops.arrowLast)) html += '<a href=# class="scpLast" onclick="return ' + this.variable + ".changePage(" + (this.currentTotalPages - 1) + ');">' + ops.arrowLast + "</a>"
            } else {
                if (!$.isEmptyString(ops.arrowNextOff) || this.currentShowAll) html += ops.arrowNextOff;
                if (!$.isEmptyString(ops.arrowLastOff) || this.currentShowAll) html += ops.arrowLastOff
            }
            $(".scpArrows", this.pagingHtmlElement).html(html)
        }
        this.runEvent("onAfterNavRender")
    };
    this.renderSortbar = function () {
        if (!this.options.sortVisible) return;
        var html = "";
        if (!$.isEmptyString(this.options.sortPrefix)) html += '<span class="prefix">' + this.options.sortPrefix + "</span>";
        if (this.options.sortLayout == "select") html += '<select onchange="' + this.variable + '.changeSort(this.options[this.selectedIndex].value)">';
        for (var i = 0, count = this.options.sortFields.length; i < count; i++) {
            var fc = this.options.sortFields[i],
                f = fc[0],
                order = fc[1],
                changeTo = f,
                biDir = order.indexOf("|") > 0;
            if (!biDir) changeTo = f + "|" + order;
            if (this.options.sortLayout == "select") html += '<option value="' + changeTo + '" ' + ((f == this.sortField || this.sortField == "" && f == "initial") && (biDir || this.sortOrder == order) ? ' selected="selected" selected="true" ' : "") + ">" + fc[2] + "</option>";
            else {
                if (i != 0) html += this.options.sortSeparator;
                var cssClass = "";
                if ((f == this.sortField || this.sortField == "" && f == "initial") && (biDir || this.sortOrder == order)) {
                    cssClass = "selected";
                    if (biDir) if (this.sortOrder == "ASC") cssClass += " asc";
                    else cssClass += " desc"
                }
                if (i == count - 1) if (cssClass != "") cssClass += " last";
                else cssClass = "last";
                if (cssClass != "") cssClass = ' class="' + cssClass + '"';
                html += "<a href=# " + cssClass + ' onclick="return ' + this.variable + ".changeSort('" + changeTo + "');\">" + fc[2] + "</a>"
            }
        }
        if (this.options.sortLayout == "select") html += "</select>";
        $(".scpSort", this.pagingHtmlElement).each(function () {
            this.innerHTML = html
        })
    };
    this.renderFilterbar = function () {
        this.runEvent("onBeforeFilterRender");
        if (!this.options.filterVisible || this.filterHtmlElement == null) {
            $("#scpFilter").hide();
            return
        }
        var html = "";
        
        if (!$.isEmptyString(this.options.filterPrefix)) html += '<h1 class="prefix">' + this.options.filterPrefix + "</h1>";
        $(this.filterHtmlElement).html(html);
        var i = 0;
        this.options.filterLayout == "vertical" && $(this.filterHtmlElement).addClass("vertical");
        for (var f in this.options.filterFields) {
            if (this.options.filterFields[f]==null || this.options.filterFields[f].length==0 || $.isFunction(this.options.filterFields[f]))
                continue;  
            var fc = this.options.filterFields[f],
                ctype = "select",  //fc[0]
                ftitle = fc[1],
                ops = fc[2],
                div = $("<div>").addClass("scpFilter").appendTo(this.filterHtmlElement);
            $("<span>").addClass("prefix").html(ftitle).appendTo(div);
            var ul = $("<ul>").addClass("scpFilterList").appendTo(div),
                vs = function (ob, field, fc) {
                    var ops = fc[2] || {
                        mode: "distinct"
                    },
                        a = [];
                    if (ops["mode"] == null) ops["mode"] = "distinct";
                    switch (ops["mode"]) {
                    case "distinct":
                        a = ob.distinctItemValues(field);
                        if (ops["set"]) for (var i = 0; i < a.length; i++) a[i] = "~" + a[i];
                        break;
                    case "range":
                        for (var min = null, max = null, i = 0; i < ob.items.length; i++) {
                            var v = ob.items[i][field];
                            if (v != null) if ($.isFloat(v)) {
                                var vc = $.forceFloat(v);
                                if (min == null || min > vc) min = vc;
                                if (max == null || max < vc) max = vc
                            } else return []
                        }
                        var range = ops["range"] || 5,
                            start = min;
                        if (ops["min"] != null) start = ops["min"];
                        for (var end = ops["max"] || max, inc = Math.ceil((end - start) / range), i = start; i < end; i = i + inc) {
                            var n = i,
                                m = n + inc;
                            if (m > end) m = end;
                            if (ops["format"] == "price") a.push(["-" + n + "-" + m, $.toPrice(n) + "-" + $.toPrice(m)]);
                            else a.push("-" + n + "-" + m)
                        }
                        break;
                    case "custom":
                        if (ops["func"] != null) a = ops["func"](ob, field);
                        break
                    }
                    return a
                }(this, f, fc),
                select = null;
            if (ctype == "select") {
                select = $("<select filter_name=\"" + f + "\">").appendTo($("<li>").addClass("scpFilterLine").appendTo(ul));
                $(select).domElement().onchange = function (obj, field) {
                    return function () {
                        var f = field,
                            v = this.options[this.selectedIndex].value;
                        if (v != "") obj.changeFilter(f, v, true);
                        else obj.changeFilter(f, "", true, true)
                    }
                }(this, f)
            }
            var el = label = null;
            if (ops.first) {
                switch (ctype) {
                case "radio":
                    el = '<input type=radio name="filter-' + f + '" onclick="' + this.variable + ".changeFilter('" + f + "',null,true,true);\" />";
                    label = ops.first;
                    break;
                case "links":
                    el = '<a href=# onclick="return ' + this.variable + ".changeFilter('" + f + "',null,true,true);\" >" + ops.first + "</a>";
                    break;
                case "select":
                    $("<option>").attr("value", "").html(ops.first).appendTo(select);
                    break
                }
                if (ctype != "select") {
                    var li = $("<li>").addClass("scpFilterLine").appendTo(ul);
                    if (this.options.filterLabelAlign == "right") $(li).append(el).append(label);
                    else $(li).append(label).append(el)
                }
            }
            for (var j = 0; j < vs.length; j++) {
                var v = null;
                el = null;
                label = null;
                if ($.typeOf(vs[j]) == "array") {
                    v = vs[j][0];
                    label = vs[j][1]
                } else {
                    v = label = vs[j];
                    if ($.startWith(v, "=") || $.startWith(v, ">") || $.startWith(v, "<") || $.startWith(v, "-") || $.startWith(v, "~")) label = v.substr(1)
                }
                switch (ctype) {
                case "radio":
                    el = '<input type=radio name="filter-' + f + '" onclick="' + this.variable + ".changeFilter('" + f + "','" + v + "',true);\" />";
                    break;
                case "checkbox":
                    el = '<input type=checkbox onclick="' + this.variable + ".changeFilter('" + f + "','" + v + "',false, !this.checked); \" />";
                    break;
                case "links":
                    el = '<a href=# onclick="return ' + this.variable + ".changeFilter('" + f + "','" + v + "',true);\" >" + label + "</a>";
                    label = null;
                    break;
                case "select":
                    $("<option>").attr("value", v).html(label).appendTo(select);
                    break
                }
                if (ctype != "select") {
                    var li = $("<li>").addClass("scpFilterLine").appendTo(ul);
                    j == vs.length - 1 && $(li).addClass("last");
                    if (this.options.filterLabelAlign == "right") $(li).append(el).append(label);
                    else $(li).append("<span>" + label + "</span>").append(el)
                }
            }
            i++
        }
        //if (this.options.filterResetAllVisible);
        
        for (var f in this.filters) {
            if ($.isArray(this.filters[f])) {
                var k=this.filters[f];
                $(".scpFilterLine select[filter_name=\"" + f + "\"] option").each(function(ind) {
                    if (this.value==k[0][1]) {
                        this.selected="selected";
                        this.parentNode.selectedIndex=ind;
                    }
                });
            }
        }
        
        this.runEvent("onAfterFilterRender")
    }
}

function P(id,name,u,finish,image,price,sale,orderable,mappricing,manufacturer,bulbs,width,height,best,k1,k2,k3) {
    
    var bInt=scPaging.items.length;
    
    try {
        bInt=parseInt(best);
    } catch(e) {
    }
    
    scPaging.addItem({
        
        n:name,
        id:id,
        u:u,
        f:finish==""?null:finish,
        i:image,
        p:price,
        s:sale,
        fp:sale==null?price:sale,
        o:orderable==null?1:0,
        mp:mappricing==null?0:1,
        m:manufacturer==""?null:manufacturer,
        b:bulbs==""?null:bulbs,
        w:width==""?null:width,
        h:height==""?null:height,
        bi:bInt,
        k1:k1==null?0:1,
        k2:k2==null?0:1,
        k3:k3==null?0:1
    
    });
}
