<commit_before>/*
Add this file to $(ipython locate)/nbextensions/vim.js
And load it with:

require(["nbextensions/vim"], function (vim_extension) {
    console.log('vim extension loaded');
    vim_extension.load_extension();
});

*/
define( function () {
    var token_name = "vim_github_token";

    var load_extension = function () {
        $([IPython.events]).on("notebook_loaded.Notebook", function () {
          console.log("notebook loaded event");
        });
    };

    return {
        load_extension : load_extension,
    };
});

// plug in so :w saves
CodeMirror.commands.save = function(cm) {
  IPython.notebook.save_notebook();
}

// Monkey patch: KeyboardManager.handle_keydown
// Diff: disable this handler

IPython.KeyboardManager.prototype.handle_keydown = function (event) {
  var cell = IPython.notebook.get_selected_cell();
  if(cell instanceof IPython.TextCell) {
    if(cell.mode == 'command' && event.type == 'keydown') {
      // switch IPython.notebook to this.notebook if Cells get notebook reference
      ret = IPython.VIM.keyDown(IPython.notebook, event);
      return ret;
    }
  }
  return;
}

// Monkey patch: KeyboardManager.register_events
// Diff: disable this handler
IPython.KeyboardManager.prototype.register_events = function (e) {
  return;
}
// Monkey patch insert_cell_below
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_below = function (type, index) {
    index = this.index_or_selected(index);
    var cell = this.insert_cell_at_index(type, index+1);
    this.select(this.find_cell_index(cell));
    return cell;
};

// Monkey patch insert_cell_above
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_above = function (type, index) {
    index = this.index_or_selected(index);
    var cell = this.insert_cell_at_index(type, index);
    this.select(this.find_cell_index(cell));
    return cell;
};

// Monkey patch: execute_cell
// Diff: don't switch to command mode
IPython.Notebook.prototype.execute_cell = function () {
    var cell = this.get_selected_cell();
    var cell_index = this.find_cell_index(cell);
    cell.execute();
    this.set_dirty(true);
};

// Focus editor on select
IPython.CodeCell.prototype.select = function () {
    var cont = IPython.Cell.prototype.select.apply(this);
    if (cont) {
        this.code_mirror.refresh();
        this.focus_editor();
        this.auto_highlight();
    }
    return cont;
};

IPython.CodeCell.prototype.handle_keyevent = function (editor, event) {

    // console.log('CM', this.mode, event.which, event.type)
        var ret = this.handle_codemirror_keyevent(editor, event);
        if(ret) {
          return ret;
        }
        if(event.type == 'keydown') {
          // switch IPython.notebook to this.notebook if Cells get notebook reference
          ret = IPython.VIM.keyDown(IPython.notebook, event);
          return ret;
        }
        return false;
};

// Override TextCell keydown
// Really just here to handle the render/editing of text cells
// Might need to consider also using codemirror keyevent
IPython.TextCell.prototype.handle_keyevent = function (editor, event) {
      var ret = this.handle_codemirror_keyevent(editor, event);
      if(ret) {
        return ret;
      }
      if( event.type == 'keydown') {
        ret = IPython.VIM.keyDown(IPython.notebook, event);
        return ret;
      }
      return false;
}

IPython.Notebook.prototype.setVIMode = function (mode) {
  var cell = this.get_selected_cell();
  cm = cell.code_mirror;
  if(cm) {
    if(mode == 'INSERT') {
      CodeMirror.keyMap.vim.I(cm);
    }
  }
}

var IPython = (function (IPython) {

  var NormalMode = {};
  var InsertMode = {};

  var VIM = function() {;};

  VIM.prototype.keyDown = function(that, event) {
    var cell = that.get_selected_cell();
    var vim_mode = cell.code_mirror.getOption('keyMap');

    ret = false;

    if(vim_mode == 'vim') {
      ret = NormalMode.keyDown(that, event);
    }

    if(vim_mode == 'vim-insert') {
      ret = InsertMode.keyDown(that, event);
    }

    if(ret) {
      event.preventDefault();
      return true;
    }
    return false;
  };

  NormalMode.keyDown = function(that, event) {
    var cell = that.get_selected_cell();
    var cell_type = cell.cell_type;
    var textcell = cell instanceof IPython.TextCell;

    // ` : enable console
    if (event.which === 192) {
      $(IPython.console_book.element).toggle();
      IPython.console_book.focus_selected();
      return true;
    }

    // Meta S: save_notebook
    if ((event.ctrlKey || event.metaKey) && event.keyCode==83) {
      that.save_notebook();
      event.preventDefault();
      return false;
    }

    // K: up cell
    if (event.which === 75 && (event.shiftKey || event.metaKey))
    {
        that.select_prev();
        return true;
    }
    // k: up
    if (event.which === 75 && !event.shiftKey)
    {
      // textcell. Treat as one line item when not rendered
      if(textcell && cell.rendered) {
          that.select_prev();
          return true;
      }
        var cursor = cell.code_mirror.getCursor();
        if (cursor.line === 0) {
          that.select_prev();
          var new_cell = that.get_selected_cell();
          if(new_cell.code_mirror) { // bottom line, same ch position
            var last_line = new_cell.code_mirror.lastLine();
            // NOTE: a current code_mirror bug doesn't respect the new cursor opsition
            // https://github.com/marijnh/CodeMirror/issues/2289
            if(new_cell.code_mirror.state.vim) {
              new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
            }
            new_cell.code_mirror.setCursor(last_line, cursor.ch);
          }
          return true;
        }
        // right now textcell is handled via Document handler prevent the double call
        event.preventDefault();
        event.stopPropagation();
    }
    // J: down cell
    if (event.which === 74 && (event.shiftKey || event.metaKey)) {
        that.select_next();
        return true;
    }
    // j: down
    if (event.which === 74 && !event.shiftKey) {
      // textcell. Treat as one line item when not rendered
      if(textcell && cell.rendered) {
          that.select_next();
          return true;
      }
      var cursor = cell.code_mirror.getCursor();
      var ch = cursor.ch;
      if (cursor.line === (cell.code_mirror.lineCount()-1)) {
        that.select_next();
        var new_cell = that.get_selected_cell();
        if(new_cell.code_mirror) { // bottom line, same ch position
          // NOTE: a current code_mirror bug doesn't respect the new cursor opsition
          // https://github.com/marijnh/CodeMirror/issues/2289
          new_cell.code_mirror.setCursor(0, cursor.ch);
          if(new_cell.code_mirror.state.vim) {
            new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
          }
        }
        // right now textcell is handled via Document handler prevent the double call
        event.preventDefault();
        event.stopPropagation();
        return true;
      };
    }
    // Y: copy cell
    if (event.which === 89 && event.shiftKey) {
        that.copy_cell();
        return true;
    }
    // D: delete cell / cut
    if (event.which === 68 && event.shiftKey) {
        that.cut_cell();
        return true;
    }
    // P: paste cell
    if (event.which === 80 && event.shiftKey) {
        that.paste_cell();
        return true;
    }
    // B: open new cell below
    if (event.which === 66 && event.shiftKey) {
        that.insert_cell_below('code');
        that.setVIMode('INSERT');
        return true;
    }
    // shift+O or apple + O: open new cell below
    // I know this is wrong but i hate hitting A
    if (event.which === 79 && (event.metaKey || event.shiftKey)) {
        that.insert_cell_below('code');
        that.setVIMode('INSERT');
        return true;
    }
    // A: open new cell above
    if (event.which === 65 && event.shiftKey) {
      that.insert_cell_above('code');
      that.setVIMode('INSERT');
      return true;
    }
    // control/apple E: execute (apple - E is easier than shift E)
    if ((event.ctrlKey || event.metaKey) && event.keyCode==69) {
      that.execute_cell();
      return true;
    }
    // E:  execute
    if (event.which === 69 && event.shiftKey) {
      that.execute_cell();
      return true;
    }
    // F: toggle output
    if (event.which === 70 && event.shiftKey) {
      that.toggle_output();
      return true;
    }
    // M: markdown
    if (event.which === 77 && event.shiftKey) {
      that.to_markdown();
      return true;
    }
    // C: codecell
    if (event.which === 77 && event.shiftKey) {
      that.to_code();
      return true;
    }
    // i: insert. only relevant on textcell
    var rendered = cell.rendered;
    if (textcell && rendered && event.which === 73 && !event.shiftKey) {
      cell.edit_mode();
      return false;
    }

    // esc: get out of insert and render textcell
    if (textcell && !rendered && event.which === 27 && !event.shiftKey) {
        cell.render();
        return false;
    }
  };

  InsertMode.keyDown = function(that, event) {
    var cell = that.get_selected_cell();
    var cell_type = cell.cell_type;
    var textcell = cell instanceof IPython.TextCell;

    // control/apple E: execute (apple - E is easier than shift E)
    if ((event.ctrlKey || event.metaKey) && event.keyCode==69) {
      that.execute_cell();
      return true;
    }
    if (event.which === 74 && (event.metaKey)) {
        that.select_next();
        return true;
    }
    if (event.which === 75 && (event.metaKey)) {
        that.select_prev();
        return true;
    }
    // Meta S: save_notebook
    if ((event.ctrlKey || event.metaKey) && event.keyCode==83) {
      that.save_notebook();
      event.preventDefault();
      return false;
    }
  };

  IPython.VIM = new VIM();
  return IPython;

}(IPython));
<commit_msg>BUG: fix crossing up above textcell<commit_after>/*
Add this file to $(ipython locate)/nbextensions/vim.js
And load it with:

require(["nbextensions/vim"], function (vim_extension) {
    console.log('vim extension loaded');
    vim_extension.load_extension();
});

*/
define( function () {
    var token_name = "vim_github_token";

    var load_extension = function () {
        $([IPython.events]).on("notebook_loaded.Notebook", function () {
          console.log("notebook loaded event");
        });
    };

    return {
        load_extension : load_extension,
    };
});

// plug in so :w saves
CodeMirror.commands.save = function(cm) {
  IPython.notebook.save_notebook();
}

// Monkey patch: KeyboardManager.handle_keydown
// Diff: disable this handler

IPython.KeyboardManager.prototype.handle_keydown = function (event) {
  var cell = IPython.notebook.get_selected_cell();
  if(cell instanceof IPython.TextCell) {
    if(cell.mode == 'command' && event.type == 'keydown') {
      // switch IPython.notebook to this.notebook if Cells get notebook reference
      ret = IPython.VIM.keyDown(IPython.notebook, event);
      return ret;
    }
  }
  return;
}

// Monkey patch: KeyboardManager.register_events
// Diff: disable this handler
IPython.KeyboardManager.prototype.register_events = function (e) {
  return;
}
// Monkey patch insert_cell_below
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_below = function (type, index) {
    index = this.index_or_selected(index);
    var cell = this.insert_cell_at_index(type, index+1);
    this.select(this.find_cell_index(cell));
    return cell;
};

// Monkey patch insert_cell_above
// Diff: Select cell after insert
IPython.Notebook.prototype.insert_cell_above = function (type, index) {
    index = this.index_or_selected(index);
    var cell = this.insert_cell_at_index(type, index);
    this.select(this.find_cell_index(cell));
    return cell;
};

// Monkey patch: execute_cell
// Diff: don't switch to command mode
IPython.Notebook.prototype.execute_cell = function () {
    var cell = this.get_selected_cell();
    var cell_index = this.find_cell_index(cell);
    cell.execute();
    this.set_dirty(true);
};

