/// class PD.Manage.Modules.Resources.LocationBar
// using PD.Web.UI.Controls.Control

PD.Manage.Modules.Resources.LocationBar =
PD.Web.UI.Controls.Control.extend({

    //===================================
    // FIELDS
    //===================================

    _history: null,
    _overflowMenu: null,
    _path: null,

    //===================================
    // PROPERTIES
    //===================================
    
    get_nextButton: function () {
        return this.get_node().find(".resource-location-bar-next");
    },

    get_prevButton: function () {
        return this.get_node().find(".resource-location-bar-prev");
    },

    get_rootButton: function () {
        return this.get_node().find(".resource-location-bar-root");
    },

    get_pathNode: function () {
        return this.get_node().find(".resource-location-bar-path");
    },

    //===================================
    // EVENT HANDLERS
    //===================================

    onInit: function (e) {

        var that = this;

        this._history = new PD.Manage.Modules.Resources.History({
            add: function (e) {
                that._enableButton(that.get_prevButton(), e.canMovePrev);
                that._enableButton(that.get_nextButton(), e.canMoveNext);
            },
            move: function (e) {
                that._enableButton(that.get_prevButton(), e.canMovePrev);
                that._enableButton(that.get_nextButton(), e.canMoveNext);
                that._publishLocationChangeEvent(e.item, false);
            }
        });

        this.subscriptions.add("location/changed", _.bind(this._change, this));
        this.subscriptions.add("location/change", _.bind(this._showLocationChangeState, this));

    },

    onActivate: function () {
        this.get_pathNode().on("click", ".location-bar-item:not(:last-child)", _.bind(this._item_onClick, this));
        this.get_prevButton().on("click", _.bind(this._historyMovePrev, this));
        this.get_nextButton().on("click", _.bind(this._historyMoveNext, this));
        this._addOverflowMenu();
    },

    _item_onClick: function (e) {

        var $item = $(e.currentTarget),
            item = $item.data("item");

        this._publishLocationChangeEvent(item.id);

    },

    _overflow_onSelect: function (e) {

        var id = $(e.item).find(".-pd-menu-item").data("id");

        this._publishLocationChangeEvent(id);

    },

    //===================================
    // PUBLIC METHODS
    //===================================

    resize: function () {
        this._resize();
    },

    getPath: function () {

        var result = null;

        if (_.isArray(this._path)) {
            result = "";
            _.each(this._path, function (item) {
                result += "/" + item.name;
            });
        }
        return result;
    },

    //===================================
    // PROTECTED METHODS
    //===================================

    template: function () {
        return [
            "<div class='resource-location-bar'>",
                "<div class='resource-location-bar-prev' disabled></div>",
                "<div class='resource-location-bar-next' disabled></div>",
                "<div class='resource-location-bar-box'>",
                    "<div class='resource-location-bar-root'>",
                        "<div></div>",
                        "<div></div>",
                    "</div>",
                    "<div class='resource-location-bar-path'></div>",
                "</div>",
            "</div>",
        ];
    },

    //===================================
    // PRIVATE METHODS
    //===================================

    _change: function (e) {
        this._path = e.data;
        this._renderPath(this._path);
        if (e.record !== false) {
            this._history.add(e.folderId);
        }
    },

    _renderPath: function (path) {

        var $path = this.get_pathNode(),
            $item = null;

        this.get_pathNode().removeClass("-pd-state-loading");

        _.each(path, function (part) {
            $item = $("<span class='location-bar-item' data-id='" + part.id + "'>" + part.name + "</span>");
            $item.data("item", part);
            $path.append($item);
        });

        this._resize();

    },

    _resize: function () {

        var $path = this.get_pathNode(),
            $pathWidth = $path.outerWidth() - 56,
            $nodeReversedChildren = $($path.children().get().reverse()),
            hiddenItems = [],
            totalWidth = 0,
            totalHidden = 0;

        $nodeReversedChildren.hide();
        $nodeReversedChildren.each(function (index, element) {

            var $element = $(element),
                dataItem = $element.data("item");

            totalWidth += $element.outerWidth();

            if (totalWidth <= $pathWidth) {
                $element.show();
            }
            else {
                if (dataItem != null) {
                    hiddenItems[hiddenItems.length] = dataItem;
                }
            }

        });

        this.get_rootButton().removeClass("-pd-state-toggled");

        this._clearOverflowMenuItems();

        if (hiddenItems.length > 0) {
            this.get_rootButton().addClass("-pd-state-toggled");
            this._addOverflowMenu(hiddenItems);
        }

    },

    _clearOverflowMenuItems: function () {
        
        var that = this;

        if (this._overflowMenu != null) {
            this._overflowMenu.element.children("UL > LI").each(function (index, element) {
                that._overflowMenu.remove(element);
            });
        }

    },

    _addOverflowMenu: function (items) {

        var that = this;

        if (this._overflowMenu == null) {

            this._overflowMenu = $("<ul></ul>").kendoContextMenu({
                alignToAnchor: true,
                target: this.get_rootButton(),
                showOn: "click",
                select: _.bind(this._overflow_onSelect, this)
            }).data("kendoContextMenu");

        }

        this._clearOverflowMenuItems();

        items = _.map(items, function (item) {
            return {
                text: item.name,
                id: item.id
            }
        });

        items = this._applyItemTemplate(items);

        _.each(items, function (item) {
            that._overflowMenu.append(item);
        });

    },

    _applyItemTemplate: function (items) {

        var imageUrl = PD.Path.resolve("~/application/icons/16x16/folder.png");
        
        _.each(items, function (e) {

            e.encoded = false;

            e.text = [
                "<span data-id='" + e.id + "' class='-pd-menu-item'>",
                    "<span class='-pd-menu-icon'>",
                        "<img src='" + imageUrl + "'>",
                    "</span>",
                    "<span class='-pd-menu-text'>",
                        e.text,
                    "</span>",
                "</span>"
            ].join("");

        });

        return items;

    },

    _clearPathNodes: function () {
        this.get_node().find(".location-bar-item").remove();
    },

    _historyMovePrev: function () {
        this._history.prev();
    },

    _historyMoveNext: function () {
        this._history.next();
    },

    _publishLocationChangeEvent: function (id, record) {

        PD.context
            .get_default()
            .get_events()
            .publish("location/change", {
                folderId: id,
                source: "location",
                record: record
            });

    },

    _showLocationChangeState: function () {
        this.get_pathNode().empty();
        this.get_pathNode().addClass("-pd-state-loading");
    },

    _enableButton: function ($button, enable) {

        if (enable) {
            $button.removeAttr("disabled");
        }
        else {
            $button.attr("disabled", "");
        }
        
    }

});