'use strict';
/**
*
*/
angular.module('qusion.ui.colorpicker', [])
    .directive('qnColorpicker', ['$timeout',
        function($timeout) {
            return {
                require: '?ngModel',
               
                link: function(scope, element, attr, controller) {
                    var settings = { };

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

                        if (controller) {
                            options.onColorChange = function(id, val) {
                                element.blur();
                                scope.$apply(function() {
                                    controller.$setViewValue(element.val());
                                });
                            };

                            // Update the color picker when the model changes
                            controller.$render = function() {
                                var color = controller.$viewValue;
                                element.val(color);
                                element.change();
                            };
                        }
                        
                        element.colorPicker(options);
                        // If we don't destroy the old one it doesn't update properly when the config changes
                        // element.colorPicker('destroy');
                        // Create the new colorpicker widget
                    };
                    
                    // Watch for changes to the directives options
                    scope.$watch(getOptions, init, true);
                }
            };
        }
    ]);