var app = angular.module('myApp', []);

app.controller('MyCtrl', function($scope, $http) {
  $scope.loadStatement = function() {
    if(!$scope.statementPath || $scope.statementPath == "") {
      return;
    }
    $http.get('/statements.json', { params: { path: $scope.statementPath } }).success(function(data) {
      $scope.statement = data.statement;
      $scope.tryIt();
    })
  }

  var loadSQL = function(statement) {
    $scope.query = null;
    var displayIt = function(formatted_data) {
      $scope.query = formatted_data.result;
    };

    $http.post('/api/v0/sql', statement).success(function(data) {
      $http( { url: 'http://sqlformat.org/api/v1/format',
            method: 'POST',
            responseType: 'JSON',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: $.param({ reindent: 1, sql: data.sql })})
                .success(displayIt)
                .error(displayIt);
    });
  };

  var loadYAML = function(statement) {
    $scope.yaml = null;
    $http.post('/to_yaml', statement).success(function(data) {
      $scope.yaml = data.yaml;
    });
  };

  var loadDiagram = function(statement) {
    $scope.img_src = null;
    $http.post('/api/v0/diagram', statement).success(function(data) {
      $scope.img_src = data.img_src;
    });
  };

  $scope.tryIt = function () {
    var statement = angular.fromJson($scope.statement)
    loadSQL($.extend(true, {}, statement));
    loadYAML($.extend(true, {}, statement));
    loadDiagram($.extend(true, {}, statement));
    $scope.statement = angular.toJson(statement, true)
  };
});

@@ -382,16 +382,97 @@
 %7D)%0A  %7D%0A%0A
+  $scope.$watch('statementPath', function() %7B%0A    $scope.loadStatement();%0A  %7D);%0A%0A
   var lo
@@ -1675,13 +1675,363 @@
 ue)%0A  %7D;
+%0A%0A  preloadSomeExample = function() %7B%0A    // Grabbed the idea for parsing a URL from:%0A    // http://jsfiddle.net/PT5BG/4/%0A    var parser, hashy;%0A    parser = document.createElement('a');%0A    parser.href = window.location;%0A%0A    var hashy;%0A    if (hashy = parser.hash) %7B%0A      $scope.statementPath = hashy.substr(1);%0A    %7D%0A  %7D;%0A%0A  preloadSomeExample();
 %0A%7D);%0A

Allow # in URL to preload an example statement