/**
 * Collection of bookmarked documents and folders. Synchronized with the server.
 *
 * A single global object is created for it. Documents lists and models watch for changes in this global collection
 * and modify their state accordingly.
 */
var BookmarksCollection = Backbone.Collection.extend({
	model: BookmarkModel,
	urlBase: '/intranet/rest/documents/bookmark/',

	load: function ()
	{
		this.url = this.urlBase + '?full=1';
		this.fetch();
		this.url = this.urlBase;
	},

	isBookmarked: function (obj_type, obj_id)
	{
		var res = this.find(function (bm) { return bm.isBookmarked(obj_type, obj_id); } );
		return res ? true : false;
	},

	addBookmarkUI: function (obj_type, obj_id, comment, category_id)
	{
		this.addBookmark(obj_type, obj_id, comment, category_id);
		// docsShowMessage('Bookmark added', 'success', 3);
	},

	addBookmark: function (obj_type, obj_id, comment, category_id)
	{
		if (this.isBookmarked(obj_type, obj_id))
			return;
		var bookmark = new BookmarkModel({
			'obj_type': obj_type,
			'obj_id': obj_id, // obj_id for documents here is doc_id
			'comment': comment,
			'object': views_manager.getActiveView().collection.getDocObject(obj_type, obj_id),
			'category': category_id
		});

		bookmark = this.add(bookmark);
		bookmark.save();
	},
	
	comparator: function(model) {
		title = '';
		obj = model.getDocument();
		
		if ((typeof(obj) === 'object') &&
				(obj !== null))
		{
			title = obj.get('title');
			
			if (typeof(title) == 'undefined')
				title = obj.get('pc_title');
		}
		
		if (typeof(title) !== 'undefined')
	    	title = title.toLowerCase();

	    return title;
	},

	removeBookmarkUI: function (obj_type, obj_id, comment, category_id)
	{
		this.removeBookmark(obj_type, obj_id, comment, category_id);
		// docsShowMessage('Bookmark removed', 'success', 3);
	},

	removeBookmark: function (obj_type, obj_id)
	{
		var bookmark = this.find(function (bm) { return bm.isBookmarked(obj_type, obj_id); });
		if (bookmark)
		{
			bookmark.destroy();
			this.remove(bookmark);
		}
	},

	getDocObject: function (obj_type, obj_id)
	{
		var bm = this.find(function (bm) { return bm.isBookmarked(obj_type, obj_id); } );
		if (!bm)
			return null;
		// bm.loadFull();
		return bm.getDocument();
	}

});
