<commit_before>/*
This file is part of SOS Pomoc application.

SOS Pomoc application is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

SOS Pomoc application is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with SOS Pomoc application.  If not, see
<http://www.gnu.org/licenses/>.
*/

'use strict';

angular.module('sosPomocApp')
  .controller('AdFormCtrl', function ($scope, Ad, adsService) {

   $scope.findMe = function() {
        if ($scope.geolocationAvailable) {
            return navigator.geolocation.getCurrentPosition(function(position) {
                return $scope.$apply(function() {
                    return $scope.newItem.location = {
                        lat: position.coords.latitude,
                        lon: position.coords.longitude
                    };
                });
            }, function() {});
        }
    };

    $scope.initAutocomplete = function() {
        var autocomplete, input;
        input = document.getElementById('newLocation');
        autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addDomListener(input, 'keydown', function(e) {
            if (e.keyCode === 13) {
                return e.preventDefault();
            }
        });
        return google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place;
            place = autocomplete.getPlace();
            if (!place.geometry) {
                return;
            }
            if (place.geometry.location) {
                return $scope.$apply(function() {
                    return $scope.newItem.location = {
                        lat: place.geometry.location.jb,
                        lon: place.geometry.location.kb,
                        name: document.getElementById('newLocation').value
                    };
                });
            }
        });
    };

    $scope.init = function() {
        $scope.errors = []
        $scope.formSent = false
        $scope.newItem = {}
        $scope.asked = false
        $scope.showForm = false
        $scope.allCategories = adsService.categories.map(function(category) {
            category.checked = false;
            return category;
        });
        $scope.newItem.categories = angular.copy($scope.allCategories);
        $scope.initAutocomplete()
    }

    $scope.$watch('showForm', function() {
        if($scope.showForm && !$scope.newItem.location) {
            $scope.geolocationAvailable = navigator.geolocation ? true : false
            $scope.asked = true
            $scope.findMe()
        }
    });

    $scope.submit = function() {
        if(!$scope.createForm.$invalid) {
            $scope.errors = []
            if(!$scope.newItem.location) {
                $scope.errors.push({param: 'location', msg: "Lokalita je povinná položka."});
            }
            else {
                $scope.newItem.categories = $scope.newItem.categories.filter(function (el, idx, arr) { return el.checked == true; })
                Ad.create($scope.newItem, (function(data){
                    if(data.errors) {
                        $scope.errors.push("Odeslání se nezdařilo")
                    }
                    else {
                        $scope.errors = [];
                        $scope.formSent = true;
                        $scope.newItem = {}
                        $scope.newItem.categories = $scope.allCategories
                    }
                }))
            }
        }
    }

    $scope.toggleCategory = function(index) {
        $scope.newItem.categories[index].checked = !$scope.newItem.categories[index].checked
    }

    $scope.open = function() {
      $scope.showForm = true;
    };

    $scope.close = function() {
      $scope.showForm = false;
    };

    $scope.init();

  });
<commit_msg>AdFromCtrl reformatted<commit_after>/*
This file is part of SOS Pomoc application.

SOS Pomoc application is free software: you can redistribute it and/or
modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

SOS Pomoc application is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with SOS Pomoc application.  If not, see
<http://www.gnu.org/licenses/>.
*/

'use strict';

angular.module('sosPomocApp')
  .controller('AdFormCtrl', function ($scope, Ad, adsService) {

    $scope.findMe = function() {
      if ($scope.geolocationAvailable) {
        return navigator.geolocation.getCurrentPosition(function(position) {
          return $scope.$apply(function() {
            return $scope.newItem.location = {
              lat: position.coords.latitude,
              lon: position.coords.longitude
            };
          });
        }, function() {});
      }
    };

    $scope.initAutocomplete = function() {
      var autocomplete, input;
      input = document.getElementById('newLocation');
      autocomplete = new google.maps.places.Autocomplete(input);
      google.maps.event.addDomListener(input, 'keydown', function(e) {
        if (e.keyCode === 13) {
          return e.preventDefault();
        }
      });
      return google.maps.event.addListener(autocomplete, 'place_changed', function() {
        var place;
        place = autocomplete.getPlace();
        if (!place.geometry) {
          return;
        }
        if (place.geometry.location) {
          return $scope.$apply(function() {
            return $scope.newItem.location = {
              lat: place.geometry.location.jb,
              lon: place.geometry.location.kb,
              name: document.getElementById('newLocation').value
            };
          });
        }
      });
    };

    $scope.init = function() {
      $scope.errors = []
      $scope.formSent = false
      $scope.newItem = {}
      $scope.asked = false
      $scope.showForm = false
      $scope.allCategories = adsService.categories.map(function(category) {
        category.checked = false;
        return category;
      });
      $scope.newItem.categories = angular.copy($scope.allCategories);
      $scope.initAutocomplete()
    }

    $scope.$watch('showForm', function() {
      if($scope.showForm && !$scope.newItem.location) {
        $scope.geolocationAvailable = navigator.geolocation ? true : false
        $scope.asked = true
        $scope.findMe()
      }
    });

    $scope.submit = function() {
      if(!$scope.createForm.$invalid) {
        $scope.errors = []
        if(!$scope.newItem.location) {
          $scope.errors.push({param: 'location', msg: "Lokalita je povinná položka."});
        }
        else {
          $scope.newItem.categories = $scope.newItem.categories.filter(function (el, idx, arr) { return el.checked == true; })
          Ad.create($scope.newItem, (function(data){
            if(data.errors) {
              $scope.errors.push("Odeslání se nezdařilo")
            }
            else {
              $scope.errors = [];
              $scope.formSent = true;
              $scope.newItem = {}
              $scope.newItem.categories = $scope.allCategories
            }
          }))
        }
      }
    }

    $scope.toggleCategory = function(index) {
      $scope.newItem.categories[index].checked = !$scope.newItem.categories[index].checked
    }

    $scope.open = function() {
      $scope.showForm = true;
    };

    $scope.close = function() {
      $scope.showForm = false;
    };

    $scope.init();

  });
<|endoftext|>


<commit_before>'use strict';

function DataPoint (date, prescription, dosage, tLevel, eLevel, logEntry){
  this.date = date;
  this.prescription = prescription;
  this.dosage = dosage;
  this.tLevel = tLevel;
  this.eLevel = eLevel;
  this.logEntry = logEntry;
};

DataPoints.allData = [];

DataPoint.prototype.toHtml = function (){
   //manipulate template strings here so that the dom renders them to #log section

};

$('#submit-button').on('click', function(e){
  e.preventDefault();
  var obj = new DataPoint($('#date').val(), $('#prescription').val(), parseInt($('#dosage').val()), parseInt($('#tLevel').val()), parseInt($('#eLevel').val()), $('#entry-form').val());
  DataPoints.allData.push(obj);
  localStorage.dataPoints = DataPoints.allData;
  $.post('/submit', obj).then(console.log('post complete')).catch(console.error);
});
<commit_msg>fixed console error<commit_after>'use strict';

function DataPoint (date, prescription, dosage, tLevel, eLevel, logEntry){
  this.date = date;
  this.prescription = prescription;
  this.dosage = dosage;
  this.tLevel = tLevel;
  this.eLevel = eLevel;
  this.logEntry = logEntry;
};

DataPoint.allData = [];

DataPoint.prototype.toHtml = function (){
   //manipulate template strings here so that the dom renders them to #log section

};

$('#submit-button').on('click', function(e){
  e.preventDefault();
  var obj = new DataPoint($('#date').val(), $('#prescription').val(), parseInt($('#dosage').val()), parseInt($('#tLevel').val()), parseInt($('#eLevel').val()), $('#entry-form').val());
  DataPoint.allData.push(obj);
  localStorage.dataPoints = DataPoints.allData;
  $.post('/submit', obj).then(console.log('post complete')).catch(console.error);
});
<|endoftext|>


