(function () {
	'use strict';

	// INTERNAL VARIABLES

	var _ = {
		$list: null,
	};

	// METHODS

	function createItems() {
		var i = 0;
		var list = '';

		// build the html items as a string
		for (i; i < 10; i += 1) {
			list += '<li class="list-group-item" data-index="' + i +
				'" data-click-count="0"><span class="index">#' + (i + 1) +
				'</span> <span class="list-label">Click me.</span></li>';
		}

		// convert string to html and add to list
		_.$list.html($(list));
	}

	function updateItem($item) {
		// calculate new click count
		var clickCount = Number($item.data('click-count')) + 1;
		// update label
		var label = 'Clicked ' + clickCount + (clickCount === 1 ? ' time.' : ' times.');
		// apply label to item
		$item.data('click-count', clickCount).find('.list-label').text(label);
	}

	function sortItems() {
		var $items = _.$list.find('li');

		$items.sort(function (a, b) {
			if ($(b).data('click-count') > $(a).data('click-count')){
				return 1;
			} else if ($(b).data('click-count') < $(a).data('click-count')){
				return -1;
			}
			return 0;
		}).appendTo(_.$list); // replace all items with newly-sorted items (easy but not efficient)
	}

	// INIT

	$(document).ready(function () {
		// make a persistent reference to the list's parent element
		_.$list = $('#click-list');
		// start
		createItems();

		// EVENT LISTENERS
		_.$list.on('click', 'li', function () {
			updateItem($(this));
			sortItems();

			// bootstrap has an "active" state for list groups
			//$(this).addClass('active').siblings().removeClass('active');
		})
	})
})()