// Focus editor on select
IPython.CodeCell.prototype.select = function () {
    var cont = IPython.Cell.prototype.select.apply(this);
    if (cont) {
        this.code_mirror.refresh();
        this.focus_editor();
        this.auto_highlight();
    }
    return cont;
};

IPython.CodeCell.prototype.handle_keyevent = function (editor, event) {

    // console.log('CM', this.mode, event.which, event.type)
        var ret = this.handle_codemirror_keyevent(editor, event);
        if(ret) {
          return ret;
        }
        if(event.type == 'keydown') {
          // switch IPython.notebook to this.notebook if Cells get notebook reference
          ret = IPython.VIM.keyDown(IPython.notebook, event);
          return ret;
        }
        return false;
};

// Override TextCell keydown
// Really just here to handle the render/editing of text cells
// Might need to consider also using codemirror keyevent
IPython.TextCell.prototype.handle_keyevent = function (editor, event) {
      var ret = this.handle_codemirror_keyevent(editor, event);
      if(ret) {
        return ret;
      }
      if( event.type == 'keydown') {
        ret = IPython.VIM.keyDown(IPython.notebook, event);
        return ret;
      }
      return false;
}

IPython.Notebook.prototype.setVIMode = function (mode) {
  var cell = this.get_selected_cell();
  cm = cell.code_mirror;
  if(cm) {
    if(mode == 'INSERT') {
      CodeMirror.keyMap.vim.I(cm);
    }
  }
}

var IPython = (function (IPython) {

  var NormalMode = {};
  var InsertMode = {};

  var VIM = function() {;};

  VIM.prototype.keyDown = function(that, event) {
    var cell = that.get_selected_cell();
    var vim_mode = cell.code_mirror.getOption('keyMap');

    ret = false;

    if(vim_mode == 'vim') {
      ret = NormalMode.keyDown(that, event);
    }

    if(vim_mode == 'vim-insert') {
      ret = InsertMode.keyDown(that, event);
    }

    if(ret) {
      event.preventDefault();
      return true;
    }
    return false;
  };

  NormalMode.keyDown = function(that, event) {
    var cell = that.get_selected_cell();
    var cell_type = cell.cell_type;
    var textcell = cell instanceof IPython.TextCell;

    // ` : enable console
    if (event.which === 192) {
      $(IPython.console_book.element).toggle();
      IPython.console_book.focus_selected();
      return true;
    }

    // Meta S: save_notebook
    if ((event.ctrlKey || event.metaKey) && event.keyCode==83) {
      that.save_notebook();
      event.preventDefault();
      return false;
    }

    // K: up cell
    if (event.which === 75 && (event.shiftKey || event.metaKey))
    {
        that.select_prev();
        return true;
    }
    // k: up
    if (event.which === 75 && !event.shiftKey)
    {
      // textcell. Treat as one line item when not rendered
      if(textcell && cell.rendered) {
          that.select_prev();
          return true;
      }
        var cursor = cell.code_mirror.getCursor();
        if (cursor.line === 0) {
          that.select_prev();
          var new_cell = that.get_selected_cell();
          if(new_cell.code_mirror) { // bottom line, same ch position
            var last_line = new_cell.code_mirror.lastLine();
            // NOTE: a current code_mirror bug doesn't respect the new cursor opsition
            // https://github.com/marijnh/CodeMirror/issues/2289
            if(new_cell.code_mirror.state.vim) {
              new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
            }
            new_cell.code_mirror.setCursor(last_line, cursor.ch);
          }
        }
        // right now textcell is handled via Document handler prevent the double call
        event.preventDefault();
        event.stopPropagation();
        return true;
    }
    // J: down cell
    if (event.which === 74 && (event.shiftKey || event.metaKey)) {
        that.select_next();
        return true;
    }
    // j: down
    if (event.which === 74 && !event.shiftKey) {
      // textcell. Treat as one line item when not rendered
      if(textcell && cell.rendered) {
          that.select_next();
          return true;
      }
      var cursor = cell.code_mirror.getCursor();
      var ch = cursor.ch;
      if (cursor.line === (cell.code_mirror.lineCount()-1)) {
        that.select_next();
        var new_cell = that.get_selected_cell();
        if(new_cell.code_mirror) { // bottom line, same ch position
          // NOTE: a current code_mirror bug doesn't respect the new cursor opsition
          // https://github.com/marijnh/CodeMirror/issues/2289
          new_cell.code_mirror.setCursor(0, cursor.ch);
          if(new_cell.code_mirror.state.vim) {
            new_cell.code_mirror.state.vim.lastHPos = cursor.ch;
          }
        }
        // right now textcell is handled via Document handler prevent the double call
        event.preventDefault();
        event.stopPropagation();
        return true;
      };
    }
    // Y: copy cell
    if (event.which === 89 && event.shiftKey) {
        that.copy_cell();
        return true;
    }
    // D: delete cell / cut
    if (event.which === 68 && event.shiftKey) {
        that.cut_cell();
        return true;
    }
    // P: paste cell
    if (event.which === 80 && event.shiftKey) {
        that.paste_cell();
        return true;
    }
    // B: open new cell below
    if (event.which === 66 && event.shiftKey) {
        that.insert_cell_below('code');
        that.setVIMode('INSERT');
        return true;
    }
    // shift+O or apple + O: open new cell below
    // I know this is wrong but i hate hitting A
    if (event.which === 79 && (event.metaKey || event.shiftKey)) {
        that.insert_cell_below('code');
        that.setVIMode('INSERT');
        return true;
    }
    // A: open new cell above
    if (event.which === 65 && event.shiftKey) {
      that.insert_cell_above('code');
      that.setVIMode('INSERT');
      return true;
    }
    // control/apple E: execute (apple - E is easier than shift E)
    if ((event.ctrlKey || event.metaKey) && event.keyCode==69) {
      that.execute_cell();
      return true;
    }
    // E:  execute
    if (event.which === 69 && event.shiftKey) {
      that.execute_cell();
      return true;
    }
    // F: toggle output
    if (event.which === 70 && event.shiftKey) {
      that.toggle_output();
      return true;
    }
    // M: markdown
    if (event.which === 77 && event.shiftKey) {
      that.to_markdown();
      return true;
    }
    // C: codecell
    if (event.which === 77 && event.shiftKey) {
      that.to_code();
      return true;
    }
    // i: insert. only relevant on textcell
    var rendered = cell.rendered;
    if (textcell && rendered && event.which === 73 && !event.shiftKey) {
      cell.edit_mode();
      return false;
    }

    // esc: get out of insert and render textcell
    if (textcell && !rendered && event.which === 27 && !event.shiftKey) {
        cell.render();
        return false;
    }
  };

  InsertMode.keyDown = function(that, event) {
    var cell = that.get_selected_cell();
    var cell_type = cell.cell_type;
    var textcell = cell instanceof IPython.TextCell;

    // control/apple E: execute (apple - E is easier than shift E)
    if ((event.ctrlKey || event.metaKey) && event.keyCode==69) {
      that.execute_cell();
      return true;
    }
    if (event.which === 74 && (event.metaKey)) {
        that.select_next();
        return true;
    }
    if (event.which === 75 && (event.metaKey)) {
        that.select_prev();
        return true;
    }
    // Meta S: save_notebook
    if ((event.ctrlKey || event.metaKey) && event.keyCode==83) {
      that.save_notebook();
      event.preventDefault();
      return false;
    }
  };

  IPython.VIM = new VIM();
  return IPython;

}(IPython));
<|endoftext|>


<commit_before>
function iconFromWeatherId(weatherId, iconId) {
  if (weatherId == 801 || weatherId == 802) {
    return 0; // cloudy

  } else if (weatherId > 500 && weatherId < 600) {
    return 1; //heavy rain

  } else if (weatherId == 500 || (weatherId >= 300 && weatherId <=321)) {
    return 2; //light rain

  } else if (weatherId >= 600 && weatherId < 700) {
    return 3; // snow

  } else if ((weatherId >= 200 && weatherId < 300) || weatherId >= 960 && weatherId <= 962) {
    return 4; // lightning

  }  else if (weatherId == 803 || weatherId == 804) {
    return 5; // mostly cloudy

  } else if (weatherId == 904) {
    return 6; //sun

  }else if (weatherId == 800) {
    if (iconId == "01d"){
      return 6 // sun
    }
    if (iconId == "01n"){
      return 7 // moon
    }
  } else if (weatherId == 905 || (weatherId >= 952 && weatherId <= 959)) {
    return 8; // wind

  } else {
    return 9; // other
  }
}
function fetchWeather(latitude, longitude) {
  var response;
  var req = new XMLHttpRequest();
  var tmp = "http://api.openweathermap.org/data/2.5/weather?" + "lat=" + latitude
                                                           + "&lon=" + longitude;
  console.log(tmp);
  req.open('GET', tmp, true);
  req.onload = function(e) {
    if (req.readyState == 4) {
      if(req.status == 200) {
        console.log(req.responseText);
        response = JSON.parse(req.responseText);

        var city = response.name;
        console.log("city:");
        console.log(city);

        var main = response.main;
        var weather = response.weather[0];

        var temperature = Math.round((main.temp - 273.15)*1.8 + 32);
        console.log("temperature:");
        console.log(temperature);

        var type = weather.main;
        console.log("type:");
        console.log(type);

        var icon = iconFromWeatherId(weather.id, weather.icon);
        console.log("icon:");
        console.log(icon);

        Pebble.sendAppMessage({
            "icon":icon,
            "temperature":temperature + "\u00B0",
            "type":type
        });

      } else {
        console.log("Error");
      }
    }
  }
  req.send(null);
}

function locationSuccess(pos) {
  var coordinates = pos.coords;
  fetchWeather(coordinates.latitude, coordinates.longitude);
}

function locationError(err) {
  console.warn('location error (' + err.code + '): ' + err.message);
  Pebble.sendAppMessage({
    "type":"N/A",
    "temperature":"N/A"
  });
}

var locationOptions = { "timeout": 15000, "maximumAge": 60000 };
var initialized = false;

Pebble.addEventListener("ready",
  function(e) {
    console.log("connect!" + e.ready);
    locationWatcher = window.navigator.geolocation.watchPosition(locationSuccess, locationError, locationOptions);
    console.log(e.type);
    initialized = true;
  });

Pebble.addEventListener("appmessage",
  function(e) {
    window.navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
    console.log(e.type);
    console.log(e.payload.temperature);
    console.log("message!");
});

Pebble.addEventListener("webviewclosed",
  function(e) {
    console.log("webview closed");
    console.log(e.type);
    console.log(e.response);
});

Pebble.addEventListener("showConfiguration", function() {
  console.log("showing configuration");
  Pebble.openURL('http://assets.getpebble.com.s3-website-us-east-1.amazonaws.com/pebble-js/configurable.html');
});