<commit_before>function LWJSTE(){
    this.templates = {};
    arguments.callee.escape_character = "#";
    arguments.callee.IF = 0;
    arguments.callee.EACH = 1;
    arguments.callee.SWITCH = 2;
    arguments.callee.LITERAL = 3;
    arguments.callee.VARIABLE = 4;
}
LWJSTE.prototype = {
    _parseTemplate : function(str){
        var LITERAL = 0, EACH = 1, IF = 2, ELIF = 3, ELSE = 4, ID = 5, SWITCH = 6, CASE = 7, LITERAL = 8, L_CB = 9, R_CB = 10, EACH_END = 12, IF_END = 13, SWITCH_END = 14, DEFAULT = 11;
        var tokens = [];
        //lexer
        var token = "";
        var literal = true;
        var last_is_escape = false;
        var pushed = false;
        function success(result){
            return [0, result];
        }
        function faild(result){
            return [1, result];
        }
        function push(type, lexeme){
            if(lexeme.length != 0){
                tokens.push([type, lexeme]);
                token = "";
            }
        }
        function push_reserved_word(token){
            switch(token.toLowerCase()){
                case "if": push(IF, token); break;
                case "elif": push(ELIF, token); break;
                case "else": push(ELSE, token); break;
                case "/if": push(IF_END, token); break;
                case "each": push(EACH, token); break;
                case "/each": push(EACH_END, token); break;
                case "switch": push(SWITCH, token); break;
                case "case": push(CASE, token); break;
                case "default": push(DEFAULT, token); break;
                case "/switch": push(SWITCH_END, token); break;
                default: push(ID, token);
            }
        }
        for(var i = 0, len = str.length; i < len; i ++){
            if(literal){
                if(last_is_escape){
                    last_is_escape = false;
                    if(str[i] == LWJSTE.escape_character){
                        token += LWJSTE.escape_character;
                    }else{
                        token += LWJSTE.escape_character + str[i];
                    }
                }else{
                    if(str[i] == LWJSTE.escape_character){
                        last_is_escape = true;
                    }else if(str[i] == "{"){
                        push(LITERAL, token);
                        push(L_CB, "{");
                        literal = false;
                    }else{
                        token += str[i];
                    }
                }
            }else{
                if(str[i] == "}"){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                    push(R_CB, "}");
                    pushed = false;
                    literal = true;
                }else if(str[i] == " "){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                }else{
                    token += str[i];
                }
            }
        }
        if(literal && token.length != 0){
            push(LITERAL, token);
        }else{
            //TODO error
        }
        //syntactic analysis
        var progress = 0;
        var token_length = tokens.length;
        var result = []; //output of parser
        var node = result; //pointer to result
        var indexes = []; //indexes of result
        var parent_nodes = []; //used in move_node_parent
        var cb_open = false; //it's true when in curly brackets
        var in_cb = []; //tokens in curly brackets
        var if_opens = 0, else_used = []; //used when in if blocks
        var each_opens = 0; //used when in each blocks
        var switch_opens = 0, case_used = [], default_used = []; //used when in switch blocks
        function drop(array, index){
            array.splice(index, 1);
        }
        function move_node_parent(count){
            drop(indexes, indexes.length - 1);
            indexes[indexes.length - 1] = parent_nodes[parent_nodes.length - 1];
            drop(parent_nodes, parent_nodes.length - 1);
            if(count != undefined && count > 1){
                move_node_parent(count - 1);
            }
        }
        function move_node_child(index){
            if(index == undefined){
                index = node.length - 1;
            }
            parent_nodes.push(indexes[indexes.length - 1]);
            indexes.push(index);
        }
        function move_node(index){
            indexes[indexes.length - 1] = index;
        }
        function get_current_node(){
            node = result;
            for(var i = 0, len = indexes.length; i < len; i ++){
                node = node[indexes[i]];
            }
        }
        function format_statement(){
            var result = [];
            for(var i = 1, len = in_cb.length; i < len; i ++){
                result.push(in_cb[i][1]);
            }
            return result;
        }
        while(progress < token_length){
            get_current_node();
            if(! cb_open){
                switch(tokens[progress][0]){
                    case LITERAL:
                        node.push([LWJSTE.LITERAL, tokens[progress][1]]);
                        break;
                    case L_CB:
                        cb_open = true;
                        in_cb = [];
                        break;
                    default:
                        //TODO error
                }
            }else{
                if(tokens[progress][0] == R_CB){
                    cb_open = false;
                    switch(in_cb[0][0]){
                        case IF:
                            if(in_cb.length == 1){
                                //TODO error
                            }else{
                                if_opens ++;
                                else_used.push(false);
                                node.push([LWJSTE.IF, [[format_statement(), []]], []]);
                                move_node_child();
                                move_node_child(1);
                                move_node_child(0);
                                move_node_child(1);
                            }
                            break;
                        case ELIF:
                            if(if_opens == 0 || in_cb.length == 1 || else_used[if_opens]){
                                //TODO error
                            }else{
                                drop(in_cb, 0);
                                move_node_parent(2);
                                get_current_node();
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                            }
                            break;
                        case ELSE:
                            if(if_opens == 0 || else_used[if_opens] || in_cb.length != 1){
                                //TODO error
                            }else{
                                else_used[if_opens] = true;
                                move_node_parent(3);
                                move_node_child(2);
                            }
                            break;
                        case IF_END:
                            if(if_opens == 0 || in_cb.length != 1){
                                //TODO error
                            }else{
                                if(else_used[if_opens]){
                                    drop(else_used, if_opens);
                                    move_node_parent(2);
                                }else{
                                    move_node_parent(4);
                                }
                                if_opens --;
                            }
                            break;
                        case EACH:
                            if(in_cb.length != 2){
                                //TODO error
                            }else{
                                each_opens ++;
                                node.push([LWJSTE.EACH, in_cb[1][1], []]);
                                move_node_child();
                                move_node_child(2);
                            }
                            break;
                        case EACH_END:
                            if(each_opens == 0 || in_cb.length != 1){
                                //TODO error
                            }else{
                                move_node_parent(2);
                                each_opens --;
                            }
                            break;
                        case SWITCH:
                            if(in_cb.length != 2){
                                //TODO error
                            }else{
                                switch_opens ++;
                                case_used.push(false);
                                default_used.push(false);
                                node.push([LWJSTE.SWITCH, in_cb[1], [], []]);
                                move_node_child();
                                move_node_child(2);
                            }
                            break;
                        case CASE:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length == 1){
                                //TODO error
                            }else{
                                if(case_used[switch_opens]){
                                    parent_nodes(2);
                                    get_current_node();
                                }
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                                case_used[switch_opens] = true;
                            }
                            break;
                        case DEFAULT:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length != 1){
                                //TODO error
                            }else{
                                default_used[switch_opens] = true;
                                if(case_used[switch_opens]){
                                    move_node_parent(3);
                                }else{
                                    move_node_parent();
                                }
                                move_node_child(3);
                            }
                            break;
                        case SWITCH_END:
                            if(switch_opens == 0 || case_used[switch_opens] == false || in_cb.length != 1){
                                //TODO error
                            }else{
                                console.log("fe;waoifjew");
                                if(default_used[switch_opens]){
                                    move_node_parent(2);
                                }else if(case_used[switch_opens]){
                                    move_node_parent(4);
                                }
                                switch_opens --;
                            }
                            break;
                        case ID:
                            if(in_cb.length != 1){
                                //TODO error
                            }else{
                                node.push([LWJSTE.VARIABLE, tokens[progress][1]]);
                            }
                            break;
                        default:
                            //TODO error
                    }
                    in_cb = [];
                }
                in_cb.push(tokens[progress]);
            }
            progress ++;
        }
        return success(result);
    },
    addTemplate : function(name, template){
        this.templates[name] = this._parseTemplate(template);
    },
    useTemplate : function(selector, name, template){
    },
    removeTemplate : function(name){
        if(name == null){
            this.templates = {};
        }else if(name in this.templates){
            delete this.templates[name];
        }
    },
    saveTemplates : function(destination){
    },
    loadTemplates : function(source){
    }
};
lwjste = new LWJSTE();
<commit_msg>add process of checking unexpected token to parser<commit_after>function LWJSTE(){
    this.templates = {};
    arguments.callee.escape_character = "#";
    arguments.callee.IF = 0;
    arguments.callee.EACH = 1;
    arguments.callee.SWITCH = 2;
    arguments.callee.LITERAL = 3;
    arguments.callee.VARIABLE = 4;
}
LWJSTE.prototype = {
    _parseTemplate : function(str){
        var LITERAL = 0, EACH = 1, IF = 2, ELIF = 3, ELSE = 4, ID = 5, SWITCH = 6, CASE = 7, DEFAULT = 8, L_CB = 9, R_CB = 10, EACH_END = 12, IF_END = 13, SWITCH_END = 14;
        var tokens = [];
        //lexer
        var token = "";
        var literal = true;
        var last_is_escape = false;
        var pushed = false;
        function success(result){
            return [0, result];
        }
        function faild(result){
            return [1, result];
        }
        function push(type, lexeme){
            if(lexeme.length != 0){
                tokens.push([type, lexeme]);
                token = "";
            }
        }
        function push_reserved_word(token){
            switch(token.toLowerCase()){
                case "if": push(IF, token); break;
                case "elif": push(ELIF, token); break;
                case "else": push(ELSE, token); break;
                case "/if": push(IF_END, token); break;
                case "each": push(EACH, token); break;
                case "/each": push(EACH_END, token); break;
                case "switch": push(SWITCH, token); break;
                case "case": push(CASE, token); break;
                case "default": push(DEFAULT, token); break;
                case "/switch": push(SWITCH_END, token); break;
                default: push(ID, token);
            }
        }
        for(var i = 0, len = str.length; i < len; i ++){
            if(literal){
                if(last_is_escape){
                    last_is_escape = false;
                    if(str[i] == LWJSTE.escape_character){
                        token += LWJSTE.escape_character;
                    }else{
                        token += LWJSTE.escape_character + str[i];
                    }
                }else{
                    if(str[i] == LWJSTE.escape_character){
                        last_is_escape = true;
                    }else if(str[i] == "{"){
                        push(LITERAL, token);
                        push(L_CB, "{");
                        literal = false;
                    }else{
                        token += str[i];
                    }
                }
            }else{
                if(str[i] == "}"){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                    push(R_CB, "}");
                    pushed = false;
                    literal = true;
                }else if(str[i] == " "){
                    if(token.length != 0){
                        push_reserved_word(token);
                    }
                }else{
                    token += str[i];
                }
            }
        }
        if(literal && token.length != 0){
            push(LITERAL, token);
        }else{
            //TODO error
        }
        //syntactic analysis
        var progress = 0;
        var token_length = tokens.length;
        var result = []; //output of parser
        var node = result; //pointer to result
        var indexes = []; //indexes of result
        var parent_nodes = []; //used in move_node_parent
        var cb_open = false; //it's true when in curly brackets
        var in_cb = []; //tokens in curly brackets
        var if_opens = 0, else_used = []; //used when in if blocks
        var each_opens = 0; //used when in each blocks
        var switch_opens = 0, case_used = [], default_used = []; //used when in switch blocks
        var unexpected_tokens = [ELIF, ELSE, CASE, DEFAULT, EACH_END, IF_END, SWITCH_END];
        function drop(array, index){
            array.splice(index, 1);
        }
        function set_unexpected_token(token){
            if(token instanceof Array){
                for(var i = 0, len = token.length; i < len; i ++){
                    set_unexpected_token(token[i]);
                }
            }else{
                if(unexpected_tokens.indexOf(token) == -1){
                    unexpected_tokens.push(token);
                }
            }
        }
        function remove_unexpected_token(token){
            if(token instanceof Array){
                for(var i = 0, len = token.length; i < len; i ++){
                    remove_unexpected_token(token[i]);
                }
            }else{
                for(var i = 0, len = unexpected_tokens.length; i < len; i ++){
                    if(token == unexpected_tokens[i]){
                        drop(unexpected_tokens, i);
                        break;
                    }
                }
            }
        }
        function move_node_parent(count){
            drop(indexes, indexes.length - 1);
            indexes[indexes.length - 1] = parent_nodes[parent_nodes.length - 1];
            drop(parent_nodes, parent_nodes.length - 1);
            if(count != undefined && count > 1){
                move_node_parent(count - 1);
            }
        }
        function move_node_child(index){
            if(index == undefined){
                index = node.length - 1;
            }
            parent_nodes.push(indexes[indexes.length - 1]);
            indexes.push(index);
        }
        function move_node(index){
            indexes[indexes.length - 1] = index;
        }
        function get_current_node(){
            node = result;
            for(var i = 0, len = indexes.length; i < len; i ++){
                node = node[indexes[i]];
            }
        }
        function format_statement(){
            var result = [];
            for(var i = 1, len = in_cb.length; i < len; i ++){
                result.push(in_cb[i][1]);
            }
            return result;
        }
        while(progress < token_length){
            if(unexpected_tokens.indexOf(tokens[progress][0]) != -1){
                //TODO error
                console.log(tokens[progress][1] + "aaaa");
            }
            get_current_node();
            if(! cb_open){
                switch(tokens[progress][0]){
                    case LITERAL:
                        node.push([LWJSTE.LITERAL, tokens[progress][1]]);
                        break;
                    case L_CB:
                        cb_open = true;
                        in_cb = [];
                        break;
                    default:
                        //TODO error
                }
            }else{
                if(tokens[progress][0] == R_CB){
                    cb_open = false;
                    switch(in_cb[0][0]){
                        case IF:
                            if(in_cb.length == 1){
                                //TODO error
                            }else{
                                if_opens ++;
                                else_used.push(false);
                                node.push([LWJSTE.IF, [[format_statement(), []]], []]);
                                move_node_child();
                                move_node_child(1);
                                move_node_child(0);
                                move_node_child(1);
                                remove_unexpected_token([ELIF, ELSE, IF_END]);
                            }
                            break;
                        case ELIF:
                            if(if_opens == 0 || in_cb.length == 1 || else_used[if_opens]){
                                //TODO error
                            }else{
                                drop(in_cb, 0);
                                move_node_parent(2);
                                get_current_node();
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                            }
                            break;
                        case ELSE:
                            if(if_opens == 0 || else_used[if_opens] || in_cb.length != 1){
                                //TODO error
                            }else{
                                else_used[if_opens] = true;
                                move_node_parent(3);
                                move_node_child(2);
                                set_unexpected_token(ELIF);
                            }
                            break;
                        case IF_END:
                            if(if_opens == 0 || in_cb.length != 1){
                                //TODO error
                            }else{
                                if(else_used[if_opens]){
                                    drop(else_used, if_opens);
                                    move_node_parent(2);
                                }else{
                                    move_node_parent(4);
                                }
                                if_opens --;
                                set_unexpected_token([ELIF, ELSE, IF_END]);
                            }
                            break;
                        case EACH:
                            if(in_cb.length != 2){
                                //TODO error
                            }else{
                                each_opens ++;
                                node.push([LWJSTE.EACH, in_cb[1][1], []]);
                                move_node_child();
                                move_node_child(2);
                                remove_unexpected_token(EACH_END);
                            }
                            break;
                        case EACH_END:
                            if(each_opens == 0 || in_cb.length != 1){
                                //TODO error
                            }else{
                                move_node_parent(2);
                                each_opens --;
                                set_unexpected_token(EACH_END);
                            }
                            break;
                        case SWITCH:
                            if(in_cb.length != 2){
                                //TODO error
                            }else{
                                switch_opens ++;
                                case_used.push(false);
                                default_used.push(false);
                                node.push([LWJSTE.SWITCH, in_cb[1][1], [], []]);
                                move_node_child();
                                move_node_child(2);
                                remove_unexpected_token([CASE, DEFAULT, SWITCH_END]);
                                set_unexpected_token([EACH, IF, LITERAL, SWITCH]);
                            }
                            break;
                        case CASE:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length == 1){
                                //TODO error
                            }else{
                                if(case_used[switch_opens]){
                                    parent_nodes(2);
                                    get_current_node();
                                }
                                node.push([format_statement(), []]);
                                move_node_child();
                                move_node_child(1);
                                case_used[switch_opens] = true;
                                remove_unexpected_token([EACH, IF, LITERAL, SWITCH]);
                            }
                            break;
                        case DEFAULT:
                            if(switch_opens == 0 || default_used[switch_opens] || in_cb.length != 1){
                                //TODO error
                            }else{
                                default_used[switch_opens] = true;
                                if(case_used[switch_opens]){
                                    move_node_parent(3);
                                }else{
                                    move_node_parent();
                                }
                                move_node_child(3);
                                set_unexpected_token(CASE);
                                remove_unexpected_token([EACH, IF, LITERAL, SWITCH]);
                            }
                            break;
                        case SWITCH_END:
                            if(switch_opens == 0 || case_used[switch_opens] == false || in_cb.length != 1){
                                //TODO error
                            }else{
                                if(default_used[switch_opens]){
                                    move_node_parent(2);
                                }else if(case_used[switch_opens]){
                                    move_node_parent(4);
                                }
                                switch_opens --;
                                set_unexpected_token([CASE, DEFAULT, SWITCH_END]);
                            }
                            break;
                        case ID:
                            if(in_cb.length != 1){
                                //TODO error
                            }else{
                                node.push([LWJSTE.VARIABLE, tokens[progress][1]]);
                            }
                            break;
                        default:
                            //TODO error
                    }
                    in_cb = [];
                }
                in_cb.push(tokens[progress]);
            }
            progress ++;
        }
        return success(result);
    },
    addTemplate : function(name, template){
        this.templates[name] = this._parseTemplate(template);
    },
    useTemplate : function(selector, name, template){
    },
    removeTemplate : function(name){
        if(name == null){
            this.templates = {};
        }else if(name in this.templates){
            delete this.templates[name];
        }
    },
    saveTemplates : function(destination){
    },
    loadTemplates : function(source){
    }
};
lwjste = new LWJSTE();
<|endoftext|>


