﻿var biens = new Class({
    _items: [],
    _maxPricesVal: { min: Number.MAX_VALUE, max: 0 },
    _filtersObject: false,
    _detailRequest: false,
    _currentOrder: "p",
    _currentFilters: {},
    _sliders: [],
    _mainScroll: false,
    _needsRefresh: false,
    _cookie: false,
    _call: function (o) {
        switch (o.a) {
            case "filter":
                this._toggleFilter(o.c, o.v);
                this._cookie.set("filters", this._currentFilters);
                site.HM.set("filters", this._currentFilters);
                this._filter();
                this._refresh();
                break;
            case "order":
                this._currentOrder = o.v;
                this._cookie.set("order", this._currentOrder);
                site.HM.set("order", this._currentOrder);
                this._order();
                this._refresh();
                break;
            case "history":
                switch (o.HMUID) {
                    case "filters":
                        this._currentFilters = Object.clone(o.v);
                        this._cookie.set("filters", this._currentFilters);
                        this._needsRefresh = true;
                        this._refresh();
                        break;
                    case "order":
                        $('orderBy').set('value', o.v);
                        this._order(o.v);
                        this._refresh();
                        break;
                }
                break;
        }
    },
    initialize: function (listUID, from) {

        this._cookie = new Hash.Cookie(listUID);
        if (from == "list") {
            if (this._cookie.get("filters")) {
                this._currentFilters = this._cookie.get("filters");
                this._needsRefresh = true;
            }
            if (this._cookie.get("order")) {
                this._currentOrder = this._cookie.get("order");
                this._needsRefresh = true;
            }
        }
        this._needsRefresh = true;
        this._refresh();

        $('orderBy').addEvent('change',
            function (e) {
                this._call({ a: "order", v: $('orderBy').get('value') });

            } .bind(this));

        this._detailRequest = new Request.JSON({ "url": "/ajax/biensDetail.aspx" })
            .addEvent("error", function (t, o) { console.log(t, o) } .bind(this))
            .addEvent("complete", function (o) { this._detailsReady(o) } .bind(this));
        this._mainScroll = new Fx.Scroll($(window));

        Object.each(this._currentFilters, function (cat) {
            cat.each(function (val) {
                var link = $("filters").getElement("a[data-val='" + val + "']");
                if (!link)
                    return;
                link.addClass("active");
            });
        });

        $("selectFiltres").addEvent("click", this._toggleFilterWindow.bind(this));
        $('closeFilters').addEvent('click', this._toggleFilterWindow.bind(this));
        site.addHistoryEvent("biens", "filters");
        site.addHistoryEvent("biens", "order");
        site.addEvent("biens", function (o) { this._call(o); } .bind(this));
        this._refresh();
    },
    _toggleFilterWindow: function () {

        if (!$("filtersWarp").retrieve("isReady")) {
            $("filters")
                .position({ relativeTo: $("selectFiltres"), position: "centerBottom", edge: "centerTop" })
                .setStyle("opacity", 0)
                .addEvent("click", function (e) { e.stopPropagation() });
            $("filtersWarp").addEvent("click", this._toggleFilterWindow.bind(this));
            $("filtersWarp").store("isReady", true);
        }

        if (!$("filtersWarp").hasClass("modal")) {
            $("filtersWarp").addClass("modal");
            $("filters").fade("in");
        }
        else {
            $("filtersWarp").removeClass("modal");
            $("filters").setStyle("opacity", 0);
        }
    },
    addItems: function (objects) {
        var objectsArr = Array.from(objects);
        objects.each(function (i) {
            if (i.p || i.p == 0) {
                this._maxPricesVal.max = Math.max(this._maxPricesVal.max, i.p);
                this._maxPricesVal.min = Math.min(this._maxPricesVal.min, i.p);
            }
            if (!i.uid || !$(i.uid))
                return;

            $(i.uid)
                .getElement("div.preview").addEvent("click", this._toggle.pass(i.uid, this));
            $(i.uid)
                .getElement("div.preview a.detailLink").addEvent("click", function (e) { e.stopPropagation(); });
            $(i.uid)
                .getElement("a.leftImg").set("href", "javascript:void(0)");

            this._items.push(i);
        }, this);

        this._sliders.each(function (s) {
            s.setMaxValues({ min: this._maxPricesVal.min, max: this._maxPricesVal.max });
        }, this);


        this._filter();
        this._filterPrices();
        this._order();

        this._refresh();
    },
    addSliders: function (sliders) {
        if (((!this._maxPricesVal.min && this._maxPricesVal.min != 0) || this._maxPricesVal.min == Number.MAX_VALUE) || (!this._maxPricesVal.max && this._maxPricesVal.max != 0)) {
            return;
        }
        var sliders = Array.from(sliders);
        sliders.each(function (s) {
            s = $(s);
            this._sliders.push(
                 new slider(s.get("id"), s.getElements(".knob"), s.getElements(".knobLog .val")).addEvent("valuesChanged", function (e) { this._pricesChanged(e); } .bind(this))
                );
        }, this);
        this._sliders.each(function (s) {
            s.setMaxValues({ min: this._maxPricesVal.min, max: this._maxPricesVal.max });
        }, this);
    },
    _pricesChanged: function (e) {
        this._filterPrices(e[0].val, e[1].val);
        this._refresh();
    },
    _order: function () {
        var key = this._currentOrder;
        this._items.sort(function (a, b) {
            var aValue = a[key];
            var bValue = b[key];
            switch (key) {
                case "p":
                    aValue = aValue == null ? 0 : aValue;
                    bValue = bValue == null ? 0 : bValue;
                    break;
                case "d":
                    aValue = aValue == null ? "" : aValue.toLowerCase();
                    bValue = bValue == null ? "" : bValue.toLowerCase();
                    break;
            }

            if (aValue < bValue)
                return -1;
            if (aValue > bValue)
                return 1;
            return 0;
        });
        this._needsRefresh = true;
    },
    _toggleFilter: function (cat, val) {
        var isActive = false;
        if (this._currentFilters[cat]) {
            if (this._currentFilters[cat].contains(val)) {
                this._currentFilters[cat].erase(val);
                if (this._currentFilters[cat].length == 0) {
                    delete this._currentFilters[cat];
                }
            }
            else {
                this._currentFilters[cat].push(val);
                isActive = true;
            }
        } else {
            isActive = true;
            this._currentFilters[cat] = [val];
        }
        this._filter();
        // TRY to toggle the class of the link
        var link = $("filters").getElement("a[data-val='" + val + "']");
        if (!link)
            return;
        if (isActive)
            link.addClass("active");
        else
            link.removeClass("active");
    },
    _filter: function () {
        if (Object.keys(this._currentFilters).length == 0)
            $("selectFiltres").removeClass("active");
        else {
            $("selectFiltres").addClass("active");
        }

        this._items.each(function (ai) {
            // show if 
            ai.show =
                Object.keys(this._currentFilters).length == 0 ||
                (ai.k && Object.every(ai.k, function (vals, cat) {
                    // current filters does not have this cat or this cat contains at least one of the item criterias
                    return !this._currentFilters[cat] || vals.some(function (val) { return this._currentFilters[cat].contains(val); } .bind(this))
                } .bind(this)));
        }, this);

        this._needsRefresh = true;
    },
    _filterPrices: function (min, max) {
        this._items.each(function (ai) {
            if (!min && !max)
                ai.showPrice = true;
            else
                ai.showPrice = ai.p == undefined || (ai.p >= min) && (ai.p <= max);
        }, this);
        this._needsRefresh = true;
    },
    _refresh: function () {
        if (!this._needsRefresh)
            return;
        // filter
        this._items.each(function (i) {
            if (i.showPrice && i.show)
                $(i.uid).removeClass('hidden');
            else
                $(i.uid).addClass('hidden');
        }, this);
        // reorder
        this._items.each(function (ai) {
            var li = $(ai.uid);
            li.inject(li.getParent(), 'bottom');
        });
        this._needsRefresh = false;
    },
    _toggle: function (itemUID) {
        var li = $(itemUID);
        if (!li.retrieve("opened")) {
            li.store("opened", true);
            li.addClass("active");
            if (!li.retrieve("ready")) {
                this._detailRequest.cancel();
                this._detailRequest.post({
                    UID: itemUID
                });
                if (!li.retrieve("detail")) {
                    li.adopt(new Element("div", { "class": "detail loading" }));
                    li.store("detail", true);
                }
            }

            this._mainScroll.toElement(li);
        }
        else {
            li.store("opened", false);
            li.removeClass("active");
            this._detachImagesScroll(itemUID);

        }

    },
    _detailsReady: function (o) {
        if (!o)
            return;
        var li = $(o.uid);
        li.getElement("div.detail").removeClass("loading").set("html", o.html).setStyle("opacity", 0).fade("in");
        this._attachImagesScroll(o.uid);
        this._mainScroll.toElement(li);
        li.store("ready", true)
    },
    _attachImagesScroll: function (uid) {
        var scroller = $(uid).retrieve("imagesScroll", new Scroller($(uid).getElement("div.detail div.images"), { area: 100, fps: 20 }));
        scroller.start()
    },
    _detachImagesScroll: function (uid) {
        var scroller;
        if (scroller = $(uid).retrieve("imagesScroll"))
            scroller.stop();
    }
    //    _toggleFilterKey: function (key, v) {

    //        if (typeOf(v) == 'number' || v)
    //            this._currentFilter[key] = v;
    //        else
    //            delete this._currentFilter[key];

    //        site.HM.set("filters", this._currentFilter);

    //    }

});
