'use strict';

angular.module('arethusaTranslateGuiApp').directive('trslValue', [
  function() {
    var DIRTY = 'dirty-bg';
    var CLEAN = 'clean-bg';
    var TRSL_CHANGE = 'trslChange';
    var VALUE_CHANGE = 'valueChange';

    return {
      restrict: 'A',
      link: function(scope) {
        function switchClassAndNotify(newVal, oldVal) {
          scope.statusClass = newVal ? DIRTY : CLEAN;
          if (newVal !== oldVal) scope.$emit(VALUE_CHANGE);
        }

        function isClean() {
          return scope.allClean(scope.value, 'translations');
        }

        function checkDirtyness() {
          scope.value.dirty = !isClean();
        }

        function changeAllStatus(bool) {
          var trsls = scope.value.translations;
          for (var i = trsls.length - 1; i >= 0; i--){
            var trsl = trsls[i];
            trsl.dirty = bool;
          }
          scope.$emit(TRSL_CHANGE);
        }

        scope.$watch('value.dirty', switchClassAndNotify);

        scope.$watch('value.name', function(newVal, oldVal) {
          if (!oldVal) checkDirtyness();
          if (!newVal) scope.value.dirty = true;
        });

        scope.$on('mainChange', function() {
          scope.value.dirty = true;
          scope.$broadcast('mainDirty');
          scope.deferredUpdate();
        });

        scope.$on(TRSL_CHANGE, checkDirtyness);

        scope.setDirty = function() {
          changeAllStatus(true);
        };

        scope.setClean = function() {
          changeAllStatus(false);
        };

        scope.remove = function() {
          scope.removeHelper(scope.container.values, scope.value, function() {
            scope.$emit(VALUE_CHANGE);
            scope.immediateUpdate();
          });
        };
      },
      templateUrl: 'app/i18n/trsl_value.directive.html'
    };
  }
]);



@@ -916,32 +916,618 @@
 GE);%0A        %7D%0A%0A
+        function addMissingTranslations() %7B%0A          var langs = scope.languages;%0A          var trsls = scope.value.translations;%0A          if (langs.length !== trsls.length) %7B%0A            var missing = angular.copy(langs);%0A            for (var i = trsls.length - 1; i %3E= 0; i--)%7B%0A              var idx = missing.indexOf(trsls%5Bi%5D.lang);%0A              missing.splice(idx, 1);%0A            %7D%0A            for (var id = missing.length - 1; id %3E= 0; id--)%7B%0A              trsls.push(scope.newTranslation(missing%5Bid%5D));%0A            %7D%0A            scope.deferredUpdate();%0A          %7D%0A        %7D%0A%0A
         scope.$w
@@ -2335,16 +2335,51 @@
       %7D;
+%0A%0A        addMissingTranslations();
 %0A      %7D

Add languages when translation objects are missing