<commit_before>var monthCtrl = function ($scope, $rootScope, underscore, SweetAlert, $filter) {
    $scope.annualReport = {
        oral: [],
        colorectal: [],
        coach: []
    };

    function initReport() {
        for(var i = 0; i < 12; i++) {
            $scope.annualReport.oral[i] = {
                filter: {
                    count: 0,
                    man: 0,
                    female: 0,
                    teenager: {
                        man: 0,
                        female: 0
                    },
                    abor: {
                        man: 0,
                        female: 0
                    }
                },
                lectures: {
                    school: {
                        count: 0,
                        man: 0,
                        female: 0
                    },
                    count: 0,
                    man: 0,
                    female: 0
                },
                media: {
                    newspaper: 0,
                    column:0,
                    publication:0,
                    magazine:0,
                    other:0
                },
                tv: {
                    adv: 0,
                    report:0,
                    interview:0,
                    other:0
                },
                ads: {
                    car: 0,
                    board: 0,
                    wall: 0,
                    buman: 0,
                    other: 0
                },
                marquee: 0,
                cloth: 0,
                other:0,
                area: 0,
            };

            $scope.annualReport.colorectal[i] = {
                filter: {
                    count: 0,
                    man: 0,
                    female: 0,
                    workplace: {
                        count: 0,
                        oral: 0,
                        blood: 0,
                    }
                },
                lectures: {
                    count: 0,
                    man: 0,
                    female: 0
                },
            };

            $scope.annualReport.coach[i] = {
                count: 0,
                data: []
            }
        }
    }

    $scope.init = function () {
        initReport();
    }

    $scope.analytics = function () {
        if ($('#source1').val() === '' || $('#source2').val() === '') {
            swal("請選擇檔案", "發生錯誤", "error");
            return;
        }
        oralSource(colorectalSource);
    }

    var oralSource = function (callback) {
        $('#source1').parse({
            config: {
                complete: function (results) {
                    results.data.shift();
                    if (results.data.length == 0) {
                        callback();
                        return;
                    }
                    underscore.each(results.data, function (item, key) {
                        if (underscore.size(item) === 1) {
                            return;
                        }
                        var month = item[2] - 1;

                        // filter
                        $scope.annualReport.oral[month].filter.count += parseIntFilterEmpty(item[3]);
                        $scope.annualReport.oral[month].filter.man += parseIntFilterEmpty(item[4]);
                        $scope.annualReport.oral[month].filter.female += parseIntFilterEmpty(item[5]);
                        // teenage
                        $scope.annualReport.oral[month].filter.teenager.man += parseIntFilterEmpty(item[6]);
                        $scope.annualReport.oral[month].filter.teenager.female += parseIntFilterEmpty(item[7]);
                        // abor
                        $scope.annualReport.oral[month].filter.abor.man += parseIntFilterEmpty(item[8]);
                        $scope.annualReport.oral[month].filter.abor.female += parseIntFilterEmpty(item[9]);

                        // lectures
                        for (var i = 10; i < 22; i+=4) {
                            if (item[i] !== '') {
                                $scope.annualReport.oral[month].lectures.school.count++;
                                $scope.annualReport.oral[month].lectures.school.man += parseIntFilterEmpty(item[i + 1]);
                                $scope.annualReport.oral[month].lectures.school.female += parseIntFilterEmpty(item[i + 2]);
                            }
                        }

                        for (var i = 22; i < 40; i+=6) {
                            if (item[i] !== '') {
                                $scope.annualReport.oral[month].lectures.count++;
                                $scope.annualReport.oral[month].lectures.man += parseIntFilterEmpty(item[i + 2]);
                                $scope.annualReport.oral[month].lectures.female += parseIntFilterEmpty(item[i + 3]);
                            }
                        }

                        // media
                        $scope.annualReport.oral[month].media.newspaper += parseIntFilterEmpty(item[43]);
                        $scope.annualReport.oral[month].media.column += parseIntFilterEmpty(item[45]);
                        $scope.annualReport.oral[month].media.publication += parseIntFilterEmpty(item[47]);
                        $scope.annualReport.oral[month].media.magazine += parseIntFilterEmpty(item[49]);
                        $scope.annualReport.oral[month].media.other += parseIntFilterEmpty(item[51]);

                        // tv
                        $scope.annualReport.oral[month].tv.adv += parseIntFilterEmpty(item[53]);
                        $scope.annualReport.oral[month].tv.report += parseIntFilterEmpty(item[55]);
                        $scope.annualReport.oral[month].tv.interview += parseIntFilterEmpty(item[57]);
                        $scope.annualReport.oral[month].tv.other += parseIntFilterEmpty(item[59]);

                        // ads
                        $scope.annualReport.oral[month].ads.car += parseIntFilterEmpty(item[61]);
                        $scope.annualReport.oral[month].ads.board += parseIntFilterEmpty(item[63]);
                        $scope.annualReport.oral[month].ads.wall += parseIntFilterEmpty(item[65]);
                        $scope.annualReport.oral[month].ads.buman += parseIntFilterEmpty(item[67]);
                        $scope.annualReport.oral[month].ads.other += parseIntFilterEmpty(item[69]);

                        // marquee
                        $scope.annualReport.oral[month].marquee += parseIntFilterEmpty(item[71]);

                        // cloth
                        $scope.annualReport.oral[month].cloth += parseIntFilterEmpty(item[73]);

                        // other
                        $scope.annualReport.oral[month].other += parseIntFilterEmpty(item[75]);

                        // area
                        $scope.annualReport.oral[month].area += parseIntFilterEmpty(item[77])

                        // coach
                        processCoach(month, item[78]);
                    });
                    callback();
                }
            }
        });
    }

    var colorectalSource = function (callback) {
        $('#source2').parse({
            config: {
                complete: function (results) {
                    results.data.shift();
                    if (results.data.length == 0) {
                        analyticsComplete();
                        return;
                    }
                    underscore.each(results.data, function (item, key) {
                        if (underscore.size(item) === 1) {
                            return;
                        }
                        var month = item[2] - 1;
                        // fiter
                        $scope.annualReport.colorectal[month].filter.count += parseIntFilterEmpty(item[3]);
                        $scope.annualReport.colorectal[month].filter.man += parseIntFilterEmpty(item[4]);
                        $scope.annualReport.colorectal[month].filter.female += parseIntFilterEmpty(item[5]);
                        for (var i = 6; i < 15; i+=3) {
                            if (item[6] !== '') {
                                $scope.annualReport.colorectal[month].filter.workplace.count++;
                                $scope.annualReport.colorectal[month].filter.workplace.oral += parseIntFilterEmpty(item[i + 1]);
                                $scope.annualReport.colorectal[month].filter.workplace.blood += parseIntFilterEmpty(item[i + 2]);
                            }
                        }

                        // lectures
                        $scope.annualReport.colorectal[month].lectures.count += parseIntFilterEmpty(item[15]);
                        for (var i = 16; i < 28; i+=4) {
                            if (item[i] !== '') {
                                $scope.annualReport.colorectal[month].lectures.man += parseIntFilterEmpty(item[i + 2]);
                                $scope.annualReport.colorectal[month].lectures.female += parseIntFilterEmpty(item[i + 3]);
                            }
                        }

                        // coach
                        processCoach(month, item[62]);
                    });
                    analyticsComplete();
                }
            }
        });
    }

    var processCoach = function (month, item) {
        if (item !== '') {
            var report = [];
            underscore.each(item.split('\n'), function (value, index) {
                var match = value.match(/(\d{2,3}\.\d{1,2}\.\d{1,2}),?(.*)/);
                if (match !== null) {
                    report.push({
                        date: new Date(match[1]),
                        name: match[2]
                    })
                }
            });

            underscore.each(report, function (value, index) {
                if (underscore.where($scope.annualReport.coach[month].data, value).length === 0) {
                    $scope.annualReport.coach[month].count++;
                    $scope.annualReport.coach[month].data.push(value);
                }
            });
        }
    }

    var analyticsComplete = function () {
        SweetAlert.swal("Good job!", "分析完成!", "success");
        // $scope.$apply();
    };
}

