'use strict';
/**
 * Implements directive for slider JQueryUI component. 
 * Slider component: http://jqueryui.com/sloder/
 */
angular.module('qusion.ui.slider', [])
    .directive('qnSlider', [
        function() {
            return {
                require: '?ngModel',
                link: function(scope, element, attr, controller) {
                    var settings = {
                        range: "min"
                    };

                    var getOptions = function() {
                        return angular.extend({ }, settings, scope.$eval(attr.qnSlider));
                    };

                    var init = function() {
                        var options = getOptions();

                        if (controller) {
                            var updateModel = function() {
                                if (!scope.$$phase) {
                                    scope.$apply(function() {
                                        var value = element.slider("value");
                                        controller.$setViewValue(value);
                                    });
                                }
                            };

                            // update model on slider change
                            element.on('slidechange slide', function() {
                                updateModel();
                            });

                            // Update the values when model changes
                            controller.$render = function() {
                                if (angular.isArray(controller.$viewValue))
                                    element.slider("values", controller.$viewValue);
                                else
                                    element.slider("value", controller.$viewValue);
                            };
                        }

                        // If we don't destroy the old one it doesn't update properly when the config changes
                        //element.slider('destroy');
                        // Create the new datepicker widget
                        element.slider(options);

                        if (controller) {
                            // Force a render to override whatever is in the input text box
                            controller.$render();
                        }
                    };

                    // Watch for changes to the directives options
                    scope.$watch(getOptions, init, true);

                }
            };
        }
    ]);