'use strict';
/**
 * Implements directive for progressbar jqueryUI component. 
 * Progressbar component: http://jqueryui.com/progressbar/
 */
angular.module('qusion.ui.progressbar', [])
    .directive('qnProgressbar', [
        function() {
            return {
                require: '?ngModel',
                link: function(scope, element, attr, controller) {
                    // settings to be aplied on widget
                    var settings = {
                                                                                                                                                
                    };
                    // gets options/settings
                    var getOptions = function() {
                        return angular.extend({ }, settings, scope.$eval(attr.qnProgressbar));
                    };

                    // initializes widget
                    var init = function() {
                        var options = getOptions();
                        if (controller) {
                            // updates model
                            var updateModel = function() {
                                if (!scope.$$phase) {
                                    scope.$apply(function() {
                                        var value = element.progressbar("value");
                                        controller.$setViewValue(value);
                                        element.progressbar("value", controller.$viewValue);
                                    });
                                }
                            };

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

                            // Update the values when model changes
                            controller.$render = function() {
                                element.progressbar("value", controller.$viewValue);
                            };
                        }

                        element.progressbar(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);
                }
            };
        }
    ]);