var parseIntFilterEmpty = function (value) {
  return parseInt(value) || 0;
}

app.controller('monthCtrl', monthCtrl);<commit_msg>Update reports.<commit_after>var monthCtrl = function ($scope, $rootScope, underscore, SweetAlert, $filter) {
    $scope.annualReport = {
        oral: [],
        colorectal: [],
        coach: []
    };

    function initReport() {
        for(var i = 0; i < 12; i++) {
            $scope.annualReport.oral[i] = {
                filter: {
                    count: 0,
                    man: 0,
                    female: 0,
                    teenager: {
                        man: 0,
                        female: 0
                    },
                    abor: {
                        man: 0,
                        female: 0
                    }
                },
                lectures: {
                    school: {
                        count: 0,
                        man: 0,
                        female: 0
                    },
                    count: 0,
                    man: 0,
                    female: 0
                },
                media: {
                    newspaper: 0,
                    column:0,
                    publication:0,
                    magazine:0,
                    other:0
                },
                tv: {
                    adv: 0,
                    report:0,
                    interview:0,
                    other:0
                },
                ads: {
                    car: 0,
                    board: 0,
                    wall: 0,
                    buman: 0,
                    other: 0
                },
                marquee: 0,
                cloth: 0,
                other:0,
                area: 0,
            };

            $scope.annualReport.colorectal[i] = {
                filter: {
                    count: 0,
                    man: 0,
                    female: 0,
                    workplace: {
                        count: 0,
                        oral: 0,
                        blood: 0,
                    }
                },
                lectures: {
                    count: 0,
                    man: 0,
                    female: 0
                },
            };

            $scope.annualReport.coach[i] = {
                count: 0,
                data: []
            }
        }
    }

    $scope.init = function () {
        initReport();
    }

    $scope.analytics = function () {
        if ($('#source1').val() === '' || $('#source2').val() === '') {
            swal("請選擇檔案", "發生錯誤", "error");
            return;
        }
        oralSource(colorectalSource);
    }

    var oralSource = function (callback) {
        $('#source1').parse({
            config: {
                complete: function (results) {
                    results.data.shift();
                    if (results.data.length == 0) {
                        callback();
                        return;
                    }
                    underscore.each(results.data, function (item, key) {
                        if (underscore.size(item) === 1) {
                            return;
                        }
                        var month = item[2] - 1;

                        // filter
                        $scope.annualReport.oral[month].filter.count += parseIntFilterEmpty(item[3]);
                        $scope.annualReport.oral[month].filter.man += parseIntFilterEmpty(item[4]);
                        $scope.annualReport.oral[month].filter.female += parseIntFilterEmpty(item[5]);
                        // teenage
                        $scope.annualReport.oral[month].filter.teenager.man += parseIntFilterEmpty(item[6]);
                        $scope.annualReport.oral[month].filter.teenager.female += parseIntFilterEmpty(item[7]);
                        // abor
                        $scope.annualReport.oral[month].filter.abor.man += parseIntFilterEmpty(item[8]);
                        $scope.annualReport.oral[month].filter.abor.female += parseIntFilterEmpty(item[9]);

                        // lectures
                        for (var i = 10; i < 22; i+=4) {
                            if (item[i] !== '') {
                                $scope.annualReport.oral[month].lectures.school.count++;
                                $scope.annualReport.oral[month].lectures.school.man += parseIntFilterEmpty(item[i + 1]);
                                $scope.annualReport.oral[month].lectures.school.female += parseIntFilterEmpty(item[i + 2]);
                            }
                        }

                        for (var i = 22; i < 40; i+=6) {
                            if (item[i] !== '') {
                                $scope.annualReport.oral[month].lectures.count++;
                                $scope.annualReport.oral[month].lectures.man += parseIntFilterEmpty(item[i + 2]);
                                $scope.annualReport.oral[month].lectures.female += parseIntFilterEmpty(item[i + 3]);
                            }
                        }

                        // media
                        $scope.annualReport.oral[month].media.newspaper += parseIntFilterEmpty(item[58]);
                        $scope.annualReport.oral[month].media.column += parseIntFilterEmpty(item[60]);
                        $scope.annualReport.oral[month].media.publication += parseIntFilterEmpty(item[62]);
                        $scope.annualReport.oral[month].media.magazine += parseIntFilterEmpty(item[64]);
                        $scope.annualReport.oral[month].media.other += parseIntFilterEmpty(item[66]);

                        // tv
                        $scope.annualReport.oral[month].tv.adv += parseIntFilterEmpty(item[68]);
                        $scope.annualReport.oral[month].tv.report += parseIntFilterEmpty(item[70]);
                        $scope.annualReport.oral[month].tv.interview += parseIntFilterEmpty(item[72]);
                        $scope.annualReport.oral[month].tv.other += parseIntFilterEmpty(item[74]);

                        // ads
                        $scope.annualReport.oral[month].ads.car += parseIntFilterEmpty(item[76]);
                        $scope.annualReport.oral[month].ads.board += parseIntFilterEmpty(item[78]);
                        $scope.annualReport.oral[month].ads.wall += parseIntFilterEmpty(item[80]);
                        $scope.annualReport.oral[month].ads.buman += parseIntFilterEmpty(item[82]);
                        $scope.annualReport.oral[month].ads.other += parseIntFilterEmpty(item[84]);

                        // marquee
                        $scope.annualReport.oral[month].marquee += parseIntFilterEmpty(item[86]);

                        // cloth
                        $scope.annualReport.oral[month].cloth += parseIntFilterEmpty(item[88]);

                        // other
                        $scope.annualReport.oral[month].other += parseIntFilterEmpty(item[90]);

                        // area
                        $scope.annualReport.oral[month].area += parseIntFilterEmpty(item[92])

                        // coach
                        processCoach(month, item[94]);
                    });
                    callback();
                }
            }
        });
    }

    var colorectalSource = function (callback) {
        $('#source2').parse({
            config: {
                complete: function (results) {
                    results.data.shift();
                    if (results.data.length == 0) {
                        analyticsComplete();
                        return;
                    }
                    underscore.each(results.data, function (item, key) {
                        if (underscore.size(item) === 1) {
                            return;
                        }
                        var month = item[2] - 1;
                        // fiter
                        $scope.annualReport.colorectal[month].filter.count += parseIntFilterEmpty(item[3]);
                        $scope.annualReport.colorectal[month].filter.man += parseIntFilterEmpty(item[4]);
                        $scope.annualReport.colorectal[month].filter.female += parseIntFilterEmpty(item[5]);
                        for (var i = 6; i < 15; i+=3) {
                            if (item[6] !== '') {
                                $scope.annualReport.colorectal[month].filter.workplace.count++;
                                $scope.annualReport.colorectal[month].filter.workplace.oral += parseIntFilterEmpty(item[i + 1]);
                                $scope.annualReport.colorectal[month].filter.workplace.blood += parseIntFilterEmpty(item[i + 2]);
                            }
                        }

                        // lectures
                        $scope.annualReport.colorectal[month].lectures.count += parseIntFilterEmpty(item[15]);
                        for (var i = 16; i < 28; i+=4) {
                            if (item[i] !== '') {
                                $scope.annualReport.colorectal[month].lectures.man += parseIntFilterEmpty(item[i + 2]);
                                $scope.annualReport.colorectal[month].lectures.female += parseIntFilterEmpty(item[i + 3]);
                            }
                        }

                        // coach
                        processCoach(month, item[62]);
                    });
                    analyticsComplete();
                }
            }
        });
    }

    var processCoach = function (month, item) {
        if (item !== '') {
            var report = [];
            underscore.each(item.split('\n'), function (value, index) {
                var match = value.match(/(\d{2,3}\.\d{1,2}\.\d{1,2}),?(.*)/);
                if (match !== null) {
                    report.push({
                        date: new Date(match[1]),
                        name: match[2]
                    })
                }
            });

            underscore.each(report, function (value, index) {
                if (underscore.where($scope.annualReport.coach[month].data, value).length === 0) {
                    $scope.annualReport.coach[month].count++;
                    $scope.annualReport.coach[month].data.push(value);
                }
            });
        }
    }

    var analyticsComplete = function () {
        SweetAlert.swal("Good job!", "分析完成!", "success");
        // $scope.$apply();
    };
}

