'use strict';
/**
 * Implements directive for image selector
 */
angular.module('qusion.ui.selector', [])
    .directive('qnSelector', [
        function () {
            return {
                require: '?ngModel',
                link: function (scope, element, attr, ngModel) {
                    var opts = {};
                    var settings = {
                        filter: "li",
                        multipleSeletcion: true
                    };
                    
                    opts = angular.extend({}, settings, scope.$eval(attr.qnSelector));
                    if (ngModel) {
                        ngModel.$render = function () {
                            element.selectable("refresh");
                        };

                        opts.stop = function (event, ui) {
                            var selected = element.find('.ui-selected').map(function () {
                                var idx = $(this).index();
                                return ngModel.$modelValue[idx];
                            }).get();
                            scope.selectedItems = selected;
                            scope.$apply(scope.selectedItems);
                        };
                        opts.selected = function (event, ui) {
                            if (opts.multipleSeletcion == false) {
                                $(ui.selected).addClass("ui-selected").siblings().removeClass("ui-selected");
                            }
                        };
                    }
                     element.selectable(opts);
                }

            };
        }
    ]);