angular.module("app").directive("sqSlider", function ($rootScope, $timeout, BackendService, SQEvents, SQConstants) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/sqSlider/sqSlider.html",
        scope: {
            sqModel: '=',
            min: '@',
            max: '@',
            step: '@',
            postfix: '@',
            valueAlign: '@',
            width: '@?',
            changed: '='
        },
        link: function (scope, elem, attrs) {

            $slider = $(elem).find('input').jRange({
                from: scope.min,
                to: scope.max,
                step: scope.step,
                format: '%s',
                showLabels: false,
                showScale: false,
                snap: true,
                width: scope.width,
                onstatechange: function (sliderVal) {
                    scope.value = sliderVal;
                    
                    if(!timerRunning) {      //debouncing
                        timerRunning = true;

                        $timeout(function(){
                            scope.$evalAsync();
                            timerRunning = false;
                            scope.sqModel = sliderVal;

                            if(scope.changed) scope.changed();
                        }, 50, false);
                    }
                },
                ondragend: function (sliderVal) {
                    if(scope.changed) scope.changed();

                    scope.value = sliderVal;
                    scope.$evalAsync();
                }
            });

            scope.$watch('sqModel', function (newVal) {
                if (newVal > scope.max) {
                    return;
                }

                if (newVal != undefined && newVal != null) {
                    scope.value = newVal;
                    $(elem).find('input').jRange('setValue', newVal);
                }
            });

            scope.alignTypes = {
                left: 'left',
                right: 'right'
            }

            scope.width = angular.isDefined(scope.width) ? scope.width : '300';
            scope.value = scope.sqModel;
            scope.postfix = scope.postfix || '';
            scope.valueAlign = scope.valueAlign || scope.alignTypes.left;

            var timerRunning = false;

        }
    };
});