Pebble.addEventListener("webviewclosed", function(e) {
  console.log("configuration closed");
  // webview closed
  var options = JSON.parse(decodeURIComponent(e.response));
  console.log("Options = " + JSON.stringify(options));
});
<commit_msg>dummy config page for PebblePanes.<commit_after>
function iconFromWeatherId(weatherId, iconId) {
  if (weatherId == 801 || weatherId == 802) {
    return 0; // cloudy

  } else if (weatherId > 500 && weatherId < 600) {
    return 1; //heavy rain

  } else if (weatherId == 500 || (weatherId >= 300 && weatherId <=321)) {
    return 2; //light rain

  } else if (weatherId >= 600 && weatherId < 700) {
    return 3; // snow

  } else if ((weatherId >= 200 && weatherId < 300) || weatherId >= 960 && weatherId <= 962) {
    return 4; // lightning

  }  else if (weatherId == 803 || weatherId == 804) {
    return 5; // mostly cloudy

  } else if (weatherId == 904) {
    return 6; //sun

  }else if (weatherId == 800) {
    if (iconId == "01d"){
      return 6 // sun
    }
    if (iconId == "01n"){
      return 7 // moon
    }
  } else if (weatherId == 905 || (weatherId >= 952 && weatherId <= 959)) {
    return 8; // wind

  } else {
    return 9; // other
  }
}
function fetchWeather(latitude, longitude) {
  var response;
  var req = new XMLHttpRequest();
  var tmp = "http://api.openweathermap.org/data/2.5/weather?" + "lat=" + latitude
                                                           + "&lon=" + longitude;
  console.log(tmp);
  req.open('GET', tmp, true);
  req.onload = function(e) {
    if (req.readyState == 4) {
      if(req.status == 200) {
        console.log(req.responseText);
        response = JSON.parse(req.responseText);

        var city = response.name;
        console.log("city:");
        console.log(city);

        var main = response.main;
        var weather = response.weather[0];

        var temperature = Math.round((main.temp - 273.15)*1.8 + 32);
        console.log("temperature:");
        console.log(temperature);

        var type = weather.main;
        console.log("type:");
        console.log(type);

        var icon = iconFromWeatherId(weather.id, weather.icon);
        console.log("icon:");
        console.log(icon);

        Pebble.sendAppMessage({
            "icon":icon,
            "temperature":temperature + "\u00B0",
            "type":type
        });

      } else {
        console.log("Error");
      }
    }
  }
  req.send(null);
}

function locationSuccess(pos) {
  var coordinates = pos.coords;
  fetchWeather(coordinates.latitude, coordinates.longitude);
}

function locationError(err) {
  console.warn('location error (' + err.code + '): ' + err.message);
  Pebble.sendAppMessage({
    "type":"N/A",
    "temperature":"N/A"
  });
}

var locationOptions = { "timeout": 15000, "maximumAge": 60000 };
var initialized = false;

Pebble.addEventListener("ready",
  function(e) {
    console.log("connect!" + e.ready);
    locationWatcher = window.navigator.geolocation.watchPosition(locationSuccess, locationError, locationOptions);
    console.log(e.type);
    initialized = true;
  });

Pebble.addEventListener("appmessage",
  function(e) {
    window.navigator.geolocation.getCurrentPosition(locationSuccess, locationError, locationOptions);
    console.log(e.type);
    console.log(e.payload.temperature);
    console.log("message!");
});

Pebble.addEventListener("webviewclosed",
  function(e) {
    console.log("webview closed");
    console.log(e.type);
    console.log(e.response);
});

Pebble.addEventListener("showConfiguration", function() {
  console.log("showing configuration");
  Pebble.openURL('http://www.google.com');
});

Pebble.addEventListener("webviewclosed", function(e) {
  console.log("configuration closed");
  // webview closed
  var options = JSON.parse(decodeURIComponent(e.response));
  console.log("Options = " + JSON.stringify(options));
});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         NFOrce IMDB
// @namespace    http://www.nfohump.com/
// @version      1.1.0
// @description  Show inline IMDB.com ratings and movie details
// @author       https://github.com/SirPumpAction
// @match        http://*.nfohump.com/forum/*
// @match        https://*.nfohump.com/forum/*
// @grant        GM_addStyle
// @downloadURL  https://github.com/SirPumpAction/nforce_imdb/raw/master/nforce_imdb.user.js
// @updateURL    https://github.com/SirPumpAction/nforce_imdb/raw/master/nforce_imdb.user.js
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// ==/UserScript==

GM_addStyle("\
.nforating {font-weight: bold; margin-left: 10px; color: #ffa;}\
.nforating > span.details {position: absolute; font-weight: normal; display: inline-block; margin-left: 30px; opacity: 0; pointer-events: all; transition: all 300ms; visibility: hidden;}\
.nforating > span.details > dl {margin:0; background:#ffc; color: #000; padding: 10px; font-family: helvetica, arial; max-width: 300px; box-shadow: 0px 2px 5px 0px #000;}\
.nforating > span.details > dl > dd {margin-bottom: 5px;}\
.nforating > span.details > dl > dt {font-weight: bold;}\
.nforating > span.details > dl > dt a{color: #000;}\
.nforating > span.det {text-shadow:0px 1px 2px #000;    padding: 0px 5px;}\
.nforating:hover > span.details {opacity: 1; visibility: visible;}\
");

function setColor(p){
    p=p<0?0:p>100?100:p;
    var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);
    var green = p>50 ? 255 : Math.round((p)*5.12);
    return "rgb(" + red + "," + green + ",0)";
}

$('a.nav[href*="imdb.com/title/"]').each(function(){
    var $link = $(this);

    var href = $link.attr('href');

    var ttid = href.match(/imdb\.com\/title\/(\w*)/i);

    if (ttid){
        var fetch = false;
        var storageid = "nforce." + ttid[1];
        if (!localStorage[storageid])
            fetch = true;
        else
            if (Date.now() - (JSON.parse(localStorage[storageid])).date > 14400000) //updates every 4 hours
                fetch = true;

        if (fetch) {
            $link.after("loading...");
            $.getJSON("http://www.omdbapi.com/?i=" + ttid[1] + "&plot=short&r=json&random="+Math.round(Math.random()*100000), function( data ) {
                data.date = Date.now();
                localStorage["nforce."+ttid[1]] = JSON.stringify(data);
                renderData(data, $link);
            });
        } else {
            renderData(JSON.parse(localStorage["nforce."+ttid[1]]), $link);
        }
    }
});

function forceRefresh(){
    localStorage.clear();
    document.location.reload();
}

