﻿(function() {

	var o = {

		init: function(control, field) {
			EMOTIFY.log('sf init');

			var p, f;
			p = $('#' + control + "_up");
			f = $('#' + field);

			p.data('fieldID', field);
			p.data('controlID', control);
			p.click(o.toggleSelect);

		},

		toggleSelect: function(e) {

			var p, t;
			t = $(e.target);

			if (!t.hasClass('item')) {
				t = t.parents('.item:first');
			}

			if (t.hasClass('selected')) {
				t.removeClass('selected');
			} else {
				t.addClass('selected');
			}

			o.updateValues.call(this);


		},



		updateValues: function() {
			EMOTIFY.log(this);
			var selects, t, newVal = [];
			t = $(this);
			selects = t.find('.selected');


			for (var i = 0; i < selects.length; i++) {
				newVal.push($(selects[i]).attr('id').replace(t.data('controlID') + '_', ''));


			}

			EMOTIFY.log(newVal);

			$('#' + t.data('fieldID')).val(newVal.join(','));


		}






	};


	EMOTIFY.namespace('ui.selectfriends');
	EMOTIFY.ui.selectfriends = o;

})();