angular.module('app.language', [
  'ui.router',
  'firebase'
])

.directive('language', function() {
  return {
    restrict: 'E', //E = element, A = attribute, C = class, M = comment
    scope: {
      //@ reads the attribute value, = provides two-way binding, & works with functions
      title: '@'
    },
    templateUrl: "language/language.tpl.html",
    controller: 'LanguageCtrl' //Embed a custom controller in the directive
  };
})

.controller('LanguageCtrl', function LanguageController($scope, session, LanguageRepository) {

  LanguageRepository.getLanguages().then(function(languages) {
    $scope.languages = languages;
  });

  $scope.editing = false;
  $scope.language = session.language;

  if (! $scope.language) {
    $scope.language = { name: '' };
  }

  $scope.$watch('language.name', function () {
    if (! _.isEmpty( $scope.language.name ) ) {
      LanguageRepository.getLanguage($scope.language.name)
      .then(function(language) {
        $scope.language = language;
      });
    }
    // Todo Initialize session.language from repository
    // now that we know the language we are dealing with
  });

  $scope.submit = function() {
    session.setLanguage($scope.language);
    $scope.editing = false;
  };

})

;


@@ -530,16 +530,165 @@
 ory) %7B%0A%0A
+  var getLanguage = function (session) %7B%0A    var lang = session.language;%0A    if (! lang ) %7B%0A      lang = %7B name: '' %7D;%0A    %7D%0A    return lang;%0A  %7D;%0A%0A
   Langua
@@ -796,93 +796,41 @@
 ope.
-editing = false;%0A  $scope.language = session.language;%0A%0A  if (! $scope.language) %7B%0A  
+language = getLanguage(session);%0A
   $s
@@ -838,36 +838,24 @@
 ope.
-language = %7B name: '' %7D;%0A  %7D
+editing = false;
 %0A%0A  
@@ -1095,121 +1095,8 @@
   %7D%0A
-    // Todo Initialize session.language from repository%0A    // now that we know the language we are dealing with%0A
   %7D)

Refactor for clarity