/*
 * Copyright (c) 2013, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

jQuery(function($) {
	$.fn.superSelect = function(supers) {
		/*$(this).delegate('select', 'change', function(event) {
			var selected = $(this).val(), i = 0, e = 0;
			if(!selected || !selected.length) return true;
			for(; i < selected.length; i++) {
				if(minors[selected[i]]) {
					for(; e < minors[selected[i]].length; e++) {
						$('option[value=' + minors[selected[i]][e] + ']', this).attr('selected', 'selected');
					}
				}
			}
		});*/

		var minors = {};

		for (var i in supers) {
			for (var e = 0; e < supers[i].length; e++) {
				if (!minors[supers[i][e]]) minors[supers[i][e]] = [];
				minors[supers[i][e]].push(i);
			}
		}

		$(this).delegate('input', 'change', function() {
			var entity = $(this).closest('.sly-select-checkbox-list'), checkboxes = entity.find('input'), i = 0, e, selected, s;
			selected = checkboxes.filter(':checked');

			if (!selected || !selected.length) {
				return true;
			}

			for (; i < selected.length; i++) {
				s = $(selected[i]).val();

				if (minors[s]) {
					for (e = 0; e < minors[s].length; e++) {
						$('input[value="' + minors[s][e] + '"]', entity).attr('checked', 'checked');
					}
				}
			}
		});
	};
});
