var $ = global.jQuery
var UserBookmarks = function() {
	var priv = {}; //private api
	var publ = {}; //public api

	priv.options = {};
	var defaults = {
		url: '',	//webservice url
		store: null, // @required
		debug: false
	};

	var _cont; // container holding table
	var _stateEdit = false;

	/*
	 initialize the plugin.
	 */
	priv.init = function() {
		_cont = $(priv.options.id);

		priv.options.store.subscribe(
			(function (global, priv) {
				return function renderUserBookmarks(data) {
					priv.setData(data.bookmarks)
				}
			})(global, priv)
		)

		_cont.sortable();
		_cont.on('sortupdate', priv.sort);
	};

	priv.setData = function(data) {
		_cont.empty();
		data.forEach(function(item) {
			if (!item) return;
			if ('type' in item) {
				var l = $('<a></a>');
				l.data('id', item.id);
				l.addClass('btn');
				l.addClass('btn-xs');
				var label = item.name, title = '';
				if (item.hasOwnProperty('class') && item['class'] != '') {
					l.addClass(item.class);
				} else {
					l.addClass('btn-default');
				}
				if (item.type == 'menu') {
					// l.attr('href', 'index.php?_route=ViewTableAjax&typeName=' + 'p5_default_db:' + item.name);
					l.attr('href', 'index.php?_route=ViewTableAjax&namespace=' + item.namespace);
					if ('label' in item && item.label.length > 0) {
						label = item.label;
						title = item.label + ' (' + item.name + ')';
					}
					else if ('opis' in item && item.opis.length > 0) {
						label = item.opis;
						title = item.opis + ' (' + item.name + ')';
					}
				} else if (item.type == 'url') {
					l.attr('href', 'index.php?FUNCTION_INIT=URL_INIT&ZASOB_ID=' + item.id);
					l.attr('target', '_blank');
				}
				if (label.length > 20) {
					var pos = label.indexOf(' - ');
					if (pos > 20 || pos < 5) {
						pos = 20;
						l.text(label.substring(0, pos) + ' ...');
					} else {
						l.text(label.substring(0, pos));
					}
				} else {
					l.text(label);
				}
				if (title == '') title = label;
				l.attr('title', title);
				l.appendTo(_cont);

				if (_stateEdit) {
					priv.addEditBtns(l);
				}
			}
		});

		if (data.length > 0) {
			var editBtn = $('<button class="btn btn-xs" style="float:right" title="Edit Bookmarks"><i class="glyphicon glyphicon-cog"></i></button>')
			editBtn.on('click', priv.edit);
			editBtn.prependTo(_cont);
		}
	};

	priv.changed = function(e) {
		global.p5UI__MenuStore.remoteUpdate({
			'_postTask': 'changeBookmark',
			'_zasobID': e.data.id,
			btnCls: e.data.cls
		})
		return false;
	};

	priv.removed = function(e) {
		global.p5UI__MenuStore.remoteUpdate({
			'_postTask': 'removeBookmark',
			'_zasobID': e.data.id,
		})
		return false;
	};

	priv.sort = function(e, ui) {
		var idsOrder = _cont.find('a').map(function(ind, n){
			return $(n).data('id');
		});
		global.p5UI__MenuStore.remoteUpdate({
			'_postTask': 'sortBookmarks',
			'_zasobID': 0,
			ids: idsOrder,
		})
		return true;
	};

	priv.addEditBtns = function(el) {
		var next, btn;
		el.wrap('<div></div>');
		next = $('<span><em> Change color:</em> </span>');
		$.each(['btn-default', 'btn-primary', 'btn-info', 'btn-success', 'btn-warning', 'btn-danger'], function(btnInd, btnClass){
			btn = $('<button class="btn btn-xs ' + btnClass + '"> &nbsp; </button>');
			btn.on('click', {id: el.data('id'), cls: btnClass}, priv.changed);
			btn.appendTo(next);
		});

		btn = $('<button class="btn btn-xs"> remove </button>');
		btn.on('click', {id: el.data('id')}, priv.removed);
		btn.appendTo(next);

		next.insertAfter(el);
	};

	priv.edit = function(e) {
		_stateEdit = !_stateEdit;
		var el;
		_cont.find('a').each(function(ind, n){
			if (priv.options.debug) console.log(n);
			el = $(n);
			if (_stateEdit) {
				priv.addEditBtns(el);
			} else {
				el.next().remove();
				el.unwrap();
			}
		});
	}

	publ.init = function(options) {
		if (priv.options.debug) console.log('UserBookmarks initialization...');
		//merge supplied options with defaults
		$.extend(priv.options, defaults, options);
		priv.init();
		return publ;
	};
	return publ;
};

$.fn.UserBookmarks = function(options) {
	options = options || {};
	return this.each(function() {
		options.id = this;
		$(this).data('UserBookmarks', new UserBookmarks().init(options));
	});
};
