

//==============================================================================================
var subfolders_cache = {};

/**
 * Breadcrumb element - folder with optional siblings list
 */
var BreadcrumbElementModel = Backbone.Model.extend({
	siblings: null,
	defaults: {
		"id": null,
		"title": ""
	},

	loadSiblings: function (callback)
	{
		var cache_key = 'f_' + this.get('parent_id');
		if (typeof(subfolders_cache[cache_key]) === 'undefined')
		{
			this.siblings = new DocsCollection();
			this.siblings.bind('loaded', function () {
			    subfolders_cache[cache_key] = this.siblings;
			    callback();
            }, this);
			this.siblings.loadAllFolders(this.get('parent_id'));
		} else
		{
			this.siblings = subfolders_cache[cache_key];
            callback();
		}
	}
});

/**
 * Collection of folders shown in breadcrumb
 */
var BreadcrumbCollection = Backbone.Collection.extend({
	model: BreadcrumbElementModel,

	load: function (folder_id)
	{
		if (folder_id > 0)
		{
			if (!this.get(folder_id))
			{
				this.url = '/intranet/rest/documents/folder/' + folder_id + '/path';
				this.fetch({reset: 1});
			} else
			{
				var index = this.indexOf(this.get(folder_id));
				this.reset(_.first(this.models, index+1));
			}
		} else
		{
			this.reset();
		}
	}
});

var BreadcrumbView = Backbone.View.extend({
	el: $('#docsListBreadcrumb'),

	events: {
		'mouseover li.breadcrumble-node' : "onMouseOver"
	},

	initialize : function() {
	    this.breadcrumb = new BreadcrumbCollection();
	    this.breadcrumb.bind('change', function () { this.render(); }, this);
        this.breadcrumb.bind('reset', function () { this.render(); }, this);

        window.addEventListener("resize", () => {this.render();});
    },

	render: function ()
	{
		this.$("li:gt(0)").remove();
        var isMobileBreadcrumb = document.documentElement.clientWidth < 1011;
        var templateId = isMobileBreadcrumb ? '#breadcrumb_node_mobile_template' : '#breadcrumb_node_template';
		var template = _.template($(templateId).html());
		this.breadcrumb.each(function (doc, index) {
			var data = doc.toJSON();
			data.index = index;
			data.is_last = 0;

			if(this.breadcrumb.length - 1 === index)
				data.is_last = 1;

			this.$el.append(template(data));
		}, this);


		if (this.breadcrumb.length > 0)
		{
			$('#parent_folder_link').attr('href', '#list/' + this.breadcrumb.last().get('parent_id')).show();
		} else
		{
			$('#parent_folder_link').hide();
		}
	},

	load: function (folder_id)
	{
		this.breadcrumb.load(folder_id);
	},

	onMouseOver: function (event)
	{
		var obj = $(event.currentTarget);
		if (obj.attr('loaded'))
			return;

		var index = obj.attr('index');
		if (typeof(index) === 'undefined')
			return;

		var bnode = this.breadcrumb.at(index);
		if (typeof(bnode) === 'undefined')
			return;

		// if siblings are not yet loaded, load them
		if (bnode.siblings === null)
		{
            var self = this;
			bnode.loadSiblings(function () {
                self.fillDropdown(obj, bnode);
            });
		} else
		{
			this.fillDropdown(obj, bnode);
		}
	},

	fillDropdown: function (obj, bnode)
	{
		var el = $('ul', obj);
		el.empty();
		if (bnode.siblings === null)
			return;
		bnode.siblings.each(function (folder) {
			el.append('<li><a href="#list/' + folder.id +'" title="' + folder.escape('title') +'" '+ (folder.id==bnode.id ? ' class="current"' : '') +'>' + folder.escape('title') +'</a></li>');
		});

		var cur_el = $('a.current', el);
		if (cur_el.length > 0)
		{
			var scrollpos = cur_el.offset().top - el.offset().top;
			el.scrollTop(scrollpos);
		}
		obj.attr('loaded', 1);
	},

	setModel: function (docs_list_state)
	{
		docs_list_state.bind('change', function () { this.load(docs_list_state.get('folder_id')); }, this);
		this.breadcrumb = new BreadcrumbCollection();
		this.breadcrumb.bind('reset', function () { this.render(); }, this);
	}
});