var parseIntFilterEmpty = function (value) {
  return parseInt(value) || 0;
}

app.controller('monthCtrl', monthCtrl);<|endoftext|>


<commit_before>'use strict';

const {
    run,
    series,
    parallel,
} = require('madrun');

module.exports = {
    'test': () => `tape 'test/**/*.js'`,
    'watch:test': () => `nodemon -w lib -w test -x ${run('test')}`,
    "lint:test": () => "eslint -c .eslintrc.server test",
    "lint:server": () => "eslint -c .eslintrc.server --rule 'no-console:0' bin server",
    "lint:client": () => "eslint --env browser --config .eslintrc client",
    'lint': () => series(['putout', 'lint:*']),
    'fix:lint': () => series(['putout', 'lint:*'], '--fix'),
    'putout': () => `putout bin test client server`,
    'coverage': () => `nyc ${run('test')}`,
    'report': () => `nyc report --reporter=text-lcov | coveralls || true`,
};

<commit_msg>chore(madrun) series -> run<commit_after>'use strict';

const {
    run,
} = require('madrun');

module.exports = {
    'test': () => `tape 'test/**/*.js'`,
    'watch:test': () => `nodemon -w lib -w test -x ${run('test')}`,
    'lint:test': () => 'eslint -c .eslintrc.server test madrun.js',
    'lint:server': () => 'eslint -c .eslintrc.server --rule \'no-console:0\' bin server',
    'lint:client': () => 'eslint --env browser --config .eslintrc client',
    'lint': () => run(['putout', 'lint:*']),
    'fix:lint': () => run(['putout', 'lint:*'], '--fix'),
    'putout': () => `putout bin test client server madrun.js`,
    'coverage': () => `nyc ${run('test')}`,
    'report': () => `nyc report --reporter=text-lcov | coveralls || true`,
};

<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var moment = require('moment');
var execSync = require('child_process').execSync;

// path to the lineup file
var running_dir = process.argv[2];
var lineupFilePath = fs.readFileSync(running_dir + "/lineups/current", 'utf8');
var media_dir = process.argv[3];
var currentClipFilePath = process.argv[4];

var lineup = null;

var findClip = function(programIdx, clipAbsolutePath) {
	var program = lineup.Programs[programIdx];

	if (program.PreShow) {
		for (var i = 0; i < program.PreShow.Clips.length; i++) {
			var cAbsolutePath = path.resolve(media_dir, program.PreShow.Clips[i].Path);
			if (clipAbsolutePath == cAbsolutePath) {
				return program.PreShow.Clips[i];
			}
		}
	}
	for (var i = 0; i < program.Show.Clips.length; i++) {
		var cAbsolutePath = path.resolve(media_dir, program.Show.Clips[i].Path);
		if (clipAbsolutePath == cAbsolutePath) {
			return program.Show.Clips[i];
		}
	}

	return null;
}

if (fs.existsSync(lineupFilePath)) {
	lineup = JSON.parse(fs.readFileSync(lineupFilePath, 'utf8'));
	var currentProgramIdx = parseInt(fs.readFileSync(lineupFilePath + ".program.iter", 'utf8'));

	clip = findClip(currentProgramIdx, currentClipFilePath);

	// might be
	if (!clip) {
		if (lineup.Programs[currentProgramIdx + 1] &&
			clipAbsolutePath == currentClipFilePathlineup.Programs[currentProgramIdx + 1].Show.Clips[0].Path) {
			// TODO
			// In case of back-to-back programs, we need to move program iter when the first
			// media of the next program begins to play.
			// Lets shift the current program iterator
			currentProgramIdx++;
			clip = findClip(currentProgramIdx, currentClipFilePath);
			// fs.writeFileSync(lineupFilePath + ".program.iter", currentProgramIdx);
		}
	}

	if (clip) {
		// We have program playing
		status = {};
		status.isCurrentlyPlaying = true;
		status.currentProgram = lineup.Programs[currentProgramIdx].Title;
		status.currentClip = clip.Description ? clip.Description : "";

		fs.writeFileSync(running_dir + "/web/status.json", status);

	} else {
		// No programs right now! Instead publish the countdown
		status = {};
		status.isCurrentlyPlaying = false;
		status.currentProgram = BLANK;
		status.now = moment().format();

		if (lineup.Programs[currentProgramIdx + 1]) {

			nextProgram = lineup.Programs[currentProgramIdx + 1];
			status.nextBoxId = nextProgram.BoxId;
			status.nextBoxStartTime = nextProgram.PreShow ?
										nextProgram.PreShow.Meta.TentativeStartTime :
										nextProgram.Show.Meta.TentativeStartTime;
		} else {
			// TODO
			// Todays programs is over, we should check the next days lineup
		}

		fs.writeFileSync(running_dir + "/web/status.json", status);
	}
}
<commit_msg>new status system<commit_after>var fs = require('fs');
var path = require('path');
var moment = require('moment');
var execSync = require('child_process').execSync;

// path to the lineup file
var running_dir = process.argv[2];
var lineupFilePath = fs.readFileSync(running_dir + "/lineups/current", 'utf8');
var media_dir = process.argv[3];
var currentClipFilePath = process.argv[4];

var lineup = null;

var findClip = function(programIdx, clipAbsolutePath) {
	var program = lineup.Programs[programIdx];

	if (program.PreShow) {
		for (var i = 0; i < program.PreShow.Clips.length; i++) {
			var cAbsolutePath = path.resolve(media_dir, program.PreShow.Clips[i].Path);
			if (clipAbsolutePath == cAbsolutePath) {
				return program.PreShow.Clips[i];
			}
		}
	}
	for (var i = 0; i < program.Show.Clips.length; i++) {
		var cAbsolutePath = path.resolve(media_dir, program.Show.Clips[i].Path);
		if (clipAbsolutePath == cAbsolutePath) {
			return program.Show.Clips[i];
		}
	}

	return null;
}