function renderData(data, $link){
    $link.next('span.nforating').remove();

    var $kvp = $('
');
    $.each( data, function( key, val ) {
        switch (key.toLowerCase()) {
            case "poster":
                $kvp.prepend("

► Watch online(beta) - Click on \"Reklamı geç\"
");
                if (val!='N/A')
                    $kvp.prepend( "
Poster link (opens in new tab)
" );
                break;
            case "date":
                var $forceRefresh = $("<button>Force refresh</button>");
                $forceRefresh.on('click', function() {forceRefresh()});
                var $dd = $("
" + (new Date(val)).toLocaleString() + "
");
                $dd.append($forceRefresh);

                $kvp.append( "
Last updated on
" );
                $kvp.append( $dd);
                break;
            default:
                $kvp.append( "
" + key + "

" + val + "
" );
                break;
        }
    });
    $kvp.prepend( "
NFOrce IMDB by SirPumpAction

" );

    var $span = $('');

    var $rating = $('');
    $rating.addClass('nforating');

    $rating.html('[' + data.imdbRating + ', ' + data.Genre + ']');

    $span.append($kvp);

    $rating.prepend($span);

    $link.after($rating);
}
<commit_msg>Update nforce_imdb.user.js<commit_after>// ==UserScript==
// @name         NFOrce IMDB
// @namespace    http://www.nfohump.com/
// @version      1.1.1
// @description  Show inline IMDB.com ratings and movie details
// @author       https://github.com/SirPumpAction
// @match        http://*.nfohump.com/forum/*
// @match        https://*.nfohump.com/forum/*
// @grant        GM_addStyle
// @downloadURL  https://github.com/SirPumpAction/nforce_imdb/raw/master/nforce_imdb.user.js
// @updateURL    https://github.com/SirPumpAction/nforce_imdb/raw/master/nforce_imdb.user.js
// @require      http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// ==/UserScript==

GM_addStyle("\
.nforating {font-weight: bold; margin-left: 10px; color: #ffa;}\
.nforating > span.details {position: absolute; font-weight: normal; display: inline-block; margin-left: 30px; opacity: 0; pointer-events: all; transition: all 300ms; visibility: hidden;}\
.nforating > span.details > dl {margin:0; background:#ffc; color: #000; padding: 10px; font-family: helvetica, arial; max-width: 300px; box-shadow: 0px 2px 5px 0px #000;}\
.nforating > span.details > dl > dd {margin-bottom: 5px;}\
.nforating > span.details > dl > dt {font-weight: bold;}\
.nforating > span.details > dl > dt a{color: #000;}\
.nforating > span.det {text-shadow:0px 1px 2px #000;    padding: 0px 5px;}\
.nforating:hover > span.details {opacity: 1; visibility: visible;}\
");

function setColor(p){
    p=p<0?0:p>100?100:p;
    var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);
    var green = p>50 ? 255 : Math.round((p)*5.12);
    return "rgb(" + red + "," + green + ",0)";
}

$('a.nav[href*="imdb.com/title/"]').each(function(){
    var $link = $(this);

    var href = $link.attr('href');

    var ttid = href.match(/imdb\.com\/title\/(\w*)/i);

    if (ttid){
        var fetch = false;
        var storageid = "nforce." + ttid[1];
        if (!localStorage[storageid])
            fetch = true;
        else
            if (Date.now() - (JSON.parse(localStorage[storageid])).date > 14400000) //updates every 4 hours
                fetch = true;

        if (fetch) {
            $link.after("loading...");
            $.getJSON("http://www.omdbapi.com/?i=" + ttid[1] + "&plot=short&r=json&random="+Math.round(Math.random()*100000), function( data ) {
                data.date = Date.now();
                localStorage["nforce."+ttid[1]] = JSON.stringify(data);
                renderData(data, $link);
            });
        } else {
            renderData(JSON.parse(localStorage["nforce."+ttid[1]]), $link);
        }
    }
});

function forceRefresh(){
    localStorage.clear();
    document.location.reload();
}

function renderData(data, $link){
    $link.next('span.nforating').remove();

    var $kvp = $('
');
    $.each( data, function( key, val ) {
        switch (key.toLowerCase()) {
            case "poster":
                $kvp.prepend("

► Watch online(beta) - Click on \"Reklamı geç\"
");
                if (val!='N/A')
                    $kvp.prepend( "
Poster link (opens in new tab)
" );
                break;
            case "date":
                var $forceRefresh = $("<button>Force refresh</button>");
                $forceRefresh.on('click', function() {forceRefresh()});
                var $dd = $("
" + (new Date(val)).toLocaleString() + "
");
                $dd.append($forceRefresh);

                $kvp.append( "
Last updated on
" );
                $kvp.append( $dd);
                break;
            default:
                $kvp.append( "
" + key + "

" + val + "
" );
                break;
        }
    });
    $kvp.prepend( "
NFOrce IMDB by SirPumpAction

" );

    var $span = $('');

    var $rating = $('');
    $rating.addClass('nforating');

    $rating.html('[' + data.imdbRating + ', ' + data.Genre + ']');

    $span.append($kvp);

    $rating.prepend($span);

    $link.after($rating);
}
<|endoftext|>


<commit_before>import angular from "angular";
import "ng-redux";
import { actionCreators } from "../../../actions/actions.js";
import postHeaderModule from "../../post-header.js";
import { attach, getIn, get } from "../../../utils.js";
import {
  isOwned,
  isPersona,
  hasChatFacet,
  hasGroupFacet,
} from "../../../need-utils.js";
import { connect2Redux } from "../../../won-utils.js";
import {
  getConnectionUriFromRoute,
  getOwnedNeedByConnectionUri,
} from "../../../selectors/general-selectors.js";

import "style/_suggestpost-viewer.scss";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

          <svg class="suggestpostv__header__icon" ng-if="self.detail.icon">
              <use xlink:href={{self.detail.icon}} href={{self.detail.icon}}></use>
          </svg>
          {{self.detail.label}}

            <won-post-header
                need-uri="self.content"
                timestamp="self.suggestedPost && self.suggestedPost.get('creationDate')"
                hide-image="::false">
            </won-post-header>
            <button class="suggestpostv__content__post__action won-button--outlined thin red"
              ng-if="self.showConnectAction"
              ng-click="self.connectWithPost()">
              Connect
            </button>
            <button class="suggestpostv__content__post__action won-button--outlined thin red"
              ng-if="self.showJoinAction"
              ng-click="self.connectWithPost()">
              Join
            </button>

              {{ self.getInfoText() }}

    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      window.suggestpostv4dbg = this;

      const selectFromState = state => {
        const openedConnectionUri = getConnectionUriFromRoute(state);
        const openedOwnPost =
          openedConnectionUri &&
          getOwnedNeedByConnectionUri(state, openedConnectionUri);
        const connection = getIn(openedOwnPost, [
          "connections",
          openedConnectionUri,
        ]);

        const suggestedPost = getIn(state, ["needs", this.content]);
        const suggestedPostUri = get(suggestedPost, "uri");

        const connectionsOfOpenedOwnPost = get(openedOwnPost, "connections");
        const connectionsBetweenPosts =
          suggestedPostUri &&
          connectionsOfOpenedOwnPost &&
          connectionsOfOpenedOwnPost.filter(
            conn => conn.get("remoteNeedUri") === suggestedPostUri
          );

        const hasConnectionBetweenPosts =
          connectionsBetweenPosts && connectionsBetweenPosts.size > 0;

        const isLoading = state.getIn([
          "process",
          "needs",
          this.content,
          "loading",
        ]);
        const toLoad = state.getIn([
          "process",
          "needs",
          this.content,
          "toLoad",
        ]);
        const failedToLoad = state.getIn([
          "process",
          "needs",
          this.content,
          "failedToLoad",
        ]);

        const fetchedSuggestion = !isLoading && !toLoad && !failedToLoad;

        return {
          suggestedPost,
          openedOwnPost,
          hasChatFacet: hasChatFacet(suggestedPost),
          hasGroupFacet: hasGroupFacet(suggestedPost),
          showConnectAction:
            suggestedPost &&
            fetchedSuggestion &&
            !hasGroupFacet(suggestedPost) &&
            hasChatFacet(suggestedPost) &&
            !hasConnectionBetweenPosts &&
            !isOwned(suggestedPost) &&
            openedOwnPost,
          showJoinAction:
            suggestedPost &&
            fetchedSuggestion &&
            hasGroupFacet(suggestedPost) &&
            !hasChatFacet(suggestedPost) &&
            !hasConnectionBetweenPosts &&
            !isOwned(suggestedPost) &&
            openedOwnPost,
          isLoading,
          toLoad,
          failedToLoad,
          multiSelectType: connection && connection.get("multiSelectType"),
          hasConnectionBetweenPosts,
        };
      };

      connect2Redux(
        selectFromState,
        actionCreators,
        ["self.content", "self.detail"],
        this
      );
    }

    getConnectButtonLabel() {
      return this.hasConnectionBetweenPosts
        ? "Already Connected With Post"
        : "Request";
    }

    getInfoText() {
      if (this.isLoading) {
        return "Loading Suggestion...";
      } else if (this.toLoad) {
        return "Suggestion marked toLoad";
      } else if (this.failedToLoad) {
        return "Failed to load Suggestion";
      }

      if (isPersona(this.suggestedPost)) {
        return isOwned(this.suggestedPost)
          ? "This is one of your Personas"
          : "This is someone elses Persona";
      } else if (this.hasConnectionBetweenPosts) {
        return "Already established a Connection with this Suggestion";
      } else if (isOwned(this.suggestedPost)) {
        return "This is one of your own Needs";
      } else if (this.hasChatFacet && !this.hasGroupFacet) {
        return "Click 'Request' to connect with this Need";
      } else if (!this.hasChatFacet && this.hasGroupFacet) {
        return "Click 'Join' to connect with this Group";
      }

      return "Click on the Icon to view Details";
    }

    connectWithPost() {
      const openedOwnPostUri =
        this.openedOwnPost && this.openedOwnPost.get("uri");
      const suggestedPostUri =
        this.suggestedPost && this.suggestedPost.get("uri");

      if (openedOwnPostUri && suggestedPostUri) {
        this.needs__connect(
          this.openedOwnPost.get("uri"),
          undefined,
          this.suggestedPost.get("uri"),
          "Hey a Friend told me about you, let's chat!"
        );
      } else {
        console.warn(
          "No Connect, either openedOwnPost(Uri) or suggestedPost(Uri) not present"
        );
      }
    }
  }
  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      content: "=",
      detail: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.suggestpostViewer", [postHeaderModule])
  .directive("wonSuggestpostViewer", genComponentConf).name;
<commit_msg>Fixes #2445<commit_after>import angular from "angular";
import "ng-redux";
import { actionCreators } from "../../../actions/actions.js";
import postHeaderModule from "../../post-header.js";
import { attach, getIn, get } from "../../../utils.js";
import {
  isOwned,
  isPersona,
  hasChatFacet,
  hasGroupFacet,
} from "../../../need-utils.js";
import { connect2Redux } from "../../../won-utils.js";
import {
  getConnectionUriFromRoute,
  getOwnedNeedByConnectionUri,
} from "../../../selectors/general-selectors.js";

import "style/_suggestpost-viewer.scss";

const serviceDependencies = ["$ngRedux", "$scope", "$element"];
function genComponentConf() {
  let template = `

          <svg class="suggestpostv__header__icon" ng-if="self.detail.icon">
              <use xlink:href={{self.detail.icon}} href={{self.detail.icon}}></use>
          </svg>
          {{self.detail.label}}

            <won-post-header
                need-uri="self.content"
                timestamp="self.suggestedPost && self.suggestedPost.get('creationDate')"
                hide-image="::false">
            </won-post-header>
            <button class="suggestpostv__content__post__action won-button--outlined thin red"
              ng-if="self.showConnectAction"
              ng-click="self.connectWithPost()">
              Connect
            </button>
            <button class="suggestpostv__content__post__action won-button--outlined thin red"
              ng-if="self.showJoinAction"
              ng-click="self.connectWithPost()">
              Join
            </button>
            <button class="suggestpostv__content__post__action won-button--outlined thin red"
              ng-if="self.hasConnectionBetweenPosts"
              ng-click="self.router__stateGoCurrent({connectionUri: self.establishedConnectionUri})">
              View Chat
            </button>

              {{ self.getInfoText() }}

    `;

  class Controller {
    constructor() {
      attach(this, serviceDependencies, arguments);
      window.suggestpostv4dbg = this;

      const selectFromState = state => {
        const openedConnectionUri = getConnectionUriFromRoute(state);
        const openedOwnPost =
          openedConnectionUri &&
          getOwnedNeedByConnectionUri(state, openedConnectionUri);
        const connection = getIn(openedOwnPost, [
          "connections",
          openedConnectionUri,
        ]);

        const suggestedPost = getIn(state, ["needs", this.content]);
        const suggestedPostUri = get(suggestedPost, "uri");

        const connectionsOfOpenedOwnPost = get(openedOwnPost, "connections");
        const connectionsBetweenPosts =
          suggestedPostUri &&
          connectionsOfOpenedOwnPost &&
          connectionsOfOpenedOwnPost.filter(
            conn => conn.get("remoteNeedUri") === suggestedPostUri
          );

        const hasConnectionBetweenPosts =
          connectionsBetweenPosts && connectionsBetweenPosts.size > 0;

        const isLoading = state.getIn([
          "process",
          "needs",
          this.content,
          "loading",
        ]);
        const toLoad = state.getIn([
          "process",
          "needs",
          this.content,
          "toLoad",
        ]);
        const failedToLoad = state.getIn([
          "process",
          "needs",
          this.content,
          "failedToLoad",
        ]);

        const fetchedSuggestion = !isLoading && !toLoad && !failedToLoad;

        return {
          suggestedPost,
          openedOwnPost,
          hasChatFacet: hasChatFacet(suggestedPost),
          hasGroupFacet: hasGroupFacet(suggestedPost),
          showConnectAction:
            suggestedPost &&
            fetchedSuggestion &&
            !hasGroupFacet(suggestedPost) &&
            hasChatFacet(suggestedPost) &&
            !hasConnectionBetweenPosts &&
            !isOwned(suggestedPost) &&
            openedOwnPost,
          showJoinAction:
            suggestedPost &&
            fetchedSuggestion &&
            hasGroupFacet(suggestedPost) &&
            !hasChatFacet(suggestedPost) &&
            !hasConnectionBetweenPosts &&
            !isOwned(suggestedPost) &&
            openedOwnPost,
          isLoading,
          toLoad,
          failedToLoad,
          multiSelectType: connection && connection.get("multiSelectType"),
          hasConnectionBetweenPosts,
          establishedConnectionUri:
            hasConnectionBetweenPosts &&
            get(connectionsBetweenPosts.first(), "uri"),
        };
      };

      connect2Redux(
        selectFromState,
        actionCreators,
        ["self.content", "self.detail"],
        this
      );
    }

    getConnectButtonLabel() {
      return this.hasConnectionBetweenPosts
        ? "Already Connected With Post"
        : "Request";
    }

    getInfoText() {
      if (this.isLoading) {
        return "Loading Suggestion...";
      } else if (this.toLoad) {
        return "Suggestion marked toLoad";
      } else if (this.failedToLoad) {
        return "Failed to load Suggestion";
      }

      if (isPersona(this.suggestedPost)) {
        return isOwned(this.suggestedPost)
          ? "This is one of your Personas"
          : "This is someone elses Persona";
      } else if (this.hasConnectionBetweenPosts) {
        return "Already established a Connection with this Suggestion";
      } else if (isOwned(this.suggestedPost)) {
        return "This is one of your own Needs";
      } else if (this.hasChatFacet && !this.hasGroupFacet) {
        return "Click 'Request' to connect with this Need";
      } else if (!this.hasChatFacet && this.hasGroupFacet) {
        return "Click 'Join' to connect with this Group";
      }

      return "Click on the Icon to view Details";
    }

    connectWithPost() {
      const openedOwnPostUri =
        this.openedOwnPost && this.openedOwnPost.get("uri");
      const suggestedPostUri =
        this.suggestedPost && this.suggestedPost.get("uri");

      if (openedOwnPostUri && suggestedPostUri) {
        this.needs__connect(
          this.openedOwnPost.get("uri"),
          undefined,
          this.suggestedPost.get("uri"),
          "Hey a Friend told me about you, let's chat!"
        );
      } else {
        console.warn(
          "No Connect, either openedOwnPost(Uri) or suggestedPost(Uri) not present"
        );
      }
    }
  }
  Controller.$inject = serviceDependencies;

  return {
    restrict: "E",
    controller: Controller,
    controllerAs: "self",
    bindToController: true, //scope-bindings -> ctrl
    scope: {
      content: "=",
      detail: "=",
    },
    template: template,
  };
}

export default angular
  .module("won.owner.components.suggestpostViewer", [postHeaderModule])
  .directive("wonSuggestpostViewer", genComponentConf).name;
<|endoftext|>


<commit_before>/**
 * A plugin which enables rendering of math equations inside
 * of reveal.js slides. Essentially a thin wrapper for MathJax.
 *
 * @author Hakim El Hattab
 */
var RevealMath = window.RevealMath || (function(){

	var options = Reveal.getConfig().math || {};
	options.mathjax = options.mathjax || 'http://cdn.mathjax.org/mathjax/latest/MathJax.js';
	options.config = options.config || 'TeX-AMS_HTML-full';

	loadScript( options.mathjax + '?config=' + options.config, function() {

		MathJax.Hub.Config({
			messageStyle: 'none',
			tex2jax: { inlineMath: [['$','$'],['\\(','\\)']] },
			skipStartupTypeset: true
		});

		// Typeset followed by an immediate reveal.js layout since
		// the typesetting process could affect slide height
		MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub ] );
		MathJax.Hub.Queue( Reveal.layout );

		// Reprocess equations in slides when they turn visible
		Reveal.addEventListener( 'slidechanged', function( event ) {

			MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, event.currentSlide ] );

		} );

	} );

	function loadScript( url, callback ) {

		var head = document.querySelector( 'head' );
		var script = document.createElement( 'script' );
		script.type = 'text/javascript';
		script.src = url;

		// Wrapper for callback to make sure it only fires once
		var finish = function() {
			if( typeof callback === 'function' ) {
				callback.call();
				callback = null;
			}
		}

		script.onload = finish;

		// IE
		script.onreadystatechange = function() {
			if ( this.readyState === 'loaded' ) {
				finish();
			}
		}

		// Normal browsers
		head.appendChild( script );

	}

})();
<commit_msg>Allow tex parsing in <code> tags<commit_after>/**
 * A plugin which enables rendering of math equations inside
 * of reveal.js slides. Essentially a thin wrapper for MathJax.
 *
 * @author Hakim El Hattab
 */
var RevealMath = window.RevealMath || (function(){

	var options = Reveal.getConfig().math || {};
	options.mathjax = options.mathjax || 'http://cdn.mathjax.org/mathjax/latest/MathJax.js';
	options.config = options.config || 'TeX-AMS_HTML-full';

	loadScript( options.mathjax + '?config=' + options.config, function() {

		MathJax.Hub.Config({
			messageStyle: 'none',
			tex2jax: {
				inlineMath: [['$','$'],['\\(','\\)']] ,
				skipTags: ['script','noscript','style','textarea','pre']
			},
			skipStartupTypeset: true
		});

		// Typeset followed by an immediate reveal.js layout since
		// the typesetting process could affect slide height
		MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub ] );
		MathJax.Hub.Queue( Reveal.layout );

		// Reprocess equations in slides when they turn visible
		Reveal.addEventListener( 'slidechanged', function( event ) {

			MathJax.Hub.Queue( [ 'Typeset', MathJax.Hub, event.currentSlide ] );

		} );

	} );

	function loadScript( url, callback ) {

		var head = document.querySelector( 'head' );
		var script = document.createElement( 'script' );
		script.type = 'text/javascript';
		script.src = url;

		// Wrapper for callback to make sure it only fires once
		var finish = function() {
			if( typeof callback === 'function' ) {
				callback.call();
				callback = null;
			}
		}

		script.onload = finish;

		// IE
		script.onreadystatechange = function() {
			if ( this.readyState === 'loaded' ) {
				finish();
			}
		}

		// Normal browsers
		head.appendChild( script );

	}

})();
<|endoftext|>


<commit_before>Ext.define('devilry_extjsextras.Router', {
    mixins: {
        observable: 'Ext.util.Observable'
    },
    requires: [
        'Ext.util.History'
    ],

    namedParam: /:\w+/g,
    splatParam: /\*\w+/g,
    escapeRegExp: /[-[\]{}()+?.,\\^$|#\s]/g,

    constructor: function(handler, config) {
        this.handler = handler;
        this.routes = [];
        this.started = false;
        this.suspendedEvents = false;

        this.mixins.observable.constructor.call(this, config);
        this.addEvents(
            /**
             * @event
             * Fired before a successful route.
             * @param route The Route object.
             */
            'beforeroute',

            /**
             * @event
             * Fired after a successful route.
             * @param route The Route object.
             */
            'afterroute'
        );
    },

    add: function(pattern, action) {
        var regex;
        if(Ext.typeOf(pattern) == 'regexp') {
            regex = pattern;
        } else if(Ext.typeOf(pattern) == 'string') {
            regex = this._patternToRegExp(pattern);
        } else {
            throw 'pattern must be regex.';
        }
        this.routes.push({
            regex: regex,
            action: action
        });
    },

    start: function() {
        if(this.started) {
            throw "Can only start() once!";
        }
        this.started = true;
        this._initHistory();
    },

    _trigger: function(token) {
        if(this.suspendedEvents) {
            this.suspendedEvents = false;
            return;
        }
        if(token == null) {
            token = '';
        }
        var routeInfo = {
            token: token,
            url: '#' + token
        };
        for(var index in this.routes) {
            var route = this.routes[index];
            var match = token.match(route.regex);
            if(match) {
                var args = match.slice(1);
                this.fireEvent('beforeroute', this);
                Ext.bind(this.handler[route.action], this.handler, args, true)(Ext.apply(routeInfo, {
                    action: route.action
                }));
                this.fireEvent('afterroute', this);
                return;
            }
        }
        Ext.bind(this.handler['routeNotFound'], this.handler)(Ext.apply(routeInfo, {
            action: 'routeNotFound'
        }));
    },

    _initHistory: function() {
		Ext.util.History.init(this._onHistoryReady, this);
    },

    _onHistoryReady: function(history) {
        this.mon(Ext.util.History, 'change', this._onHistoryChange, this);
        var token = history.getToken();
        if(token == null) {
            token = '';
        }
        this._trigger(token);
    },

    _onHistoryChange: function(token) {
        this._trigger(token);
    },

    /**
     * @private
     * Convert a route string into a regular expression, suitable for matching
     * against the current location hash.
     */
    _patternToRegExp: function(pattern) {
        var regex = pattern.replace(this.escapeRegExp, '\\$&');
        regex = regex.replace(this.namedParam, '([^\/]*)');
        regex = regex.replace(this.splatParam, '(.*?)');
        return new RegExp('^' + regex + '$');
    },

    navigate: function(token) {
        if(token.length > 0 && token.charAt(0) == '#') {
            token = token.substring(1);
        }
        Ext.util.History.add(token);
    },

    setHashWithoutEvent: function(token) {
        if(token == Ext.util.History.getToken()) {
            return;
        }
        this.suspendedEvents = true;
        this.navigate(token);
    }
});
<commit_msg>devilry_extjsextras...Router: Include routeInfo in events.<commit_after>Ext.define('devilry_extjsextras.Router', {
    mixins: {
        observable: 'Ext.util.Observable'
    },
    requires: [
        'Ext.util.History'
    ],

    namedParam: /:\w+/g,
    splatParam: /\*\w+/g,
    escapeRegExp: /[-[\]{}()+?.,\\^$|#\s]/g,

    constructor: function(handler, config) {
        this.handler = handler;
        this.routes = [];
        this.started = false;
        this.suspendedEvents = false;

        this.mixins.observable.constructor.call(this, config);
        this.addEvents(
            /**
             * @event
             * Fired before a successful route.
             * @param route The Route object.
             * @param routeInfo The route info object (the same that is sent to the handlers).
             */
            'beforeroute',

            /**
             * @event
             * Fired after a successful route.
             * @param route The Route object.
             * @param routeInfo The route info object (the same that is sent to the handlers).
             */
            'afterroute'
        );
    },

    add: function(pattern, action) {
        var regex;
        if(Ext.typeOf(pattern) == 'regexp') {
            regex = pattern;
        } else if(Ext.typeOf(pattern) == 'string') {
            regex = this._patternToRegExp(pattern);
        } else {
            throw 'pattern must be regex.';
        }
        this.routes.push({
            regex: regex,
            action: action
        });
    },

    start: function() {
        if(this.started) {
            throw "Can only start() once!";
        }
        this.started = true;
        this._initHistory();
    },

    _trigger: function(token) {
        if(this.suspendedEvents) {
            this.suspendedEvents = false;
            return;
        }
        if(token == null) {
            token = '';
        }
        var routeInfo = {
            token: token,
            url: '#' + token
        };
        for(var index in this.routes) {
            var route = this.routes[index];
            var match = token.match(route.regex);
            if(match) {
                var args = match.slice(1);
                this.fireEvent('beforeroute', this, routeInfo);
                Ext.bind(this.handler[route.action], this.handler, args, true)(Ext.apply(routeInfo, {
                    action: route.action
                }));
                this.fireEvent('afterroute', this, routeInfo);
                return;
            }
        }
        Ext.bind(this.handler['routeNotFound'], this.handler)(Ext.apply(routeInfo, {
            action: 'routeNotFound'
        }));
    },

    _initHistory: function() {
		Ext.util.History.init(this._onHistoryReady, this);
    },

    _onHistoryReady: function(history) {
        this.mon(Ext.util.History, 'change', this._onHistoryChange, this);
        var token = history.getToken();
        if(token == null) {
            token = '';
        }
        this._trigger(token);
    },

    _onHistoryChange: function(token) {
        this._trigger(token);
    },

    /**
     * @private
     * Convert a route string into a regular expression, suitable for matching
     * against the current location hash.
     */
    _patternToRegExp: function(pattern) {
        var regex = pattern.replace(this.escapeRegExp, '\\$&');
        regex = regex.replace(this.namedParam, '([^\/]*)');
        regex = regex.replace(this.splatParam, '(.*?)');
        return new RegExp('^' + regex + '$');
    },

    navigate: function(token) {
        if(token.length > 0 && token.charAt(0) == '#') {
            token = token.substring(1);
        }
        Ext.util.History.add(token);
    },

    setHashWithoutEvent: function(token) {
        if(token == Ext.util.History.getToken()) {
            return;
        }
        this.suspendedEvents = true;
        this.navigate(token);
    }
});
<|endoftext|>


<commit_before>var _ = require('underscore');
var DEBOUNCE_TIME = 350;
var Backbone = require('backbone');

module.exports = Backbone.Model.extend({

  initialize: function (attrs, opts) {
    if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
    if (!opts.basemapsCollection) throw new Error('basemapsCollection is required');

    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._basemapsCollection = opts.basemapsCollection;
    this._disabled = opts.disabled;

    this._generateSchema();
    this._initBinds();
  },

  _initBinds: function () {
    this.bind('change', _.debounce(this._onChange.bind(this), DEBOUNCE_TIME), this);
  },

  _onChange: function () {
    var self = this;

    _.each(this.changed, function (val, key) {
      if (key === 'color') {
        self._updatePlainBasemap(val.color.fixed);
      }
    });
  },

  _updatePlainBasemap: function (color) {
    var plainBasemap = this._basemapsCollection.find(function (mdl) {
      return mdl.get('className') === 'plain';
    });

    plainBasemap.set({
      color: color,
      image: '',
      maxZoom: 32
    });

    this._basemapsCollection.updateSelected(plainBasemap.getValue());
    this._layerDefinitionsCollection.setBaseLayer(plainBasemap.toJSON());
  },

  _generateSchema: function () {
    this.schema = {
      color: {
        type: 'Fill',
        title: _t('editor.layers.basemap.style.color'),
        options: [],
        editorAttrs: {
          color: {
            hidePanes: ['value'],
            disableOpacity: true
          },
          disabled: this._disabled
        },
        validators: ['required']
      }
    };
  }

});
<commit_msg>Fixed problem with plain basemap in the first set<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var DEBOUNCE_TIME = 650;

module.exports = Backbone.Model.extend({

  initialize: function (attrs, opts) {
    if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
    if (!opts.basemapsCollection) throw new Error('basemapsCollection is required');

    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._basemapsCollection = opts.basemapsCollection;
    this._disabled = opts.disabled;

    this._generateSchema();
    this._initBinds();
  },

  _initBinds: function () {
    this._onChange = this._onChange.bind(this);
    this.bind('change', _.debounce(this._onChange, DEBOUNCE_TIME), this);
  },

  _onChange: function () {
    if (this.hasChanged('color')) {
      var color = this.get('color').color.fixed;
      this._updatePlainBasemap(color);
    }
  },

  _updatePlainBasemap: function (color) {
    var plainBasemap = this._basemapsCollection.find(function (mdl) {
      return mdl.get('className') === 'plain';
    });
    var isAlreadySelected = plainBasemap.get('selected');

    plainBasemap.set({
      color: color,
      image: '',
      maxZoom: 32
    });

    if (!isAlreadySelected) {
      this._basemapsCollection.updateSelected(plainBasemap.getValue());
    } else {
      this._layerDefinitionsCollection.setBaseLayer(plainBasemap.toJSON());
    }
  },

  _generateSchema: function () {
    this.schema = {
      color: {
        type: 'Fill',
        title: _t('editor.layers.basemap.style.color'),
        options: [],
        editorAttrs: {
          color: {
            hidePanes: ['value'],
            disableOpacity: true
          },
          disabled: this._disabled
        },
        validators: ['required']
      }
    };
  }

});
<|endoftext|>


<commit_before>/* HEADER */

sessionStorage.clear();

$('.header-button').click(function() {
	if (localStorage.getItem('headerState') === 'small') {
		$('html').removeClass('header-small').addClass('header-large');
		$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
		localStorage.setItem('headerState', 'large');
	} else {
		$('html').removeClass('header-large').addClass('header-small');
		$('.header-button').removeClass('icon-chevron-down').addClass('icon-chevron-up');
		localStorage.setItem('headerState', 'small');
	}
	return false;
});

var setHeaderSize = function() {

	var headerState = localStorage.getItem('headerState');

	var headerButton = function() {
		if (headerState === 'small') {
			$('.header-button').removeClass('icon-chevron-down').addClass('icon-chevron-up');
		} else {
			$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
		}
	}

	$('html').addClass('header-' + headerState);
	headerButton();
}

setHeaderSize();

/* HEADER (end) */

/* MISC */

$('.selectHandschriften').change(function() {
	$('#scriptsSelection option:selected').val();
});

/* MISC (end) */

EditionProperties.applySettings({
									configurationUrl: 'Resources/Public/JavaScript/Archaeo18Config.js',
									maxTags: 20
								});

var showDiv = function(div, link) {
	$('#start_page').css('display', 'none');
	$('#edition_page').css('display', 'none');
	$('#indices_page').css('display', 'none');
	$('#manuscripts_page').css('display', 'none');
	$('#help_page').css('display', 'none');
	$('#terms_page').css('display', 'none');
	$('#databases_page').css('display', 'none');
	$('#acknowledgment_page').css('display', 'none');
	$('#people_page').css('display', 'none');
	$('#imprint_page').css('display', 'none');
	$('#linkstart').removeClass('selected');
	$('#linkedition').removeClass('selected');
	$('#linkindices').removeClass('selected');
	$('#linkhandschriften').removeClass('selected');
	if (typeof link != 'undefined') {
		$(link).addClass('selected');
	}
	$(div).css('display', 'block');
}

var loadTwoColumns = function(div) {
	var mainContentContainer = $(div + ' .maincontent .topics');
	var subNavigationContainer = div + ' .subnav';

	$(subNavigationContainer + ' a').removeClass('selected');

	// listener for clicks on item
	$(subNavigationContainer + ' li').click(function() {
		var scriptId = $('a', this).attr('id')
		if (scriptId != '') {
			$(subNavigationContainer + ' a').each(function() {
				$(this).removeClass("selected");
			});

			$('a', this).addClass('selected');

			var idToMarkdown = function(id) {
				var pathParts = id.split('-');
				var firstPartOfPath = pathParts[0];
				pathParts.splice(0, 1);

				var fileName = firstPartOfPath + '/' + pathParts.join('-');
				return fileName;
			}

			var pageUrl = 'content/' + idToMarkdown(scriptId) + '.html';

			$.ajax({
					   url: pageUrl
				   }).done(function(html) {
							   mainContentContainer[0].innerHTML = html;
						   });
			return false;
		}
	});

	$(subNavigationContainer + ' li:first').click();
}

var loadContent = function(page) {

	var suffix = arguments[1] === 'md' ? 'md' : 'html';
	var pageUrl = 'content/' + page + '/index.' + suffix;

	var content = this;

	content.container = function() {
		return '#' + page + '_page';
	}

	$.ajax({
			   url: pageUrl
		   }).done(function(html) {
					   var container = $(content.container() + ' .wrap');

					   var containerContent;

					   if (suffix === 'md') {
						   containerContent = markdown.toHTML(html);
					   } else {
						   container.html(html);
					   }

					   $('a[href^="http://"]').attr('target', '_blank');
				   });
}

var loadIndices = function() {
	if (!Indices.initialized) {
		Indices.initialize();
	}
	Indices.checkDisplay();
}

var loadScripts = function() {
	if (!Scripts.initialized) {
		Scripts.initialize();
	}
}

var loadEdition = function() {
	if (!EditionGui.initialized) {
		EditionGui.initialize();
	}
	EditionGui.gridLayout();

	var loadFirstDocument = function(data) {
		var doc = new Document(data.title, data.name, data.nameShort, data.preview, data.pages, true);
		doc.imagePath = Util.getImagePath(data.preview);
		var images = [];
		images.push(doc.imagePath .substring(doc.imagePath .lastIndexOf("/") + 1));

		var types = ['text', 'images'];

		for (var i = 0; i < types.length; i++) {
			EditionGui.openDocument(false, doc, 1, types[i], false, '', i);
		}

	};

	var loadDoc = function() {
		var callStorage = 0;

		Util.loadDocuments(function(data) {
			if (callStorage === 0) {
				callStorage++;
				loadFirstDocument(data);

			}
		})
	}

	loadDoc();
}

var addGeoTemCo = function() {
	if (typeof(GeoTemConfig) === 'undefined') {
		var css, js;
		css = '<link rel="stylesheet" href="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/css/geotemco.css" type="text/css" />';
		js = '<script src="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/geotemco-min.js"></script>';
		$('head').append(css + js);
	}
}

var loadPage = function() {
	if (window.location.href.indexOf('?params') != -1) {
		addGeoTemCo();
		showDiv('#edition_page', '#linkedition');
		loadEdition();
	} else
		if (window.location.href.indexOf('?page=') != -1) {
			var data = window.location.href.split('?page=')[1];

			// get path to be loaded from the "CMS"
			var pagePath = data.split('_page')[0].replace('#', '');

			var page = data, link;
			if (data.indexOf('&link=') != -1) {
				var data2 = data.split('&link=');
				page = data2[0];
				link = data2[1];
			}
			showDiv(page, link);
			if (pagePath !== 'edition' && pagePath !== 'indices' && pagePath !== 'manuscripts' && pagePath !== 'terms') {
				loadContent(pagePath);
			}

			if (page.indexOf('edition') != -1) {
				addGeoTemCo();
				loadEdition();
			}
			else
				if (page.indexOf('indices') != -1) {
					addGeoTemCo();
					loadIndices();
				}
				else
					if (page.indexOf('manuscripts') != -1) {
						loadScripts();
					} else
						if (page.indexOf('start') !== -1) {
							showDiv('#start_page', '#linkstart');
							loadContent('start', 'html');
						} else
							if (page.indexOf('help') !== -1) {
								loadTwoColumns('#help_page');
							} else
								if (page.indexOf('terms') !== -1) {
									loadTwoColumns('#terms_page');
								}
		} else {
			showDiv('#start_page', '#linkstart');
			loadContent('start');
		}
}
loadPage();

$('#linkstart').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	addGeoTemCo();
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	addGeoTemCo();
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkstart2').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition2').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkedition3').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices2').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften2').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkhelp').click(function() {
	var divToShow = '#help_page';
	showDiv(divToShow, '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#help_page";
	document.title = 'Archaeo 18: Hilfe';
	loadTwoColumns(divToShow);
});

$('#linkterms').click(function() {
	showDiv('#terms_page', '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#terms_page";
	document.title = 'Archaeo 18: Editionsrichtlinien';
	loadTwoColumns('#terms_page');
});

$('#linkimprint').click(function() {
	showDiv('#imprint_page', '#linkimprint');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#imprint_page";
	document.title = 'Archaeo 18: Impressum';
});

$('#linkdatabases').click(function(e) {
	showDiv('#databases_page', '#linkdatabases', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#databases_page";
	document.title = 'Archaeo 18: Datenbanken und Repositorien';
});

$('#linkacknowledgment').click(function(e) {
	showDiv('#acknowledgment_page', '#linkacknowledgment', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#acknowledgment_page";
	document.title = 'Archaeo 18: Danksagung';
});

$('#linkpeople').click(function(e) {
	showDiv('#people_page', '#linkpeople', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#people_page";
	document.title = 'Archaeo 18: Projekmitarbeiter';
});

window.onhashchange = function() {
	if (location.hash.indexOf('?') != -1) {
		loadPage();
	}
};

var footerWidth = $('#logoPanel').width();
$(window).resize(function() {
	var w = Math.max($(window).width(), $('#editionContainer').width());
	if (footerWidth > w) {
		$('footer').css('width', footerWidth + 'px');
	}
	else {
		$('footer').css('width', w + 'px');
	}
});

var KEYCODE_ESC = 27;
$('body').keyup(function(e) {
	if (e.keyCode == KEYCODE_ESC) {
		$('.easterEgg').toggle();
	}
});<commit_msg>Correct image loading in default view<commit_after>/* HEADER */

sessionStorage.clear();

$('.header-button').click(function() {
	if (localStorage.getItem('headerState') === 'small') {
		$('html').removeClass('header-small').addClass('header-large');
		$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
		localStorage.setItem('headerState', 'large');
	} else {
		$('html').removeClass('header-large').addClass('header-small');
		$('.header-button').removeClass('icon-chevron-down').addClass('icon-chevron-up');
		localStorage.setItem('headerState', 'small');
	}
	return false;
});

var setHeaderSize = function() {

	var headerState = localStorage.getItem('headerState');

	var headerButton = function() {
		if (headerState === 'small') {
			$('.header-button').removeClass('icon-chevron-down').addClass('icon-chevron-up');
		} else {
			$('.header-button').removeClass('icon-chevron-up').addClass('icon-chevron-down');
		}
	}

	$('html').addClass('header-' + headerState);
	headerButton();
}

setHeaderSize();

/* HEADER (end) */

/* MISC */

$('.selectHandschriften').change(function() {
	$('#scriptsSelection option:selected').val();
});

/* MISC (end) */

EditionProperties.applySettings({
									configurationUrl: 'Resources/Public/JavaScript/Archaeo18Config.js',
									maxTags: 20
								});

var showDiv = function(div, link) {
	$('#start_page').css('display', 'none');
	$('#edition_page').css('display', 'none');
	$('#indices_page').css('display', 'none');
	$('#manuscripts_page').css('display', 'none');
	$('#help_page').css('display', 'none');
	$('#terms_page').css('display', 'none');
	$('#databases_page').css('display', 'none');
	$('#acknowledgment_page').css('display', 'none');
	$('#people_page').css('display', 'none');
	$('#imprint_page').css('display', 'none');
	$('#linkstart').removeClass('selected');
	$('#linkedition').removeClass('selected');
	$('#linkindices').removeClass('selected');
	$('#linkhandschriften').removeClass('selected');
	if (typeof link != 'undefined') {
		$(link).addClass('selected');
	}
	$(div).css('display', 'block');
}

var loadTwoColumns = function(div) {
	var mainContentContainer = $(div + ' .maincontent .topics');
	var subNavigationContainer = div + ' .subnav';

	$(subNavigationContainer + ' a').removeClass('selected');

	// listener for clicks on item
	$(subNavigationContainer + ' li').click(function() {
		var scriptId = $('a', this).attr('id')
		if (scriptId != '') {
			$(subNavigationContainer + ' a').each(function() {
				$(this).removeClass("selected");
			});

			$('a', this).addClass('selected');

			var idToMarkdown = function(id) {
				var pathParts = id.split('-');
				var firstPartOfPath = pathParts[0];
				pathParts.splice(0, 1);

				var fileName = firstPartOfPath + '/' + pathParts.join('-');
				return fileName;
			}

			var pageUrl = 'content/' + idToMarkdown(scriptId) + '.html';

			$.ajax({
					   url: pageUrl
				   }).done(function(html) {
							   mainContentContainer[0].innerHTML = html;
						   });
			return false;
		}
	});

	$(subNavigationContainer + ' li:first').click();
}

var loadContent = function(page) {

	var suffix = arguments[1] === 'md' ? 'md' : 'html';
	var pageUrl = 'content/' + page + '/index.' + suffix;

	var content = this;

	content.container = function() {
		return '#' + page + '_page';
	}

	$.ajax({
			   url: pageUrl
		   }).done(function(html) {
					   var container = $(content.container() + ' .wrap');

					   var containerContent;

					   if (suffix === 'md') {
						   containerContent = markdown.toHTML(html);
					   } else {
						   container.html(html);
					   }

					   $('a[href^="http://"]').attr('target', '_blank');
				   });
}

var loadIndices = function() {
	if (!Indices.initialized) {
		Indices.initialize();
	}
	Indices.checkDisplay();
}

var loadScripts = function() {
	if (!Scripts.initialized) {
		Scripts.initialize();
	}
}

var loadEdition = function() {
	if (!EditionGui.initialized) {
		EditionGui.initialize();
	}
	EditionGui.gridLayout();

	var loadFirstDocument = function(data) {
		var doc = new Document(data.title, data.name, data.nameShort, data.preview, data.pages, true);
		doc.imagePath = data.imagePath.replace('REPLACEME', data.title);
		var images = data.images
		//images.push(doc.imagePath .substring(doc.imagePath .lastIndexOf("/") + 1));
		doc.images = images;
		var types = ['text', 'images'];

		for (var i = 0; i < types.length; i++) {
			EditionGui.openDocument(false, doc, 1, types[i], false, '', i);
		}

	};

	var loadDoc = function() {
		var callStorage = 0;

		Util.loadDocuments(function(data) {
			if (callStorage === 0) {
				callStorage++;
				loadFirstDocument(data);

			}
		})
	}

	loadDoc();
}

var addGeoTemCo = function() {
	if (typeof(GeoTemConfig) === 'undefined') {
		var css, js;
		css = '<link rel="stylesheet" href="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/css/geotemco.css" type="text/css" />';
		js = '<script src="ropen/Resources/Public/JavaScript/Libraries/GeoTemCo/geotemco-min.js"></script>';
		$('head').append(css + js);
	}
}

var loadPage = function() {
	if (window.location.href.indexOf('?params') != -1) {
		addGeoTemCo();
		showDiv('#edition_page', '#linkedition');
		loadEdition();
	} else
		if (window.location.href.indexOf('?page=') != -1) {
			var data = window.location.href.split('?page=')[1];

			// get path to be loaded from the "CMS"
			var pagePath = data.split('_page')[0].replace('#', '');

			var page = data, link;
			if (data.indexOf('&link=') != -1) {
				var data2 = data.split('&link=');
				page = data2[0];
				link = data2[1];
			}
			showDiv(page, link);
			if (pagePath !== 'edition' && pagePath !== 'indices' && pagePath !== 'manuscripts' && pagePath !== 'terms') {
				loadContent(pagePath);
			}

			if (page.indexOf('edition') != -1) {
				addGeoTemCo();
				loadEdition();
			}
			else
				if (page.indexOf('indices') != -1) {
					addGeoTemCo();
					loadIndices();
				}
				else
					if (page.indexOf('manuscripts') != -1) {
						loadScripts();
					} else
						if (page.indexOf('start') !== -1) {
							showDiv('#start_page', '#linkstart');
							loadContent('start', 'html');
						} else
							if (page.indexOf('help') !== -1) {
								loadTwoColumns('#help_page');
							} else
								if (page.indexOf('terms') !== -1) {
									loadTwoColumns('#terms_page');
								}
		} else {
			showDiv('#start_page', '#linkstart');
			loadContent('start');
		}
}
loadPage();

$('#linkstart').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	addGeoTemCo();
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	addGeoTemCo();
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkstart2').click(function() {
	showDiv('#start_page', '#linkstart');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#start_page&link=#linkstart";
	document.title = 'Archaeo 18: Start';
});

$('#linkedition2').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkedition3').click(function() {
	showDiv('#edition_page', '#linkedition');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#edition_page&link=#linkedition";
	document.title = 'Archaeo 18: Edition';
	loadEdition();
});

$('#linkindices2').click(function() {
	showDiv('#indices_page', '#linkindices');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#indices_page&link=#linkindices";
	document.title = 'Archaeo 18: Indices';
	loadIndices();
});

$('#linkhandschriften2').click(function() {
	showDiv('#manuscripts_page', '#linkhandschriften');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#manuscripts_page&link=#linkhandschriften";
	document.title = 'Archaeo 18: Handschriften';
	loadScripts();
});

$('#linkhelp').click(function() {
	var divToShow = '#help_page';
	showDiv(divToShow, '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#help_page";
	document.title = 'Archaeo 18: Hilfe';
	loadTwoColumns(divToShow);
});

$('#linkterms').click(function() {
	showDiv('#terms_page', '#linkhelp');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#terms_page";
	document.title = 'Archaeo 18: Editionsrichtlinien';
	loadTwoColumns('#terms_page');
});

$('#linkimprint').click(function() {
	showDiv('#imprint_page', '#linkimprint');
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#imprint_page";
	document.title = 'Archaeo 18: Impressum';
});

$('#linkdatabases').click(function(e) {
	showDiv('#databases_page', '#linkdatabases', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#databases_page";
	document.title = 'Archaeo 18: Datenbanken und Repositorien';
});

$('#linkacknowledgment').click(function(e) {
	showDiv('#acknowledgment_page', '#linkacknowledgment', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#acknowledgment_page";
	document.title = 'Archaeo 18: Danksagung';
});

$('#linkpeople').click(function(e) {
	showDiv('#people_page', '#linkpeople', e);
	$('html,body').animate({scrollTop: 0}, 0);
	location.hash = "?page=#people_page";
	document.title = 'Archaeo 18: Projekmitarbeiter';
});

window.onhashchange = function() {
	if (location.hash.indexOf('?') != -1) {
		loadPage();
	}
};

var footerWidth = $('#logoPanel').width();
$(window).resize(function() {
	var w = Math.max($(window).width(), $('#editionContainer').width());
	if (footerWidth > w) {
		$('footer').css('width', footerWidth + 'px');
	}
	else {
		$('footer').css('width', w + 'px');
	}
});

var KEYCODE_ESC = 27;
$('body').keyup(function(e) {
	if (e.keyCode == KEYCODE_ESC) {
		$('.easterEgg').toggle();
	}
});<|endoftext|>


<commit_before>export { Base };

//import * as MapTools from "../util/MapTools.js";
import * as MultiLayerMap from "../../util/MultiLayerMap.js";
import * as ChannelShuffler from "./ChannelShuffler.js";

//!!! ...unfinished... (2022/05/23) Re-implement by MultiLayerMap.

/**
 * A container which provides shared channel shufflers. This could simplify memory management.
 *
 */
class Base {

  /**
   * @param {object} channelShufflerClass
   *   The class object for creating new channel shuffler. It is one of ChannelShuffler.ShuffleInfo, ChannelShuffler.ConcatGather,
   * ChannelShuffler.SplitConcat, ChannelShuffler.ConcatPointwiseConv.
   */
  constructor( channelShufflerClass = ChannelShuffler.ConcatPointwiseConv ) {
    this.channelShufflerClass = channelShufflerClass;

    // channel shufflers indexed by [ concatenatedHeight, concatenatedWidth, concatenatedDepth, outputGroupCount ].
    this.channelShufflersBy_height_width_depth_group = new Map();

    this.concatenatedShape = [ null, null, null ]; // A re-used shared array for reducing memory allocation.
  }

  /**
   *
   * @param {number} concatenatedHeight
   *   The image height which will be processed by the returned channel shuffler.
   *
   * @param {number} concatenatedWidth
   *   The image width which will be processed by the returned channel shuffler.
   *
   * @param {number} concatenatedDepth
   *   The image depth which will be processed by the returned channel shuffler.
   *
   * @param {number} outputGroupCount
   *   The outputGroupCount which will be produced by the returned channel shuffler.
   *
   * @param {object}
   *   A shared channel shuffler which could process the specific concatenatedShape and outputGroupCount.
   */
  getChannelShuffler_by( concatenatedHeight, concatenatedWidth, concatenatedDepth, outputGroupCount ) {

    let channelShufflersBy_width_depth_group = MapTools.get_or_create( this.channelShufflersBy_height_width_depth_group, concatenatedHeight );
    let channelShufflersBy_depth_group = MapTools.get_or_create( channelShufflersBy_width_depth_group, concatenatedWidth );
    let channelShufflersBy_group = MapTools.get_or_create( channelShufflersBy_depth_group, concatenatedDepth );

    let channelShuffler = channelShufflersBy_group.get( outputGroupCount );

    if ( channelShuffler )
      return channelShuffler; // 1. The requested channel shufffler has already been created. Re-use it. Return it directly.

    // 2. The requested channel shufffler has not yet existed. It should be created newly.
    this.concatenatedShape[ 0 ] = concatenatedHeight;
    this.concatenatedShape[ 1 ] = concatenatedWidth;
    this.concatenatedShape[ 2 ] = concatenatedDepth;
    channelShuffler = new (this.channelShufflerClass)( this.concatenatedShape, outputGroupCount );

    channelShufflersBy_group.set( outputGroupCount, channelShuffler ); // Cache it.
    return channelShuffler;
  }

  /** Release all channel shufflers and their tf.tensor. */
  disposeTensors() {
    if ( this.channelShufflersBy_height_width_depth_group ) {
      for ( let channelShuffler of MapTools.values_recursively( this.channelShufflersBy_height_width_depth_group ) ) {
        channelShuffler.disposeTensors();
      }

      this.channelShufflersBy_height_width_depth_group.clear();
    }
  }

}
<commit_msg>Update ChannelShufflerPool.js<commit_after>export { Base };

//import * as MapTools from "../util/MapTools.js";
import * as MultiLayerMap from "../../util/MultiLayerMap.js";
import * as ChannelShuffler from "./ChannelShuffler.js";

//!!! ...unfinished... (2022/05/23) Re-implement by MultiLayerMap.

/**
 * A container which provides shared channel shufflers. This could simplify memory management.
 *
 */
class Base extends MultiLayerMap.Base {

  /**
   * @param {object} channelShufflerClass
   *   The class object for creating new channel shuffler. It is one of ChannelShuffler.ShuffleInfo, ChannelShuffler.ConcatGather,
   * ChannelShuffler.SplitConcat, ChannelShuffler.ConcatPointwiseConv.
   */
  constructor( channelShufflerClass = ChannelShuffler.ConcatPointwiseConv ) {
    super();

    this.channelShufflerClass = channelShufflerClass;

//!!! (2022/05/23 Remarked) Replaced by MultiLayerMap.
//     // channel shufflers indexed by [ concatenatedHeight, concatenatedWidth, concatenatedDepth, outputGroupCount ].
//     this.channelShufflersBy_height_width_depth_group = new Map();

    this.concatenatedShape = [ null, null, null ]; // A re-used shared array for reducing memory allocation.
  }

  /**
   *
   * @param {number} concatenatedHeight
   *   The image height which will be processed by the returned channel shuffler.
   *
   * @param {number} concatenatedWidth
   *   The image width which will be processed by the returned channel shuffler.
   *
   * @param {number} concatenatedDepth
   *   The image depth which will be processed by the returned channel shuffler.
   *
   * @param {number} outputGroupCount
   *   The outputGroupCount which will be produced by the returned channel shuffler.
   *
   * @param {object}
   *   A shared channel shuffler which could process the specific concatenatedShape and outputGroupCount.
   */
  getChannelShuffler_by( concatenatedHeight, concatenatedWidth, concatenatedDepth, outputGroupCount ) {

//!!! (2022/05/23 Remarked) Replaced by MultiLayerMap.
//
//     let channelShufflersBy_width_depth_group = MapTools.get_or_create( this.channelShufflersBy_height_width_depth_group, concatenatedHeight );
//     let channelShufflersBy_depth_group = MapTools.get_or_create( channelShufflersBy_width_depth_group, concatenatedWidth );
//     let channelShufflersBy_group = MapTools.get_or_create( channelShufflersBy_depth_group, concatenatedDepth );
//
//     let channelShuffler = channelShufflersBy_group.get( outputGroupCount );
//
//     if ( channelShuffler )
//       return channelShuffler; // 1. The requested channel shufffler has already been created. Re-use it. Return it directly.
//
//     // 2. The requested channel shufffler has not yet existed. It should be created newly.
//     this.concatenatedShape[ 0 ] = concatenatedHeight;
//     this.concatenatedShape[ 1 ] = concatenatedWidth;
//     this.concatenatedShape[ 2 ] = concatenatedDepth;
//     channelShuffler = new (this.channelShufflerClass)( this.concatenatedShape, outputGroupCount );
//
//     channelShufflersBy_group.set( outputGroupCount, channelShuffler ); // Cache it.
//     return channelShuffler;

    return this.get_or_create_by_arguments1_etc( ( concatenatedHeight, concatenatedWidth, concatenatedDepth, outputGroupCount ) => {
        this.concatenatedShape[ 0 ] = concatenatedHeight;
        this.concatenatedShape[ 1 ] = concatenatedWidth;
        this.concatenatedShape[ 2 ] = concatenatedDepth;
        let channelShuffler = new (this.channelShufflerClass)( this.concatenatedShape, outputGroupCount );
        return channelShuffler;
      },
      concatenatedHeight, concatenatedWidth, concatenatedDepth, outputGroupCount );
  }

  /** Release all channel shufflers and their tf.tensor. */
  disposeTensors() {

//!!! (2022/05/23 Remarked) Replaced by MultiLayerMap.
//
//     if ( this.channelShufflersBy_height_width_depth_group ) {
//       for ( let channelShuffler of MapTools.values_recursively( this.channelShufflersBy_height_width_depth_group ) ) {
//         channelShuffler.disposeTensors();
//       }
//
//       this.channelShufflersBy_height_width_depth_group.clear();
//     }

    this.visit_all_and_call( channelShuffler => {
      channelShuffler.disposeTensors();
    } );
    this.clear();
  }

}
<|endoftext|>


<commit_before>// Virtuals Plugin
// Allows getting/setting virtual (computed) properties on model instances.
// -----
module.exports = function (Bookshelf) {
  "use strict";
  var _         = require('lodash');
  var proto     = Bookshelf.Model.prototype;

  var Model = Bookshelf.Model.extend({
    outputVirtuals: true,

    // If virtual properties have been defined they will be created
    // as simple getters on the model.
    constructor: function (attributes, options) {
      proto.constructor.apply(this, arguments);
      var virtuals = this.virtuals;
      if (_.isObject(virtuals)) {
        for (var virtualName in virtuals) {
          var getter, setter;
          if (virtuals[virtualName].get) {
            getter = virtuals[virtualName].get;
            setter = virtuals[virtualName].set ? virtuals[virtualName].set : undefined;
          } else {
            getter = virtuals[virtualName];
          }
          Object.defineProperty(this, virtualName, {
            enumerable: true,
            get: getter,
            set: setter
          });
        }
      }
    },

    // Passing `{virtuals: true}` or `{virtuals: false}` in the `options`
    // controls including virtuals on function-level and overrides the
    // model-level setting
    toJSON: function(options) {
      var attrs = proto.toJSON.call(this, options);
      if (!options || options.virtuals !== false) {
        if ((options && options.virtuals === true) || this.outputVirtuals) {
          attrs = _.extend(attrs, getVirtuals(this));
        }
      }
      return attrs;
    },

    // Allow virtuals to be fetched like normal properties
    get: function (attr) {
      var virtuals = this.virtuals;
      if (_.isObject(virtuals) && virtuals[attr]) {
        return getVirtual(this, attr);
      }
      return proto.get.apply(this, arguments);
    },

    // Allow virtuals to be set like normal properties
    set: function(key, val, options) {
      if (key == null) return this;
       if (_.isObject(key)) {
         return proto.set.call(this, _.omit(key, setVirtual, this), val, options);
       }
       return setVirtual.call(this, val, key) || proto.set.apply(this, arguments);
    }
  });

  // Underscore methods that we want to implement on the Model.
  var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];

  // Mix in each Underscore method as a proxy to `Model#attributes`.
  _.each(modelMethods, function(method) {
    Model.prototype[method] = function() {
      var args = _.toArray(arguments);
      args.unshift(_.extend({}, this.attributes, getVirtuals(this)));
      return _[method].apply(_, args);
    };
  });

  function getVirtual(model, virtualName) {
    var virtuals = model.virtuals;
    if (_.isObject(virtuals) && virtuals[virtualName]) {
      return virtuals[virtualName].get ? virtuals[virtualName].get.call(model)
        : virtuals[virtualName].call(model);
    }
  }

  function getVirtuals(model) {
    var virtuals, attrs = {};
    if (virtuals = model.virtuals) {
      for (var virtualName in virtuals) {
        attrs[virtualName] = getVirtual(model, virtualName);
      }
    }
    return attrs;
  }

  function setVirtual(ctx, key, value) {
    var virtual = ctx.virtuals && ctx.virtuals[key];
    if (virtual && virtual.set) {
      virtual.set.call(ctx, value);
      return this;
    }
  }

  Bookshelf.Model = Model;
};<commit_msg>oops context should be this<commit_after>// Virtuals Plugin
// Allows getting/setting virtual (computed) properties on model instances.
// -----
module.exports = function (Bookshelf) {
  "use strict";
  var _         = require('lodash');
  var proto     = Bookshelf.Model.prototype;

  var Model = Bookshelf.Model.extend({
    outputVirtuals: true,

    // If virtual properties have been defined they will be created
    // as simple getters on the model.
    constructor: function (attributes, options) {
      proto.constructor.apply(this, arguments);
      var virtuals = this.virtuals;
      if (_.isObject(virtuals)) {
        for (var virtualName in virtuals) {
          var getter, setter;
          if (virtuals[virtualName].get) {
            getter = virtuals[virtualName].get;
            setter = virtuals[virtualName].set ? virtuals[virtualName].set : undefined;
          } else {
            getter = virtuals[virtualName];
          }
          Object.defineProperty(this, virtualName, {
            enumerable: true,
            get: getter,
            set: setter
          });
        }
      }
    },

    // Passing `{virtuals: true}` or `{virtuals: false}` in the `options`
    // controls including virtuals on function-level and overrides the
    // model-level setting
    toJSON: function(options) {
      var attrs = proto.toJSON.call(this, options);
      if (!options || options.virtuals !== false) {
        if ((options && options.virtuals === true) || this.outputVirtuals) {
          attrs = _.extend(attrs, getVirtuals(this));
        }
      }
      return attrs;
    },

    // Allow virtuals to be fetched like normal properties
    get: function (attr) {
      var virtuals = this.virtuals;
      if (_.isObject(virtuals) && virtuals[attr]) {
        return getVirtual(this, attr);
      }
      return proto.get.apply(this, arguments);
    },

    // Allow virtuals to be set like normal properties
    set: function(key, val, options) {
      if (key == null) return this;
       if (_.isObject(key)) {
         return proto.set.call(this, _.omit(key, setVirtual, this), val, options);
       }
       return setVirtual.call(this, val, key) || proto.set.apply(this, arguments);
    }
  });

  // Underscore methods that we want to implement on the Model.
  var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];

  // Mix in each Underscore method as a proxy to `Model#attributes`.
  _.each(modelMethods, function(method) {
    Model.prototype[method] = function() {
      var args = _.toArray(arguments);
      args.unshift(_.extend({}, this.attributes, getVirtuals(this)));
      return _[method].apply(_, args);
    };
  });

  function getVirtual(model, virtualName) {
    var virtuals = model.virtuals;
    if (_.isObject(virtuals) && virtuals[virtualName]) {
      return virtuals[virtualName].get ? virtuals[virtualName].get.call(model)
        : virtuals[virtualName].call(model);
    }
  }

  function getVirtuals(model) {
    var virtuals, attrs = {};
    if (virtuals = model.virtuals) {
      for (var virtualName in virtuals) {
        attrs[virtualName] = getVirtual(model, virtualName);
      }
    }
    return attrs;
  }

  function setVirtual(key, value) {
    var virtual = this.virtuals && this.virtuals[key];
    if (virtual && virtual.set) {
      virtual.set.call(this, value);
      return this;
    }
  }

  Bookshelf.Model = Model;
};<|endoftext|>