(function () {
    global.dashModule
        .directive('datepicker', ['$timeout', '$', datepickerDirective]);

    function datepickerDirective($timeout, $) {
        return {
            restrict: 'A',
            require: 'ngModel',
            scope: {
                onDateSelected: '=',
                elementData: '='
            },
            transclude: true,
            link: function ($scope, $element, $attrs, ngModelCtrl) {
                $timeout(function () {
                    $($element).datepicker({
                        dateFormat: 'yy-mm-dd',
                        showButtonPanel: true,
                        changeYear: true,
                        onSelect: function (date) {
                            ngModelCtrl.$setViewValue(date);
                            $scope.$apply();
                        },
                        onClose: function (date) {
                            if(typeof $scope.onDateSelected !== 'undefined' && date){
                                $scope.onDateSelected(date, $scope.elementData);
                            }
                        }
                    });
                });
            }
        };
    }
})();