if (fs.existsSync(lineupFilePath)) {
	lineup = JSON.parse(fs.readFileSync(lineupFilePath, 'utf8'));
	var currentProgramIdx = parseInt(fs.readFileSync(lineupFilePath + ".program.iter", 'utf8'));

	clip = findClip(currentProgramIdx, currentClipFilePath);

	// might be
	if (!clip) {
		upcomingClipAbsolutePath = path.resolve(media_dir, currentClipFilePathlineup.Programs[currentProgramIdx + 1].Show.Clips[0].Path)
		if (lineup.Programs[currentProgramIdx + 1] &&
			currentClipFilePath == upcomingClipAbsolutePath) {
			// In case of back-to-back programs, we need to move program iter when the first
			// media of the next program begins to play.
			// Lets shift the current program iterator
			currentProgramIdx++;
			clip = findClip(currentProgramIdx, currentClipFilePath);
			// TODO
			// fs.writeFileSync(lineupFilePath + ".program.iter", currentProgramIdx);
		}
	}

	if (clip) {
		// We have program playing
		status = {};
		status.isCurrentlyPlaying = true;
		status.currentProgram = lineup.Programs[currentProgramIdx].Title;
		status.currentClip = clip.Description ? clip.Description : "";

		fs.writeFileSync(running_dir + "/web/status.json", status);

	} else {
		// No programs right now! Instead publish the countdown
		status = {};
		status.isCurrentlyPlaying = false;
		status.currentProgram = BLANK;
		status.now = moment().format();

		if (lineup.Programs[currentProgramIdx + 1]) {

			nextProgram = lineup.Programs[currentProgramIdx + 1];
			status.nextBoxId = nextProgram.BoxId;
			status.nextBoxStartTime = nextProgram.PreShow ?
										nextProgram.PreShow.Meta.TentativeStartTime :
										nextProgram.Show.Meta.TentativeStartTime;
		} else {
			// TODO
			// Todays programs is over, we should check the next days lineup
		}

		fs.writeFileSync(running_dir + "/web/status.json", status);
	}
}
<|endoftext|>


<commit_before>var quicktest = function(svg, data, Plottable) {

  var xScale = new Plottable.Scale.Linear();
  var xAxis = new Plottable.Axis.XAxis(xScale, "bottom");

  varyScale = new Plottable.Scale.Linear();
  var yAxis = new Plottable.Axis.YAxis(yScale, "left").tickLabelPosition("bottom");
  //yAxis.tickFormat(d3.format("g"));

  var renderAreaD1 = new Plottable.Plot.Scatter(data[0].slice(0, 3), xScale, yScale);
  console.log(renderAreaD1.dataSource.data());
  var gridlines = new Plottable.Component.Gridlines(xScale, yScale);
  var renderGroup = renderAreaD1.merge(gridlines);
  var chart = new Plottable.Component.Table([[yAxis, renderGroup],
                                         [null,  xAxis]]);
  var pzi = new Plottable.Interaction.PanZoom(renderGroup, xScale, yScale);
  pzi.registerWithComponent();
  chart.renderTo(svg);

}

quicktest.quicktestName = "gridlines";
quicktests.push(quicktest);
<commit_msg>Update gridlines.js<commit_after>var quicktest = function(svg, data, Plottable) {

  var xScale = new Plottable.Scale.Linear();
  var xAxis = new Plottable.Axis.XAxis(xScale, "bottom");

  varyScale = new Plottable.Scale.Linear();
  var yAxis = new Plottable.Axis.YAxis(yScale, "left").tickLabelPosition("bottom");
  yAxis.tickFormat(d3.format("g"));

  console.log(data);

  var renderAreaD1 = new Plottable.Plot.Scatter(data[0].slice(0, 3), xScale, yScale);
  console.log(renderAreaD1.dataSource.data());
  var gridlines = new Plottable.Component.Gridlines(xScale, yScale);
  var renderGroup = renderAreaD1.merge(gridlines);
  var chart = new Plottable.Component.Table([[yAxis, renderGroup],
                                         [null,  xAxis]]);
  var pzi = new Plottable.Interaction.PanZoom(renderGroup, xScale, yScale);
  pzi.registerWithComponent();
  chart.renderTo(svg);

}

quicktest.quicktestName = "gridlines";
quicktests.push(quicktest);
<|endoftext|>


<commit_before>/*!
 * VisualEditor UserInterface MWMapsDialog class.
 *
 * @copyright 2011-2015 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */
/* globals require */
var kartobox = require( 'ext.kartographer.box' ),
	kartoEditing = require( 'ext.kartographer.editing' );

/**
 * Dialog for editing MW maps.
 *
 * @class
 * @extends ve.ui.MWExtensionDialog
 *
 * @constructor
 * @param {Object} [config] Configuration options
 */
ve.ui.MWMapsDialog = function VeUiMWMapsDialog() {
	// Parent constructor
	ve.ui.MWMapsDialog.super.apply( this, arguments );

	this.updateGeoJson = $.debounce( 300, $.proxy( this.updateGeoJson, this ) );
	this.resetMapPosition = $.debounce( 300, $.proxy( this.resetMapPosition, this ) );
};

/* Inheritance */

OO.inheritClass( ve.ui.MWMapsDialog, ve.ui.MWExtensionDialog );

/* Static Properties */

ve.ui.MWMapsDialog.static.name = 'mwMaps';

ve.ui.MWMapsDialog.static.title = OO.ui.deferMsg( 'visualeditor-mwmapsdialog-title' );

ve.ui.MWMapsDialog.static.size = 'larger';

ve.ui.MWMapsDialog.static.allowedEmpty = true;

ve.ui.MWMapsDialog.static.modelClasses = [ ve.dm.MWMapsNode, ve.dm.MWInlineMapsNode ];

/* Methods */

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.initialize = function () {
	var panel;

	// Parent method
	ve.ui.MWMapsDialog.super.prototype.initialize.call( this );

	this.$mapContainer = $( '<div>' ).addClass( 've-ui-mwMapsDialog-mapWidget' );
	this.$map = $( '<div>' ).appendTo( this.$mapContainer );
	this.map = null;
	this.scalable = null;
	this.updatingGeoJson = false;

	this.dimensions = new ve.ui.DimensionsWidget();

	this.input = new ve.ui.MWAceEditorWidget( {
		multiline: true,
		autosize: true,
		maxRows: 10,
		classes: [ 've-ui-mwMapsDialog-geoJSONWidget' ]
	} )
		.setLanguage( 'json' )
		.toggleLineNumbers( false )
		.setRTL( false );

	this.resetMapButton = new OO.ui.ButtonWidget( {
		label: ve.msg( 'visualeditor-mwmapsdialog-reset-map' )
	} );

	panel = new OO.ui.PanelLayout( {
		padded: true,
		expanded: false
	} );

	this.dimensionsField = new OO.ui.FieldLayout( this.dimensions, {
		align: 'right',
		label: ve.msg( 'visualeditor-mwmapsdialog-size' )
	} );

	this.$resetMapButtonContainer = $( '<div>' ).addClass( 've-ui-mwMapsDialog-resetMapButton' );

	this.geoJsonField = new OO.ui.FieldLayout( this.input, {
		align: 'top',
		label: ve.msg( 'visualeditor-mwmapsdialog-geojson' )
	} );

	panel.$element.append(
		this.dimensionsField.$element,
		this.$mapContainer,
		this.$resetMapButtonContainer.append( this.resetMapButton.$element ),
		this.geoJsonField.$element
	);
	this.$body.append( panel.$element );
};

/**
 * Handle change events on the dimensions widget
 *
 * @param {string} newValue
 */
ve.ui.MWMapsDialog.prototype.onDimensionsChange = function () {
	var dimensions, center;

	if ( !this.map ) {
		return;
	}

	dimensions = this.scalable.getBoundedDimensions(
		this.dimensions.getDimensions()
	);
	center = this.map && this.map.getCenter();

	// Set container width for centering
	this.$mapContainer.css( { width: dimensions.width } );
	this.$map.css( dimensions );
	this.updateSize();

	if ( center ) {
		this.map.setView( center );
	}
	this.map.invalidateSize();
	this.updateActions();
};

/**
 * Reset the map's position
 */
ve.ui.MWMapsDialog.prototype.resetMapPosition = function () {
	var position,
		dialog = this;

	if ( !this.map ) {
		return;
	}

	position = this.getInitialMapPosition();
	this.map.setView( position.center, position.zoom );

	this.updateActions();
	this.resetMapButton.setDisabled( true );

	this.map.once( 'moveend', function () {
		dialog.updateActions();
		dialog.resetMapButton.setDisabled( false );
	} );
};

/**
 * Update action states
 */
ve.ui.MWMapsDialog.prototype.updateActions = function () {
	var newMwData, modified,
		mwData = this.selectedNode && this.selectedNode.getAttribute( 'mw' );

	if ( mwData ) {
		newMwData = ve.copy( mwData );
		this.updateMwData( newMwData );
		modified = !ve.compare( mwData, newMwData );
	} else {
		modified = true;
	}
	this.actions.setAbilities( { done: modified } );
};

/**
 * @inheritdoc ve.ui.MWExtensionWindow
 */
ve.ui.MWMapsDialog.prototype.insertOrUpdateNode = function () {
	// Parent method
	ve.ui.MWMapsDialog.super.prototype.insertOrUpdateNode.apply( this, arguments );

	// Update scalable
	this.scalable.setCurrentDimensions(
		this.scalable.getBoundedDimensions(
			this.dimensions.getDimensions()
		)
	);
};

/**
 * @inheritdoc ve.ui.MWExtensionWindow
 */
ve.ui.MWMapsDialog.prototype.updateMwData = function ( mwData ) {
	var center, latitude, longitude, zoom,
		dimensions = this.scalable.getBoundedDimensions(
			this.dimensions.getDimensions()
		);

	// Parent method
	ve.ui.MWMapsDialog.super.prototype.updateMwData.call( this, mwData );

	if ( this.map ) {
		center = this.map.getCenter();
		latitude = center.lat;
		longitude = center.lng;
		zoom = this.map.getZoom();
	} else {
		// Map not loaded in insert, can't insert
		return;
	}
	mwData.attrs.latitude = latitude.toString();
	mwData.attrs.longitude = longitude.toString();
	mwData.attrs.zoom = zoom.toString();
	if ( !( this.selectedNode instanceof ve.dm.MWInlineMapsNode ) ) {
		mwData.attrs.width = dimensions.width.toString();
		mwData.attrs.height = dimensions.height.toString();
	}
};

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.getReadyProcess = function ( data ) {
	return ve.ui.MWMapsDialog.super.prototype.getReadyProcess.call( this, data )
		.next( function () {
			this.setupMap();
		}, this );
};

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.getSetupProcess = function ( data ) {
	data = data || {};
	return ve.ui.MWMapsDialog.super.prototype.getSetupProcess.call( this, data )
		.next( function () {
			var inline = this.selectedNode instanceof ve.dm.MWInlineMapsNode;

			this.input.clearUndoStack();

			this.actions.setMode( this.selectedNode ? 'edit' : 'insert' );

			if ( this.selectedNode && !inline ) {
				this.scalable = this.selectedNode.getScalable();
			} else {
				this.scalable = ve.dm.MWMapsNode.static.createScalable(
					inline ?
					{ width: 850, height: 400 } :
					{ width: 400, height: 300 }
				);
			}

			// Events
			this.input.connect( this, {
				change: 'updateGeoJson',
				resize: 'updateSize'
			} );
			this.dimensions.connect( this, {
				widthChange: 'onDimensionsChange',
				heightChange: 'onDimensionsChange'
			} );
			this.resetMapButton.connect( this, { click: 'resetMapPosition' } );

			this.dimensionsField.toggle( !inline );

			// TODO: Support block/inline conversion

			this.$resetMapButtonContainer.toggle( !!this.selectedNode );

			this.dimensions.setDimensions( this.scalable.getCurrentDimensions() );

			this.updateActions();
		}, this );
};

/**
 * Setup the map control
 */
ve.ui.MWMapsDialog.prototype.setupMap = function () {
	var dialog = this;

	if ( this.map ) {
		return;
	}

	mw.loader.using( 'ext.kartographer.editor' ).then( function () {
		var geoJsonLayer, drawControl,
			defaultShapeOptions = { shapeOptions: L.mapbox.simplestyle.style( {} ) },
			mapPosition = dialog.getInitialMapPosition();

		// TODO: Support 'style' editing
		dialog.map = kartobox.map( {
			container: dialog.$map[ 0 ],
			center: mapPosition.center,
			zoom: mapPosition.zoom
		} );

		dialog.map.doWhenReady( function ()  {

			dialog.updateGeoJson();
			dialog.onDimensionsChange();
			dialog.resetMapPosition();

			// if geojson and no center, we need the map to automatically
			// position itself when the feature layer is added.
			if ( dialog.input.getValue() && !mapPosition.center ) {
				dialog.map.on( 'layeradd', function () {
					var mwData = dialog.selectedNode && dialog.selectedNode.getAttribute( 'mw' ),
						mwAttrs = mwData && mwData.attrs || {},
						position;

					dialog.map.setView( null, mapPosition.zoom );
					position = dialog.map.getMapPosition();

					// update attributes with current position
					mwAttrs.latitude = position.center.lat;
					mwAttrs.longitude = position.center.lng;
					mwAttrs.zoom = position.zoom;
				} );
			}

			geoJsonLayer = kartoEditing.getKartographerLayer( dialog.map );
			drawControl = new L.Control.Draw( {
				edit: { featureGroup: geoJsonLayer },
				draw: {
					circle: false,
					// TODO: Determine metric preference from locale information
					polyline: defaultShapeOptions,
					polygon: defaultShapeOptions,
					rectangle: defaultShapeOptions,
					marker: { icon: L.mapbox.marker.icon( {} ) }
				}
			} ).addTo( dialog.map );

			function update() {
				// Prevent circular update of map
				dialog.updatingGeoJson = true;
				try {
					dialog.input.setValue( JSON.stringify( geoJsonLayer.toGeoJSON(), null, '  ' ) );
				} finally {
					dialog.updatingGeoJson = false;
				}
				dialog.updateActions();
			}

			function created( e ) {
				e.layer.addTo( geoJsonLayer );
				update();
			}

			dialog.map
				.on( 'draw:edited', update )
				.on( 'draw:deleted', update )
				.on( 'draw:created', created );

		} );
	} );
};
/**
 * Formats center if valid.
 *
 * @param {string|number} latitude
 * @param {string|number} longitude
 * @return {Array|undefined}
 * @private
 */
function validCenter( latitude, longitude ) {
	latitude = +latitude;
	longitude = +longitude;

	if ( !isNaN( latitude ) && !isNaN( longitude ) ) {
		return [ latitude, longitude ];
	}
}

/**
 * Formats zoom if valid.
 *
 * @param {string|number} zoom
 * @return {number|undefined}
 * @private
 */
function validZoom( zoom ) {
	zoom = +zoom;

	if ( !isNaN( zoom ) ) {
		return zoom;
	}
}

/**
 * Get the initial map position (coordinates and zoom level)
 *
 * @return {Object} Object containing latitude, longitude and zoom
 */
ve.ui.MWMapsDialog.prototype.getInitialMapPosition = function () {
	var mwData = this.selectedNode && this.selectedNode.getAttribute( 'mw' ),
		mwAttrs = mwData && mwData.attrs || {},
		center = validCenter( mwAttrs.latitude, mwAttrs.longitude ),
		zoom = validZoom( mwAttrs.zoom );

	return {
		center: center,
		zoom: zoom
	};
};

/**
 * Update the GeoJSON layer from the current input state
 */
ve.ui.MWMapsDialog.prototype.updateGeoJson = function () {
	var self = this;

	if ( !this.map || this.updatingGeoJson ) {
		return;
	}

	kartoEditing.updateKartographerLayer( this.map, this.input.getValue() )
		.done( function () {
			self.input.setValidityFlag( true );
		} )
		.fail( function () {
			self.input.setValidityFlag( false );
		} )
		.always( function () {
			self.updateActions();
		} );
};

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.getTeardownProcess = function ( data ) {
	return ve.ui.MWMapsDialog.super.prototype.getTeardownProcess.call( this, data )
		.first( function () {
			// Events
			this.input.disconnect( this );
			this.dimensions.disconnect( this );
			this.resetMapButton.disconnect( this );

			this.dimensions.clear();
			if ( this.map ) {
				this.map.remove();
				this.map = null;
			}
		}, this );
};

/* Registration */

ve.ui.windowFactory.register( ve.ui.MWMapsDialog );
<commit_msg>Wait for transitions before resetting start map position<commit_after>/*!
 * VisualEditor UserInterface MWMapsDialog class.
 *
 * @copyright 2011-2015 VisualEditor Team and others; see AUTHORS.txt
 * @license The MIT License (MIT); see LICENSE.txt
 */
/* globals require */
var kartobox = require( 'ext.kartographer.box' ),
	kartoEditing = require( 'ext.kartographer.editing' );

/**
 * Dialog for editing MW maps.
 *
 * @class
 * @extends ve.ui.MWExtensionDialog
 *
 * @constructor
 * @param {Object} [config] Configuration options
 */
ve.ui.MWMapsDialog = function VeUiMWMapsDialog() {
	// Parent constructor
	ve.ui.MWMapsDialog.super.apply( this, arguments );

	this.updateGeoJson = $.debounce( 300, $.proxy( this.updateGeoJson, this ) );
	this.resetMapPosition = $.debounce( 300, $.proxy( this.resetMapPosition, this ) );
};

/* Inheritance */

OO.inheritClass( ve.ui.MWMapsDialog, ve.ui.MWExtensionDialog );

/* Static Properties */

ve.ui.MWMapsDialog.static.name = 'mwMaps';

ve.ui.MWMapsDialog.static.title = OO.ui.deferMsg( 'visualeditor-mwmapsdialog-title' );

ve.ui.MWMapsDialog.static.size = 'larger';

ve.ui.MWMapsDialog.static.allowedEmpty = true;

ve.ui.MWMapsDialog.static.modelClasses = [ ve.dm.MWMapsNode, ve.dm.MWInlineMapsNode ];

/* Methods */

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.initialize = function () {
	var panel;

	// Parent method
	ve.ui.MWMapsDialog.super.prototype.initialize.call( this );

	this.$mapContainer = $( '<div>' ).addClass( 've-ui-mwMapsDialog-mapWidget' );
	this.$map = $( '<div>' ).appendTo( this.$mapContainer );
	this.map = null;
	this.scalable = null;
	this.updatingGeoJson = false;

	this.dimensions = new ve.ui.DimensionsWidget();

	this.input = new ve.ui.MWAceEditorWidget( {
		multiline: true,
		autosize: true,
		maxRows: 10,
		classes: [ 've-ui-mwMapsDialog-geoJSONWidget' ]
	} )
		.setLanguage( 'json' )
		.toggleLineNumbers( false )
		.setRTL( false );

	this.resetMapButton = new OO.ui.ButtonWidget( {
		label: ve.msg( 'visualeditor-mwmapsdialog-reset-map' )
	} );

	panel = new OO.ui.PanelLayout( {
		padded: true,
		expanded: false
	} );

	this.dimensionsField = new OO.ui.FieldLayout( this.dimensions, {
		align: 'right',
		label: ve.msg( 'visualeditor-mwmapsdialog-size' )
	} );

	this.$resetMapButtonContainer = $( '<div>' ).addClass( 've-ui-mwMapsDialog-resetMapButton' );

	this.geoJsonField = new OO.ui.FieldLayout( this.input, {
		align: 'top',
		label: ve.msg( 'visualeditor-mwmapsdialog-geojson' )
	} );

	panel.$element.append(
		this.dimensionsField.$element,
		this.$mapContainer,
		this.$resetMapButtonContainer.append( this.resetMapButton.$element ),
		this.geoJsonField.$element
	);
	this.$body.append( panel.$element );
};

/**
 * Handle change events on the dimensions widget
 *
 * @param {string} newValue
 */
ve.ui.MWMapsDialog.prototype.onDimensionsChange = function () {
	var dimensions, center;

	if ( !this.map ) {
		return;
	}

	dimensions = this.scalable.getBoundedDimensions(
		this.dimensions.getDimensions()
	);
	center = this.map && this.map.getCenter();

	// Set container width for centering
	this.$mapContainer.css( { width: dimensions.width } );
	this.$map.css( dimensions );
	this.updateSize();

	if ( center ) {
		this.map.setView( center );
	}
	this.map.invalidateSize();
	this.updateActions();
};

/**
 * Reset the map's position
 */
ve.ui.MWMapsDialog.prototype.resetMapPosition = function () {
	var position,
		dialog = this;

	if ( !this.map ) {
		return;
	}

	position = this.getInitialMapPosition();
	this.map.setView( position.center, position.zoom );

	this.updateActions();
	this.resetMapButton.setDisabled( true );

	this.map.once( 'moveend', function () {
		dialog.updateActions();
		dialog.resetMapButton.setDisabled( false );
	} );
};

/**
 * Update action states
 */
ve.ui.MWMapsDialog.prototype.updateActions = function () {
	var newMwData, modified,
		mwData = this.selectedNode && this.selectedNode.getAttribute( 'mw' );

	if ( mwData ) {
		newMwData = ve.copy( mwData );
		this.updateMwData( newMwData );
		modified = !ve.compare( mwData, newMwData );
	} else {
		modified = true;
	}
	this.actions.setAbilities( { done: modified } );
};

/**
 * @inheritdoc ve.ui.MWExtensionWindow
 */
ve.ui.MWMapsDialog.prototype.insertOrUpdateNode = function () {
	// Parent method
	ve.ui.MWMapsDialog.super.prototype.insertOrUpdateNode.apply( this, arguments );

	// Update scalable
	this.scalable.setCurrentDimensions(
		this.scalable.getBoundedDimensions(
			this.dimensions.getDimensions()
		)
	);
};

/**
 * @inheritdoc ve.ui.MWExtensionWindow
 */
ve.ui.MWMapsDialog.prototype.updateMwData = function ( mwData ) {
	var center, latitude, longitude, zoom,
		dimensions = this.scalable.getBoundedDimensions(
			this.dimensions.getDimensions()
		);

	// Parent method
	ve.ui.MWMapsDialog.super.prototype.updateMwData.call( this, mwData );

	if ( this.map ) {
		center = this.map.getCenter();
		latitude = center.lat;
		longitude = center.lng;
		zoom = this.map.getZoom();
	} else {
		// Map not loaded in insert, can't insert
		return;
	}
	mwData.attrs.latitude = latitude.toString();
	mwData.attrs.longitude = longitude.toString();
	mwData.attrs.zoom = zoom.toString();
	if ( !( this.selectedNode instanceof ve.dm.MWInlineMapsNode ) ) {
		mwData.attrs.width = dimensions.width.toString();
		mwData.attrs.height = dimensions.height.toString();
	}
};

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.getReadyProcess = function ( data ) {
	return ve.ui.MWMapsDialog.super.prototype.getReadyProcess.call( this, data )
		.next( function () {
			this.setupMap();
		}, this );
};

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.getSetupProcess = function ( data ) {
	data = data || {};
	return ve.ui.MWMapsDialog.super.prototype.getSetupProcess.call( this, data )
		.next( function () {
			var inline = this.selectedNode instanceof ve.dm.MWInlineMapsNode;

			this.input.clearUndoStack();

			this.actions.setMode( this.selectedNode ? 'edit' : 'insert' );

			if ( this.selectedNode && !inline ) {
				this.scalable = this.selectedNode.getScalable();
			} else {
				this.scalable = ve.dm.MWMapsNode.static.createScalable(
					inline ?
					{ width: 850, height: 400 } :
					{ width: 400, height: 300 }
				);
			}

			// Events
			this.input.connect( this, {
				change: 'updateGeoJson',
				resize: 'updateSize'
			} );
			this.dimensions.connect( this, {
				widthChange: 'onDimensionsChange',
				heightChange: 'onDimensionsChange'
			} );
			this.resetMapButton.connect( this, { click: 'resetMapPosition' } );

			this.dimensionsField.toggle( !inline );

			// TODO: Support block/inline conversion

			this.$resetMapButtonContainer.toggle( !!this.selectedNode );

			this.dimensions.setDimensions( this.scalable.getCurrentDimensions() );

			this.updateActions();
		}, this );
};

/**
 * Setup the map control
 */
ve.ui.MWMapsDialog.prototype.setupMap = function () {
	var dialog = this;

	if ( this.map ) {
		return;
	}

	mw.loader.using( 'ext.kartographer.editor' ).then( function () {
		var geoJsonLayer, drawControl,
			defaultShapeOptions = { shapeOptions: L.mapbox.simplestyle.style( {} ) },
			mapPosition = dialog.getInitialMapPosition();

		// TODO: Support 'style' editing
		dialog.map = kartobox.map( {
			container: dialog.$map[ 0 ],
			center: mapPosition.center,
			zoom: mapPosition.zoom
		} );

		dialog.map.doWhenReady( function ()  {

			dialog.updateGeoJson();
			dialog.onDimensionsChange();
			// Wait for dialog to resize as this triggers map move events
			setTimeout( function () {
				dialog.resetMapPosition();
			}, OO.ui.theme.getDialogTransitionDuration() );

			// if geojson and no center, we need the map to automatically
			// position itself when the feature layer is added.
			if ( dialog.input.getValue() && !mapPosition.center ) {
				dialog.map.on( 'layeradd', function () {
					var mwData = dialog.selectedNode && dialog.selectedNode.getAttribute( 'mw' ),
						mwAttrs = mwData && mwData.attrs || {},
						position;

					dialog.map.setView( null, mapPosition.zoom );
					position = dialog.map.getMapPosition();

					// update attributes with current position
					mwAttrs.latitude = position.center.lat;
					mwAttrs.longitude = position.center.lng;
					mwAttrs.zoom = position.zoom;
				} );
			}

			geoJsonLayer = kartoEditing.getKartographerLayer( dialog.map );
			drawControl = new L.Control.Draw( {
				edit: { featureGroup: geoJsonLayer },
				draw: {
					circle: false,
					// TODO: Determine metric preference from locale information
					polyline: defaultShapeOptions,
					polygon: defaultShapeOptions,
					rectangle: defaultShapeOptions,
					marker: { icon: L.mapbox.marker.icon( {} ) }
				}
			} ).addTo( dialog.map );

			function update() {
				// Prevent circular update of map
				dialog.updatingGeoJson = true;
				try {
					dialog.input.setValue( JSON.stringify( geoJsonLayer.toGeoJSON(), null, '  ' ) );
				} finally {
					dialog.updatingGeoJson = false;
				}
				dialog.updateActions();
			}

			function created( e ) {
				e.layer.addTo( geoJsonLayer );
				update();
			}

			dialog.map
				.on( 'draw:edited', update )
				.on( 'draw:deleted', update )
				.on( 'draw:created', created );

		} );
	} );
};
/**
 * Formats center if valid.
 *
 * @param {string|number} latitude
 * @param {string|number} longitude
 * @return {Array|undefined}
 * @private
 */
function validCenter( latitude, longitude ) {
	latitude = +latitude;
	longitude = +longitude;

	if ( !isNaN( latitude ) && !isNaN( longitude ) ) {
		return [ latitude, longitude ];
	}
}

/**
 * Formats zoom if valid.
 *
 * @param {string|number} zoom
 * @return {number|undefined}
 * @private
 */
function validZoom( zoom ) {
	zoom = +zoom;

	if ( !isNaN( zoom ) ) {
		return zoom;
	}
}

/**
 * Get the initial map position (coordinates and zoom level)
 *
 * @return {Object} Object containing latitude, longitude and zoom
 */
ve.ui.MWMapsDialog.prototype.getInitialMapPosition = function () {
	var mwData = this.selectedNode && this.selectedNode.getAttribute( 'mw' ),
		mwAttrs = mwData && mwData.attrs || {},
		center = validCenter( mwAttrs.latitude, mwAttrs.longitude ),
		zoom = validZoom( mwAttrs.zoom );

	return {
		center: center,
		zoom: zoom
	};
};

/**
 * Update the GeoJSON layer from the current input state
 */
ve.ui.MWMapsDialog.prototype.updateGeoJson = function () {
	var self = this;

	if ( !this.map || this.updatingGeoJson ) {
		return;
	}

	kartoEditing.updateKartographerLayer( this.map, this.input.getValue() )
		.done( function () {
			self.input.setValidityFlag( true );
		} )
		.fail( function () {
			self.input.setValidityFlag( false );
		} )
		.always( function () {
			self.updateActions();
		} );
};

/**
 * @inheritdoc
 */
ve.ui.MWMapsDialog.prototype.getTeardownProcess = function ( data ) {
	return ve.ui.MWMapsDialog.super.prototype.getTeardownProcess.call( this, data )
		.first( function () {
			// Events
			this.input.disconnect( this );
			this.dimensions.disconnect( this );
			this.resetMapButton.disconnect( this );

			this.dimensions.clear();
			if ( this.map ) {
				this.map.remove();
				this.map = null;
			}
		}, this );
};

/* Registration */

ve.ui.windowFactory.register( ve.ui.MWMapsDialog );
<|endoftext|>