<commit_before>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = [];
    this.curr_row   = 1 ;
    this.curr_col   = 1 ;
    this.curr_token = '';
    this.curr_val   = '';
    this.comments   = false;
    this.strings    = false;

}

// Adds token to list
Scanner.prototype.addToken = function(){

    if(this.curr_token){
        var token = {
            'token': this.curr_token,
            'value': this.curr_val,
            'row'  : this.curr_row,
            'col'  : this.curr_col
        }
        this.tokens.push(token);

        // TODO: Use bootstrap to render these tables
        var table = document.getElementById('list');
        var node = document.createElement('tr');
        for(var prop in token){
            table.appendChild(node);
            var entry = node.appendChild(document.createElement('td'));
            entry.appendChild(document.createTextNode(token[prop]));
        }
    }

    return;
}

// Resets values of token
Scanner.prototype.reset = function(){
    this.curr_val = '';
    this.curr_token = '';
    return;
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(character){
    return character.charCodeAt();
}

// Returns lowercase string
Scanner.prototype.toLower = function(character){
    return character.toLowerCase();
}

// Returns uppercase string
Scanner.prototype.toUpper = function(character){
    return character.toUpperCase();
}

// Handles comments
Scanner.prototype.setComment = function(character){
    // TODO
    return;
}

// Handles EOF
Scanner.prototype.setEOF = function(character){
    this.curr_val = 'TK_EOF';
    this.curr_val = 'EOF';
    this.addToken();
    return;
}

// Handles numerical characters
Scanner.prototype.setDigit = function(character){
    if(this.curr_token === 'TK_REAL' || this.curr_token === 'TK_INT'){
        this.curr_val += character;
    }
    else{
        this.setToken('TK_INT', character);
    }
    return;
}

// Handles strings, builds string up
Scanner.prototype.setString = function(character){
    this.curr_val += character;
    console.log(character);
    if((this.curr_token === 'TK_SINGLE_QUOTE' && character === "'") ||
       (this.curr_token === 'TK_DOUBLE_QUOTE' && character === '"')){
        console.log("HELLO");
        this.buildString();
    }
    return;
}

// Builds final string token
Scanner.prototype.buildString = function(){
    this.curr_token = 'TK_STRING';
    this.addToken();
    this.reset();
}

// Handles newline characters
Scanner.prototype.setLine = function(ascii_value){
    this.addToken();
    this.reset();
    if(ascii_value === '10'){
        this.curr_row += 1;
        this.curr_col = 0;
    }
    return;
}

// Handles whitespace character
Scanner.prototype.setSpace = function(ascii_value){
    this.addToken();
    this.reset();
    return;
}

// Adds the last token into the list, sets new token
Scanner.prototype.setToken = function(token_type, character){
    this.addToken();
    this.reset();
    this.curr_token = token_type;
    this.curr_val += character;
    console.log(this.curr_val);
    return;
}

// Handles characters
Scanner.prototype.setCharacter = function(character){
    if(this.curr_token != 'TK_IDENTIFIER'){
        this.setToken('TK_IDENTIFIER', character);
    }
    else{
        this.curr_val += character;
        if(this.curr_val in keywords){
            this.curr_token = keywords[this.curr_val];
        }
        else if(this.curr_val in operators){
            this.curr_token = operators[this.curr_val];
        }
    }
    return;
}

// Handles operators
Scanner.prototype.setOperator = function(character){
    if(character === '.' && this.curr_token === 'TK_INT'){
        this.curr_token = 'TK_REAL';
        this.curr_val += character;
    }

    else if(this.curr_val + character in operators){
        this.curr_val += character;
        // Handle all two-symbol operators
        if(this.curr_val in operators){
            this.curr_token = operators[this.curr_val];
        }
    }
    else{
        this.setToken(operators[character], character);
    }
    return;
}

// Main scanner function
function scan(){

    // Get input text from textarea
    var program = document.getElementById("program").value;
    document.getElementById("demo").innerHTML = program;

    // Initalize scanner
    var scanner = new Scanner();

    // Begin scanning input text
    for(var i = 0; i < program.length; i++){

        // Handle case when we close the string
        if(scanner.curr_token === 'TK_SINGLE_QUOTE' || scanner.curr_token === 'TK_DOUBLE_QUOTE'){
            scanner.setString(program[i]);
        }

        var character = scanner.toUpper(program[i]);
        var ascii = scanner.toAscii(character);

        // Handle case for newline character
        if(ascii == '10'){
            scanner.setLine(ascii);
        }

        // Handle case for space
        else if(ascii == '32'){
            scanner.setSpace(ascii);
        }

        // Handle case for valid letters
        else if( (ascii >= 97 && ascii <= 122) || (ascii >= 65 && ascii <= 90) ){
            console.log("HELLO AGAIN");
            scanner.setCharacter(character);
        }

        // Handle case for operators
        else if(character in operators){
            scanner.setOperator(character);
        }

        // Handle case for numbers
        else if(ascii >= 48 && ascii <= 57){
            scanner.setDigit(character);
        }

        // Handle case for strings composed with single quote
        else if(ascii === 39){
            scanner.setToken('TK_SINGLE_QUOTE', character);
        }

        // Handle case for strings composed with double quotes
        else if(ascii === 34){
            scanner.setToken('TK_DOUBLE_QUOTE', character);
        }

        scanner.curr_col += 1;

    }
    scanner.setEOF();
    console.log(scanner.tokens);

}

var keywords = {
    'begin'     : 'TK_BEGIN',
    'break'     : 'TK_BREAK',
    'const'     : 'TK_CONST',
    'do'        : 'TK_DO',
    'downto'    : 'TK_DOWNTO',
    'else'      : 'TK_ELSE',
    'end'       : 'TK_END',
    'end.'      : 'TK_END_CODE',
    'for'       : 'TK_FOR',
    'function'  : 'TK_FUNCTION',
    'identifier': 'TK_IDENTIFIER',
    'if'        : 'TK_IF',
    'label'     : 'TK_LABEL',
    'program'   : 'TK_PROGRAM',
    'repeat'    : 'TK_REPEAT',
    'string'    : 'TK_STRING',
    'then'      : 'TK_THEN',
    'to'        : 'TK_TO',
    'type'      : 'TK_TYPE',
    'var'       : 'TK_VAR',
    'until'     : 'TK_UNTIL',
    'while'     : 'TK_WHILE',
    'integer'   : 'TK_ID_INTEGER',
    'real'      : 'TK_ID_REAL',
    'char'      : 'TK_ID_CHAR',
    'boolean'   : 'TK_ID_BOOLEAN',
    'of'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'div'       : 'TK_DIV',
    'mod'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '.'         : 'TK_DOT',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'and'       : 'TK_AND',
    'xor'       : 'TK_XOR',
    'or'        : 'TK_OR',
    'not'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_SINGLE_QUOTE',
    '"'         : 'TK_DOUBLE_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'array'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'writeln'   : 'TK_WRITELN',
    'abs'       : 'TK_ABS'
}<commit_msg>scanner.js: Able to generate string tokens<commit_after>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = [];
    this.curr_row   = 1 ;
    this.curr_col   = 1 ;
    this.curr_token = '';
    this.curr_val   = '';
    this.comments   = false;
    this.strings    = false;

}

// Adds token to list
Scanner.prototype.addToken = function(){

    if(this.curr_token){
        var token = {
            'token': this.curr_token,
            'value': this.curr_val,
            'row'  : this.curr_row,
            'col'  : this.curr_col
        }
        this.tokens.push(token);

        // TODO: Use bootstrap to render these tables
        var table = document.getElementById('list');
        var node = document.createElement('tr');
        for(var prop in token){
            table.appendChild(node);
            var entry = node.appendChild(document.createElement('td'));
            entry.appendChild(document.createTextNode(token[prop]));
        }
    }

    return;
}

// Resets values of token
Scanner.prototype.reset = function(){
    this.curr_val = '';
    this.curr_token = '';
    return;
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(character){
    return character.charCodeAt();
}

// Returns lowercase string
Scanner.prototype.toLower = function(character){
    return character.toLowerCase();
}

// Returns uppercase string
Scanner.prototype.toUpper = function(character){
    return character.toUpperCase();
}

// Handles comments
Scanner.prototype.setComment = function(character){
    // TODO
    return;
}

// Handles EOF
Scanner.prototype.setEOF = function(character){
    this.curr_val = 'TK_EOF';
    this.curr_val = 'EOF';
    this.addToken();
    return;
}

// Handles numerical characters
Scanner.prototype.setDigit = function(character){
    if(this.curr_token === 'TK_REAL' || this.curr_token === 'TK_INT'){
        this.curr_val += character;
    }
    else{
        this.setToken('TK_INT', character);
    }
    return;
}

// Handles strings, builds string up
Scanner.prototype.setString = function(character){
    this.curr_val += character;
    console.log(character);
    if((this.curr_token === 'TK_SINGLE_QUOTE' && character === "'") ||
       (this.curr_token === 'TK_DOUBLE_QUOTE' && character === '"')){
        console.log("Going to build the string");
        this.buildString();
    }
    return;
}

// Builds final string token
Scanner.prototype.buildString = function(){
    this.curr_token = 'TK_STRING';
    this.addToken();
    this.reset();
}

// Handles newline characters
Scanner.prototype.setLine = function(ascii_value){
    this.addToken();
    this.reset();
    if(ascii_value === '10'){
        this.curr_row += 1;
        this.curr_col = 0;
    }
    return;
}

// Handles whitespace character
Scanner.prototype.setSpace = function(ascii_value){
    this.addToken();
    this.reset();
    return;
}

// Adds the last token into the list, sets new token
Scanner.prototype.setToken = function(token_type, character){
    this.addToken();
    this.reset();
    this.curr_token = token_type;
    this.curr_val += character;
    console.log(this.curr_val);
    return;
}

// Handles characters
Scanner.prototype.setCharacter = function(character){
    if(this.curr_token != 'TK_IDENTIFIER'){
        this.setToken('TK_IDENTIFIER', character);
    }
    else{
        this.curr_val += character;
        if(this.curr_val in keywords){
            this.curr_token = keywords[this.curr_val];
        }
        else if(this.curr_val in operators){
            this.curr_token = operators[this.curr_val];
        }
    }
    return;
}

// Handles operators
Scanner.prototype.setOperator = function(character){
    if(character === '.' && this.curr_token === 'TK_INT'){
        this.curr_token = 'TK_REAL';
        this.curr_val += character;
    }

    else if(this.curr_val + character in operators){
        this.curr_val += character;
        // Handle all two-symbol operators
        if(this.curr_val in operators){
            this.curr_token = operators[this.curr_val];
        }
    }
    else{
        this.setToken(operators[character], character);
    }
    return;
}

// Main scanner function
function scan(){

    // Get input text from textarea
    var program = document.getElementById("program").value;
    document.getElementById("demo").innerHTML = program;

    // Initalize scanner
    var scanner = new Scanner();

    // Begin scanning input text
    for(var i = 0; i < program.length; i++){

        // Handle case when we close the string
        if(scanner.curr_token === 'TK_SINGLE_QUOTE' || scanner.curr_token === 'TK_DOUBLE_QUOTE'){
            console.log(scanner.curr_token);
            scanner.setString(program[i]);
        }

        if(!scanner.strings){
            // If we are not generating a string, do this
            var character = scanner.toUpper(program[i]);
            var ascii = scanner.toAscii(character);
            console.log(ascii);
            // Handle case for newline character
            if(ascii == '10'){
                scanner.setLine(ascii);
            }

            // Handle case for space
            else if(ascii == '32'){
                scanner.setSpace(ascii);
            }

            // Handle case for valid letters
            else if( (ascii >= 97 && ascii <= 122) || (ascii >= 65 && ascii <= 90) ){
                console.log("HELLO AGAIN");
                scanner.setCharacter(character);
            }

            // Handle case for numbers
            else if(ascii >= 48 && ascii <= 57){
                console.log("number");
                scanner.setDigit(character);
            }

            // Handle case for strings composed with single quote
            else if(ascii === 39){
                console.log("IN HERE");
                scanner.setToken('TK_SINGLE_QUOTE', character);
                scanner.strings = true;
                console.log(scanner.strings);
            }

            // Handle case for strings composed with double quotes
            else if(ascii === 34){
                scanner.setToken('TK_DOUBLE_QUOTE', character);
                scanner.strings = true;
            }

            // Handle case for operators
            else if(character in operators){
                console.log("operator");
                scanner.setOperator(character);
            }
        }
    }
    scanner.curr_col += 1;

    //scanner.setEOF();
    console.log(scanner.tokens);

}

var keywords = {
    'begin'     : 'TK_BEGIN',
    'break'     : 'TK_BREAK',
    'const'     : 'TK_CONST',
    'do'        : 'TK_DO',
    'downto'    : 'TK_DOWNTO',
    'else'      : 'TK_ELSE',
    'end'       : 'TK_END',
    'end.'      : 'TK_END_CODE',
    'for'       : 'TK_FOR',
    'function'  : 'TK_FUNCTION',
    'identifier': 'TK_IDENTIFIER',
    'if'        : 'TK_IF',
    'label'     : 'TK_LABEL',
    'program'   : 'TK_PROGRAM',
    'repeat'    : 'TK_REPEAT',
    'string'    : 'TK_STRING',
    'then'      : 'TK_THEN',
    'to'        : 'TK_TO',
    'type'      : 'TK_TYPE',
    'var'       : 'TK_VAR',
    'until'     : 'TK_UNTIL',
    'while'     : 'TK_WHILE',
    'integer'   : 'TK_ID_INTEGER',
    'real'      : 'TK_ID_REAL',
    'char'      : 'TK_ID_CHAR',
    'boolean'   : 'TK_ID_BOOLEAN',
    'of'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'div'       : 'TK_DIV',
    'mod'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '.'         : 'TK_DOT',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'and'       : 'TK_AND',
    'xor'       : 'TK_XOR',
    'or'        : 'TK_OR',
    'not'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_SINGLE_QUOTE',
    '"'         : 'TK_DOUBLE_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'array'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'writeln'   : 'TK_WRITELN',
    'abs'       : 'TK_ABS'
}<|endoftext|>


<commit_before>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = []
    this.curr_row   = 0
    this.curr_col   = 0
    this.curr_token = ''

}

// Main scanner function
Scanner.prototype.scan = function(){
    console.log(keywords['BEGIN']);
}

// Retrieves value from table
Scanner.prototype.lookup = function(table, key){
    return table[key];
}

var keywords = {
    'BEGIN'     : 'TK_BEGIN',
    'BREAK'     : 'TK_BREAK',
    'CONST'     : 'TK_CONST',
    'DO'        : 'TK_DO',
    'DOWNTO'    : 'TK_DOWNTO',
    'ELSE'      : 'TK_ELSE',
    'END'       : 'TK_END',
    'END.'      : 'TK_END_CODE',
    'FOR'       : 'TK_FOR',
    'FUNCTION'  : 'TK_FUNCTION',
    'IDENTIFIER': 'TK_IDENTIFIER',
    'IF'        : 'TK_IF',
    'LABEL'     : 'TK_LABEL',
    'PROGRAM'   : 'TK_PROGRAM',
    'REPEAT'    : 'TK_REPEAT',
    'STRING'    : 'TK_STRING',
    'THEN'      : 'TK_THEN',
    'TO'        : 'TK_TO',
    'TYPE'      : 'TK_TYPE',
    'VAR'       : 'TK_VAR',
    'UNTIL'     : 'TK_UNTIL',
    'WHILE'     : 'TK_WHILE',
    'INTEGER'   : 'TK_ID_INTEGER',
    'REAL'      : 'TK_ID_REAL',
    'CHAR'      : 'TK_ID_CHAR',
    'BOOLEAN'   : 'TK_ID_BOOLEAN',
    'OF'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'DIV'       : 'TK_DIV',
    'MOD'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'AND'       : 'TK_AND',
    'XOR'       : 'TK_XOR',
    'OR'        : 'TK_OR',
    'NOT'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'ARRAY'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'WRITELN'   : 'TK_WRITELN',
    'ABS'       : 'TK_ABS'
}<commit_msg>scanner.js: Implemented toAscii method<commit_after>/************************************
* scanner.js
* MIT License (c) 2014 David Leonard
* drksephy.github.io
*************************************/

'use strict';

/**********************
* Scanner constructor *
**********************/

function Scanner(){
    this.tokens     = []
    this.curr_row   = 0
    this.curr_col   = 0
    this.curr_token = ''

}

// Main scanner function
Scanner.prototype.scan = function(){
    console.log(keywords['BEGIN']);
}

// Retrieves value from table
Scanner.prototype.lookup = function(table, key){
    return table[key];
}

// Returns ascii value of character
Scanner.prototype.toAscii = function(char){
    return a.charCodeAt();
}

var keywords = {
    'BEGIN'     : 'TK_BEGIN',
    'BREAK'     : 'TK_BREAK',
    'CONST'     : 'TK_CONST',
    'DO'        : 'TK_DO',
    'DOWNTO'    : 'TK_DOWNTO',
    'ELSE'      : 'TK_ELSE',
    'END'       : 'TK_END',
    'END.'      : 'TK_END_CODE',
    'FOR'       : 'TK_FOR',
    'FUNCTION'  : 'TK_FUNCTION',
    'IDENTIFIER': 'TK_IDENTIFIER',
    'IF'        : 'TK_IF',
    'LABEL'     : 'TK_LABEL',
    'PROGRAM'   : 'TK_PROGRAM',
    'REPEAT'    : 'TK_REPEAT',
    'STRING'    : 'TK_STRING',
    'THEN'      : 'TK_THEN',
    'TO'        : 'TK_TO',
    'TYPE'      : 'TK_TYPE',
    'VAR'       : 'TK_VAR',
    'UNTIL'     : 'TK_UNTIL',
    'WHILE'     : 'TK_WHILE',
    'INTEGER'   : 'TK_ID_INTEGER',
    'REAL'      : 'TK_ID_REAL',
    'CHAR'      : 'TK_ID_CHAR',
    'BOOLEAN'   : 'TK_ID_BOOLEAN',
    'OF'        : 'TK_OF'
}

var operators = {
    '+'         : 'TK_PLUS',
    '-'         : 'TK_MINUS',
    '*'         : 'TK_MULT',
    '/'         : 'TK_DIV_FLOAT',
    'DIV'       : 'TK_DIV',
    'MOD'       : 'TK_MOD',
    ':'         : 'TK_COLON',
    '='         : 'TK_EQUALS',
    ':='        : 'TK_ASSIGNMENT',
    '>'         : 'TK_GREATER',
    '<'         : 'TK_LESS',
    '>='        : 'TK_GREATER_EQUALS',
    '<='        : 'TK_LESS_EQUALS',
    '!'         : 'TK_EXCLAMATION',
    '!='        : 'TK_NOT_EQUALS',
    'AND'       : 'TK_AND',
    'XOR'       : 'TK_XOR',
    'OR'        : 'TK_OR',
    'NOT'       : 'TK_NOT',
    ';'         : 'TK_SEMICOLON',
    '('         : 'TK_OPEN_PARENTHESIS',
    ')'         : 'TK_CLOSE_PARENTHESIS',
    '\''        : 'TK_QUOTE',
    '(*'        : 'TK_BEGIN_COMMENT',
    '*)'        : 'TK_END_COMMENT',
    ','         : 'TK_COMMA',
    '~'         : 'TK_RANGE',
    'ARRAY'     : 'TK_ARRAY',
    '['         : 'TK_OPEN_BRACKET',
    ']'         : 'TK_CLOSE_BRACKET'
}

var SYSTEM = {
    'WRITELN'   : 'TK_WRITELN',
    'ABS'       : 'TK_ABS'
}<|endoftext|>


<commit_before>//Run when the DOM is ready to be manipulated.
$(function() {

  /* RUN TO SHOW INITIAL PAGE
  * ====================== */

  //show the correct content from the start.
  var currentPage = getCurrentPage();
  var pages = getPages();
  landingPage = showLandingPage(currentPage);
  setPrevNextArrows(currentPage);

  //Call the function to count for every number listed.
  landingPage.find('.num').each(function(){
    animateCountUp($(this));
  });

  //Set the correct navigation from the start.
  $('#main-nav a[href="#' + currentPage + '"]').parent().addClass("active");

  /* HANDLE LOGIN/REGISTER LINKS AND MODAL FIELDS
  * ====================== */
  //One modal box used here with JS to show and hide the correct fields.
  //Allows us to process only one form, not multiple forms.
  $('#register-link').click(function(){
      var loginRegModal = $('#login-reg-modal');
      loginRegModal.find('#login-group').addClass('hide');
      loginRegModal.find('#register-group, #logreg-email-group').removeClass('hide');
      loginRegModal.find('#login-reg-button').text('Register');
  });
  $('#login-link').click(function(){
      var loginRegModal = $('#login-reg-modal');
      loginRegModal.find('#login-group').removeClass('hide');
      loginRegModal.find('#register-group, #logreg-email-group').addClass('hide');
      loginRegModal.find('#login-reg-button').text('Login');
  });

  /* SLIDING BAR FOR MAIN NAVIGATION
  * ====================== */
  //Adjusted from http://css-tricks.com/jquery-magicline-navigation/.
  var $el, leftPos, newWidth,
    $mainNav = $("#main-nav");

  $mainNav.append("

");
  var $rollover_bar = $("#rollover-bar");

  $rollover_bar
  .width($(".active").width())
  .css("left", $(".active a").position().left)
  .data("origLeft", $rollover_bar.position().left)
  .data("origWidth", $rollover_bar.width());

  $("#main-nav li a").hover(function() {
    $el = $(this);
    leftPos = $el.position().left;
    newWidth = $el.parent().width();
    $rollover_bar.stop().animate({
      left: leftPos,
      width: newWidth
    });
  }, function() {
    $rollover_bar.stop().animate({
      left: $rollover_bar.data("origLeft"),
      width: $rollover_bar.data("origWidth")
    });
  });

  $("#main-nav li").click(function(evt) {
    $("#main-nav li").removeClass("active");
    $el = $(this);
    $el.addClass("active");
    $rollover_bar.data("origLeft", $(".active a").position().left);
    $rollover_bar.data("origWidth", $(".active").width());

    //Since we are going to run the click on the arrows we need to move the rollover bar to the new nav link.
    $rollover_bar.animate({
      left: $rollover_bar.data("origLeft"),
      width: $rollover_bar.data("origWidth")
    });

    //Handle page movement when a new page is clicked.
    var pageToShow = $el.children("a").attr('href');
    pageToShow = removeHash(pageToShow);
    showPageContent(pageToShow ,'next');

    var currentPage = removeHash($el.children().attr("href"))
    setPrevNextArrows(currentPage);

    evt.preventDefault();
  });

  //Set click event for the previous and next arrows.
  //We do this by triggering a click event on that navigation item.
  $('.page-control').click(function(evt){
    var clickedArrow = $(this);
    var currentPage = getCurrentPage();
    var prevNextPages = getPrevNextPages(currentPage);

    if(clickedArrow.hasClass("prev")){ //If they clicked the previous arrow.
      $("#main-nav li a[href='#" + prevNextPages['prev'] + "']").parent().trigger('click');
    }
    else{ //If they clicked the next arrow.
      $("#main-nav li a[href='#" + prevNextPages['next'] + "']").parent().trigger('click');
    }

    evt.preventDefault();
  });

  /* RUN ISOTOPE AND IMAGE ROLLOVERS
  * ====================== */
  var $container = $('#images');

  $container.isotope({
    itemSelector: '.image'
  });

    //When hovering over the images dropdown text over the top.
    $('#images .image').hover(function(){
      var imageContainer = $(this);
      var imgContent = imageContainer.children('.img-content');
      var imageHeight = imageContainer.css('height');
      imgContent.animate({
        height: imageHeight
      }, 300);
    }, function(){
      var imageContainer = $(this);
      var imgContent = imageContainer.children('.img-content');
      imgContent.animate({
        height: 0
      }, 300);
    });

    //When clicking on an image activate a modal window.
    $('#images .image').click(function(){
      $('#image-modal').modal();
    });

    //Animate the pulldown to show and hide when the pulldown button is clicked.
    $('#pulldown-btn').click(function(){
        dropdown = $('.dropdown');
        if (dropdown.hasClass('active')){
            dropdown.animate({height: '5px'}, 500);
            //We also animate the body so the whole page appears to move back up.
            $('body').animate({marginTop: '40px'}, 500);
            dropdown.removeClass('active');
        }
        else{
            dropdown.animate({height: '41px'}, 500);
            //We also animate the body so the whole page appears to move down.
            $('body').animate({marginTop: '76px'}, 500);
            dropdown.addClass('active');
        }
    });

}); //End of document ready function.

/* PAGE MOVEMENT FUNCTIONS
  * ====================== */
//Remove the hash sign from a string
function removeHash(string){
  string = string.replace("#","");

  return string;
}

function setHash(string){
  window.location.hash = string;

  return window.location.hash;
}

function getLinkString(pageName){
  var linkString = $('#main-nav a[href="#' + pageName + '"]').text();

  return linkString;
}

//Get all the pages on the site by using the name attribute from each .page-header a tag.
function getPages(){
  var pages = [];
  $("#pages .page-header a").each(function(index){
    pages.push($(this).attr('name'));
  })

  return pages;
}

//Find the current page by using the current URL.
//We can't use this when we click the navigation because the default change comes after what we do.
function getCurrentPage(){
  var currentPage;
  currentPage = window.location.hash;
  if(currentPage != ""){
    currentPage = removeHash(currentPage);
  }
  else{ //If there is no hash than use the first page in the list.
    var pages = getPages();
    currentPage = pages[0];
  }

  return currentPage;
}

//Set previous and next button text.
function setPrevNextArrows(currentPage){
  var prevNextPages = getPrevNextPages(currentPage);
  var pageControlPrev = $('#pages .page-control.prev');
  var pageControlNext = $('#pages .page-control.next');

  pageControlPrev.removeClass("active");
  pageControlNext.removeClass("active");

  //If the previous link should be shown change the text and set it to active.
  if(prevNextPages['prev'] != false){
    pageControlPrev.html(getLinkString(prevNextPages['prev']));
    pageControlPrev.addClass("active");
  }

  //If the next link should be showng change the text and set it to active.
  if(prevNextPages['next'] != false){
    pageControlNext.html(getLinkString(prevNextPages['next']));
    pageControlNext.addClass("active");
  }
}

//Get the previous and next pages of the current page.
//Return false for that array value if a previous or current doesn't exist.
function getPrevNextPages(currentPage){
  var prevNextPages = [];
  var pages = getPages();
  for (i = 0; i < pages.length; i++){
    if (pages[i] ==  currentPage){
      if(i == 0){
        prevNextPages['prev'] = false;
        prevNextPages['next'] = pages[i + 1];
      }
      else if(i == pages.length - 1){
        prevNextPages['prev'] = pages[i - 1];
        prevNextPages['next'] = false;
      }
      else{
        prevNextPages['prev'] = pages[i - 1];
        prevNextPages['next'] = pages[i + 1];
      }
    }
  }

  return prevNextPages;
}

function showLandingPage(landingPageName){
  var landingPage = $('#pages .page a[name="' + landingPageName + '"]').closest('div.page');
  landingPage.addClass("active");

  return landingPage;
}

function showPageContent(pageToShow, pageLocation){
  var pages = $('#pages');
  var currentContent = $('#pages .page.active');
  var currentContentHeight = currentContent.height();
  var pageToShowContent = $('#pages .page a[name="' + pageToShow + '"]').closest('div.page');

  //Set the height of the pages div to the current page height.
  pages.css('height', currentContentHeight);

  //Hide the current content first
  currentContent.fadeOut(100, function(){
    currentContent.removeClass("active");

    //Show the new content.
    pages.animate({
      height: pageToShowContent.height()
    }, 100);

    pageToShowContent.fadeIn(100, function(){
      pageToShowContent.addClass("active");
    });
  });

  //Set the has to be the new page.  This is needed for the prev and next buttons.
  setHash(pageToShow);

  //Call the function to count for every number listed.
  pageToShowContent.find('.num').each(function(){
    animateCountUp($(this));
  });

  return true;
}

/* COUNTING UP FUNCTION
  * ====================== */
function animateCountUp(containerSpan){
  //We pull the max number from the data-number attribute on the container span.
  var maxNumber = containerSpan.attr('data-number');
  maxNumber = Number(maxNumber);
  var currentNumber = 0;

  var i = setInterval(function(){
    if(currentNumber <= maxNumber){
      containerSpan.text(currentNumber);
      currentNumber++;
    }
    else{
      clearInterval();
    }
  }, 1);

}
<commit_msg>Adjusted height of pulldown menu in the js.<commit_after>//Run when the DOM is ready to be manipulated.
$(function() {

  /* RUN TO SHOW INITIAL PAGE
  * ====================== */

  //show the correct content from the start.
  var currentPage = getCurrentPage();
  var pages = getPages();
  landingPage = showLandingPage(currentPage);
  setPrevNextArrows(currentPage);

  //Call the function to count for every number listed.
  landingPage.find('.num').each(function(){
    animateCountUp($(this));
  });

  //Set the correct navigation from the start.
  $('#main-nav a[href="#' + currentPage + '"]').parent().addClass("active");

  /* HANDLE LOGIN/REGISTER LINKS AND MODAL FIELDS
  * ====================== */
  //One modal box used here with JS to show and hide the correct fields.
  //Allows us to process only one form, not multiple forms.
  $('#register-link').click(function(){
      var loginRegModal = $('#login-reg-modal');
      loginRegModal.find('#login-group').addClass('hide');
      loginRegModal.find('#register-group, #logreg-email-group').removeClass('hide');
      loginRegModal.find('#login-reg-button').text('Register');
  });
  $('#login-link').click(function(){
      var loginRegModal = $('#login-reg-modal');
      loginRegModal.find('#login-group').removeClass('hide');
      loginRegModal.find('#register-group, #logreg-email-group').addClass('hide');
      loginRegModal.find('#login-reg-button').text('Login');
  });

  /* SLIDING BAR FOR MAIN NAVIGATION
  * ====================== */
  //Adjusted from http://css-tricks.com/jquery-magicline-navigation/.
  var $el, leftPos, newWidth,
    $mainNav = $("#main-nav");

  $mainNav.append("

");
  var $rollover_bar = $("#rollover-bar");

  $rollover_bar
  .width($(".active").width())
  .css("left", $(".active a").position().left)
  .data("origLeft", $rollover_bar.position().left)
  .data("origWidth", $rollover_bar.width());

  $("#main-nav li a").hover(function() {
    $el = $(this);
    leftPos = $el.position().left;
    newWidth = $el.parent().width();
    $rollover_bar.stop().animate({
      left: leftPos,
      width: newWidth
    });
  }, function() {
    $rollover_bar.stop().animate({
      left: $rollover_bar.data("origLeft"),
      width: $rollover_bar.data("origWidth")
    });
  });

  $("#main-nav li").click(function(evt) {
    $("#main-nav li").removeClass("active");
    $el = $(this);
    $el.addClass("active");
    $rollover_bar.data("origLeft", $(".active a").position().left);
    $rollover_bar.data("origWidth", $(".active").width());

    //Since we are going to run the click on the arrows we need to move the rollover bar to the new nav link.
    $rollover_bar.animate({
      left: $rollover_bar.data("origLeft"),
      width: $rollover_bar.data("origWidth")
    });

    //Handle page movement when a new page is clicked.
    var pageToShow = $el.children("a").attr('href');
    pageToShow = removeHash(pageToShow);
    showPageContent(pageToShow ,'next');

    var currentPage = removeHash($el.children().attr("href"))
    setPrevNextArrows(currentPage);

    evt.preventDefault();
  });

  //Set click event for the previous and next arrows.
  //We do this by triggering a click event on that navigation item.
  $('.page-control').click(function(evt){
    var clickedArrow = $(this);
    var currentPage = getCurrentPage();
    var prevNextPages = getPrevNextPages(currentPage);

    if(clickedArrow.hasClass("prev")){ //If they clicked the previous arrow.
      $("#main-nav li a[href='#" + prevNextPages['prev'] + "']").parent().trigger('click');
    }
    else{ //If they clicked the next arrow.
      $("#main-nav li a[href='#" + prevNextPages['next'] + "']").parent().trigger('click');
    }

    evt.preventDefault();
  });

  /* RUN ISOTOPE AND IMAGE ROLLOVERS
  * ====================== */
  var $container = $('#images');

  $container.isotope({
    itemSelector: '.image'
  });

    //When hovering over the images dropdown text over the top.
    $('#images .image').hover(function(){
      var imageContainer = $(this);
      var imgContent = imageContainer.children('.img-content');
      var imageHeight = imageContainer.css('height');
      imgContent.animate({
        height: imageHeight
      }, 300);
    }, function(){
      var imageContainer = $(this);
      var imgContent = imageContainer.children('.img-content');
      imgContent.animate({
        height: 0
      }, 300);
    });

    //When clicking on an image activate a modal window.
    $('#images .image').click(function(){
      $('#image-modal').modal();
    });

    //Animate the pulldown to show and hide when the pulldown button is clicked.
    $('#pulldown-btn').click(function(){
        dropdown = $('.dropdown');
        if (dropdown.hasClass('active')){
            dropdown.animate({height: '5px'}, 500);
            //We also animate the body so the whole page appears to move back up.
            $('body').animate({marginTop: '40px'}, 500);
            dropdown.removeClass('active');
        }
        else{
            dropdown.animate({height: '36px'}, 500);
            //We also animate the body so the whole page appears to move down.
            $('body').animate({marginTop: '71px'}, 500);
            dropdown.addClass('active');
        }
    });

}); //End of document ready function.

/* PAGE MOVEMENT FUNCTIONS
  * ====================== */
//Remove the hash sign from a string
function removeHash(string){
  string = string.replace("#","");

  return string;
}

function setHash(string){
  window.location.hash = string;

  return window.location.hash;
}

function getLinkString(pageName){
  var linkString = $('#main-nav a[href="#' + pageName + '"]').text();

  return linkString;
}

//Get all the pages on the site by using the name attribute from each .page-header a tag.
function getPages(){
  var pages = [];
  $("#pages .page-header a").each(function(index){
    pages.push($(this).attr('name'));
  })

  return pages;
}

//Find the current page by using the current URL.
//We can't use this when we click the navigation because the default change comes after what we do.
function getCurrentPage(){
  var currentPage;
  currentPage = window.location.hash;
  if(currentPage != ""){
    currentPage = removeHash(currentPage);
  }
  else{ //If there is no hash than use the first page in the list.
    var pages = getPages();
    currentPage = pages[0];
  }

  return currentPage;
}

//Set previous and next button text.
function setPrevNextArrows(currentPage){
  var prevNextPages = getPrevNextPages(currentPage);
  var pageControlPrev = $('#pages .page-control.prev');
  var pageControlNext = $('#pages .page-control.next');

  pageControlPrev.removeClass("active");
  pageControlNext.removeClass("active");

  //If the previous link should be shown change the text and set it to active.
  if(prevNextPages['prev'] != false){
    pageControlPrev.html(getLinkString(prevNextPages['prev']));
    pageControlPrev.addClass("active");
  }

  //If the next link should be showng change the text and set it to active.
  if(prevNextPages['next'] != false){
    pageControlNext.html(getLinkString(prevNextPages['next']));
    pageControlNext.addClass("active");
  }
}

//Get the previous and next pages of the current page.
//Return false for that array value if a previous or current doesn't exist.
function getPrevNextPages(currentPage){
  var prevNextPages = [];
  var pages = getPages();
  for (i = 0; i < pages.length; i++){
    if (pages[i] ==  currentPage){
      if(i == 0){
        prevNextPages['prev'] = false;
        prevNextPages['next'] = pages[i + 1];
      }
      else if(i == pages.length - 1){
        prevNextPages['prev'] = pages[i - 1];
        prevNextPages['next'] = false;
      }
      else{
        prevNextPages['prev'] = pages[i - 1];
        prevNextPages['next'] = pages[i + 1];
      }
    }
  }

  return prevNextPages;
}

function showLandingPage(landingPageName){
  var landingPage = $('#pages .page a[name="' + landingPageName + '"]').closest('div.page');
  landingPage.addClass("active");

  return landingPage;
}

function showPageContent(pageToShow, pageLocation){
  var pages = $('#pages');
  var currentContent = $('#pages .page.active');
  var currentContentHeight = currentContent.height();
  var pageToShowContent = $('#pages .page a[name="' + pageToShow + '"]').closest('div.page');

  //Set the height of the pages div to the current page height.
  pages.css('height', currentContentHeight);

  //Hide the current content first
  currentContent.fadeOut(100, function(){
    currentContent.removeClass("active");

    //Show the new content.
    pages.animate({
      height: pageToShowContent.height()
    }, 100);

    pageToShowContent.fadeIn(100, function(){
      pageToShowContent.addClass("active");
    });
  });

  //Set the has to be the new page.  This is needed for the prev and next buttons.
  setHash(pageToShow);

  //Call the function to count for every number listed.
  pageToShowContent.find('.num').each(function(){
    animateCountUp($(this));
  });

  return true;
}

/* COUNTING UP FUNCTION
  * ====================== */
function animateCountUp(containerSpan){
  //We pull the max number from the data-number attribute on the container span.
  var maxNumber = containerSpan.attr('data-number');
  maxNumber = Number(maxNumber);
  var currentNumber = 0;

  var i = setInterval(function(){
    if(currentNumber <= maxNumber){
      containerSpan.text(currentNumber);
      currentNumber++;
    }
    else{
      clearInterval();
    }
  }, 1);

}
<|endoftext|>


<commit_before>$(document).ready(function(){
	$('.rollover').css('display', 'none');
    $('#work-slider ul li').hover(function() {
        $(this).children('.rollover').slideDown(300);
    }, function() {
        $(this).children('.rollover').slideUp(300);
    });
    window.setTimeout(slideShow, 5000);
});

function slideShow(){
	nextSlide();
	window.setTimeout(nextSlide, 5000);
}

function nextSlide(){
	var currentSlide = $('#work-slider').find('ul li.active');
	var nextSlide = ($(currentSlide).next().length != 0) ? $(currentSlide).next() : $('#work-slider').children('ul').children('li').first();
	$(currentSlide).removeClass('active').fadeOut(500);
	$(nextSlide).addClass('active').fadeIn(500);
}

function prevSlide(){
	var currentSlide = $('#work-slider').find('ul li.active');
	var nextSlide = ($(currentSlide).prev().length != 0) ? $(currentSlide).prev() : $('#work-slider').children('ul').children('li').last();
	$(currentSlide).removeClass('active').fadeOut(500);
	$(nextSlide).addClass('active').fadeIn(500);
}<commit_msg>Fixed js slide bug<commit_after>$(document).ready(function(){
	$('.rollover').css('display', 'none');
    $('#work-slider ul li').hover(function() {
        $(this).children('.rollover').slideDown(300);
    }, function() {
        $(this).children('.rollover').slideUp(300);
    });
    window.setTimeout(slideShow, 5000);
});

function slideShow(){
	nextSlide();
	window.setTimeout(slideShow, 5000);
}

function nextSlide(){
	var currentSlide = $('#work-slider').find('ul li.active');
	var nextSlide = ($(currentSlide).next().length != 0) ? $(currentSlide).next() : $('#work-slider').children('ul').children('li').first();
	$(currentSlide).removeClass('active').fadeOut(500);
	$(nextSlide).addClass('active').fadeIn(500);
}

function prevSlide(){
	var currentSlide = $('#work-slider').find('ul li.active');
	var nextSlide = ($(currentSlide).prev().length != 0) ? $(currentSlide).prev() : $('#work-slider').children('ul').children('li').last();
	$(currentSlide).removeClass('active').fadeOut(500);
	$(nextSlide).addClass('active').fadeIn(500);
}<|endoftext|>


<commit_before>$(document).ready(function () {
    // Initialization
    $('.carousel.carousel-slider').carousel({ fullWidth: true });

    if (innerWidth <= 635) {
        $('body').attr('background', 'img/mobileBackground.jpg');
        $('body').css('background-position-x', 'center');
    }

    // Event Listeners
    $('#linkOne').click(function () {
        $('.carousel').carousel('set', 0);
    });

    $('#linkTwo').click(function () {
        $('.carousel').carousel('set', 1);
    });

    $('#linkThree').click(function () {
        $('.carousel').carousel('set', 2);
    });

    $('#linkFour').click(function () {
        $('.carousel').carousel('set', 3);
    });

    if (innerWidth > 992) {
        $('#navbarTitle').hover(
            function () {
                $('.onHoverName').hide();
                $('.indicators').hide();
                $('#navbarTitle').removeClass("thin");
                $('#navbarTitle').addClass("light");
            },
            function () {
                $('.onHoverName').show();
                $('.indicators').show();
                $('#navbarTitle').addClass("thin");
                $('#navbarTitle').removeClass("light");
            }
        );
    }
});<commit_msg>Fixed name tap bug for mobile<commit_after>$(document).ready(function () {
    // Initialization
    $('.carousel.carousel-slider').carousel({ fullWidth: true });

    if (innerWidth <= 635) {
        $('body').attr('background', 'img/mobileBackground.jpg');
        $('body').css('background-position-x', 'center');
    }

    // Event Listeners
    $('#linkOne').click(function () {
        $('.carousel').carousel('set', 0);
    });

    $('#linkTwo').click(function () {
        $('.carousel').carousel('set', 1);
    });

    $('#linkThree').click(function () {
        $('.carousel').carousel('set', 2);
    });

    $('#linkFour').click(function () {
        $('.carousel').carousel('set', 3);
    });

    if (innerWidth > 992) {
        $('#navbarTitle').hover(
            function () {
                $('.onHoverName').hide();
                $('.indicators').hide();
                $('#navbarTitle').removeClass("thin");
                $('#navbarTitle').addClass("light");
            },
            function () {
                $('.onHoverName').show();
                $('.indicators').show();
                $('#navbarTitle').addClass("thin");
                $('#navbarTitle').removeClass("light");
            }
        );
    }
    else {
        $('#navbarTitle').click(function () {
            $('.carousel').carousel('set', 0);
        });
    }
});<|endoftext|>


<commit_before>var processing;

// JavaScript source code
$(document).ready(function () {
$('form').submit(function (evt) {
	evt.preventDefault();
	var searchTerm = $('#input').val();

	// AJAX Starts

	var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
	var animal = searchTerm;
	var flickrOptions = {
		tags: animal,
		format: "json",

	};
	function displayPhotos(data) {
		var photoHTML = '
';
		$.each(data.items, function(i,photo) {
			photoHTML += '
';
			photoHTML += '';
			photoHTML += '
';
		});
		photoHTML += '
';
		$('#photos').html(photoHTML);
	}

		$.getJSON(flickrAPI, flickrOptions, displayPhotos);

}) //end submit

// Fire AJAX every time page reaches 70% of height
    $(document).scroll(function(e){

        if (processing)
            return false;

        if ( $(document).scrollTop() >= ( $(document).height() - $(window).height() ) {
	    console.log('reached');
            processing = true;
            $.getJSON(flickrAPI, flickrOptions, displayPhotos);
	    processing = false;
        }
    });

}); // end ready

<commit_msg>Update scripts.js<commit_after>var processing = false;

// JavaScript source code
$(document).ready(function () {

$('form').submit(function (evt) {
	evt.preventDefault();
	var searchTerm = $('#input').val();

	// AJAX Starts

	var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
	var animal = searchTerm;
	var flickrOptions = {
		tags: animal,
		format: "json",

	};
	function displayPhotos(data) {
		var photoHTML = '
';
		$.each(data.items, function(i,photo) {
			photoHTML += '
';
			photoHTML += '';
			photoHTML += '
';
		});
		photoHTML += '
';
		$('#photos').html(photoHTML);
	}

		$.getJSON(flickrAPI, flickrOptions, displayPhotos);

}) //end submit

// Fire AJAX every time page reaches 70% of height
    $(document).scroll(function(e){

        if (processing)
            return false;

        if ( $(document).scrollTop() >= ( $(document).height() - $(window).height() ) {
	    console.log('reached');
            processing = true;
            $.getJSON(flickrAPI, flickrOptions, displayPhotos);
	    processing = false;
        }
    });

}); // end ready

<|endoftext|>


<commit_before>var pingPongType = function(i) {
  if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
    if (i % 15 === 0) {
        return "pingpong";
    } else if (i % 5 === 0) {
        return "pong";
    } else {
        return "ping";
    }
  } else {
    return i;
  }
}

$(function() {
  $("#game").submit(function(event) {
    $('#outputList').empty();

    var number = parseInt($("#userNumber").val());
    var warning = "Whoops! Please enter an integer!"

    if (Number.isNaN(number) === true) {
      alert(warning);
    }

    for (var i = 1; i <= number; i += 1) {
      var output = pingPongType(i)
      $('#outputList').append("
" + output + "
")
    }

    event.preventDefault();
  });
});
<commit_msg>Change minor spacing issue<commit_after>var pingPongType = function(i) {
  if ((i % 5 === 0) || (i % 3 === 0) || (i % 15 === 0)) {
    if (i % 15 === 0) {
        return "pingpong";
    } else if (i % 5 === 0) {
        return "pong";
    } else {
        return "ping";
    }
  } else {
    return i;
  }
}

$(function() {
  $("#game").submit(function(event) {
    $('#outputList').empty();

    var number = parseInt($("#userNumber").val());
    var warning = "Whoops! Please enter an integer!"

    if (Number.isNaN(number) === true) {
      alert(warning);
    }

    for (var i = 1; i <= number; i += 1) {
      var output = pingPongType(i)
      $('#outputList').append("
" + output + "
")
    }

    event.preventDefault();
  });
});
<|endoftext|>


<commit_before>var Servant = {
  api: Affiliation.org[localStorage.affiliationKey1].servantApi,
  msgNone: 'Ingen kontorvakt nå',
  msgError: 'Frakoblet fra vaktplan',

  debugServant: 0,
  debugServantString: '11:00-12:00 Steinar Hagen\n12:00-13:00 Espen Skarsbø Kristoffersen Olsen\n13:00-14:00 Aina Elisabeth Thunestveit',

  get: function(callback) {
    if (callback == undefined) {
      console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.');
      return;
    }

    // check if the affiliation has changed
    if (this.api != Affiliation.org[localStorage.affiliationKey1].servantApi) {
      this.api = Affiliation.org[localStorage.affiliationKey1].servantApi;
    }

    // Receives the meeting plan for today
    var self = this;
    Ajaxer.getPlainText({
      url: self.api,
      success: function(servant) {

        // If servant debugging is enabled
        if (self.debugServant) {
          servant = self.debugServantString;
        }

        servantList = servant.split("\n");
        currentServant = servantList[0];

        // If it's an actual servant with a time slot like this:
        // 12:00-13:00: Michael Johansen
        if (currentServant.match(/\d+:\d+\-\d+:\d+/)) {
          // Match out the name from the line
          var pieces = currentServant.match(/(\d+:\d+\-\d+:\d+) ([0-9a-zA-ZæøåÆØÅ \-]+)/);
          var timeSlot = pieces[1];
          var servantName = pieces[2];

          // If we are currently within the specified timeslot "12:00-13:00"
          var timePieces = timeSlot.split("-"); // ["12:00", "13:00"]
          var startTime = timePieces[0].split(":"); // ["12", "00"]
          var endTime = timePieces[1].split(":"); // ["13", "00"]
          var now = new Date();
          var start = new Date();
          start.setHours(startTime[0]);
          start.setMinutes(startTime[1]);
          var end = new Date();
          end.setHours(endTime[0]);
          end.setMinutes(endTime[1]);

          if (start <= now && now <= end) {

            // If the servantname is quite long...
            if (servantName.length >= 25) {
              if (servantName.split(" ").length >= 3) {
                names = servantName.split(" ");
                // ...we'll shorten all middle names to one letter
                for (var i = names.length - 2; i >= 1; i--) {
                  names[i] = names[i].charAt(0).toUpperCase()+'.';
                }
                servantName = '';
                for (i in names) {
                  servantName += names[i] + " ";
                }
              }
            }

            callback('Vakt: '+servantName);
          }
          else {
            // No servant in this timeslot
            callback(self.msgNone);
          }
        }
        else {
          // No more servants today
          callback(self.msgNone);
        }
      },
      error: function(jqXHR, text, err) {
        if (DEBUG) console.log('ERROR: Failed to get current servant.');
        callback(self.msgError);
      },
    });
  },
}<commit_msg>servant: simplified fetching of API address<commit_after>var Servant = {
  msgNone: 'Ingen kontorvakt nå',
  msgError: 'Frakoblet fra vaktplan',

  debugServant: 0,
  debugServantString: '11:00-12:00 Steinar Hagen\n12:00-13:00 Espen Skarsbø Kristoffersen Olsen\n13:00-14:00 Aina Elisabeth Thunestveit',

  get: function(callback) {
    if (callback == undefined) {
      console.log('ERROR: Callback is required. In the callback you should insert the results into the DOM.');
      return;
    }

    var api = Affiliation.org[localStorage.affiliationKey1].servantApi;

    // Receives the meeting plan for today
    var self = this;
    Ajaxer.getPlainText({
      url: api,
      success: function(servant) {

        // If servant debugging is enabled
        if (self.debugServant) {
          servant = self.debugServantString;
        }

        servantList = servant.split("\n");
        currentServant = servantList[0];

        // If it's an actual servant with a time slot like this:
        // 12:00-13:00: Michael Johansen
        if (currentServant.match(/\d+:\d+\-\d+:\d+/)) {
          // Match out the name from the line
          var pieces = currentServant.match(/(\d+:\d+\-\d+:\d+) ([0-9a-zA-ZæøåÆØÅ \-]+)/);
          var timeSlot = pieces[1];
          var servantName = pieces[2];

          // If we are currently within the specified timeslot "12:00-13:00"
          var timePieces = timeSlot.split("-"); // ["12:00", "13:00"]
          var startTime = timePieces[0].split(":"); // ["12", "00"]
          var endTime = timePieces[1].split(":"); // ["13", "00"]
          var now = new Date();
          var start = new Date();
          start.setHours(startTime[0]);
          start.setMinutes(startTime[1]);
          var end = new Date();
          end.setHours(endTime[0]);
          end.setMinutes(endTime[1]);

          if (start <= now && now <= end) {

            // If the servantname is quite long...
            if (servantName.length >= 25) {
              if (servantName.split(" ").length >= 3) {
                names = servantName.split(" ");
                // ...we'll shorten all middle names to one letter
                for (var i = names.length - 2; i >= 1; i--) {
                  names[i] = names[i].charAt(0).toUpperCase()+'.';
                }
                servantName = '';
                for (i in names) {
                  servantName += names[i] + " ";
                }
              }
            }

            callback('Vakt: '+servantName);
          }
          else {
            // No servant in this timeslot
            callback(self.msgNone);
          }
        }
        else {
          // No more servants today
          callback(self.msgNone);
        }
      },
      error: function(jqXHR, text, err) {
        if (DEBUG) console.log('ERROR: Failed to get current servant.');
        callback(self.msgError);
      },
    });
  },
}<|endoftext|>


<commit_before>"use strict";
const RACE_JSON_URL = "data/races.json";

let amount, count;

let raceData;

function loadRaceJson () {
	loadJSON(RACE_JSON_URL, onJsonLoad)
}

window.onload = function load () {
	loadRaceJson();
	prevent();
};

function onJsonLoad (data) {
	raceData = data.race;

	$("#rollbutton").click(rollstats);
	$(".base").on("input", changeBase);
	$("input.choose").on("change", choose);

	const names = raceData.map(x => x.name).sort();
	const options = names.map(name => `<option>${name}</option>`).join();
	$("#race").append(options).change(changeRace).change();

	if (window.location.hash) window.onhashchange();
	else window.location.hash = "#rolled";
}

const STATS_MIN = 8;
const STATS_MAX = 15;
function prevent () {
	for (let i = 1; i < 7; ++i) {
		const input = $(`#inputBox${i}`);
		input.on("change", function (e) {
			let num = parseInt(this.value);

			if (num < STATS_MIN) {
				this.value = "8"
			}
			if (num > STATS_MAX) {
				this.value = "15"
			}
			if (isNaN(num)) {
				this.value = "8"
			}
			changeTotal();
		})
	}
}

window.onhashchange = function hashchange () {
	const hash = window.location.hash.slice(1);
	$(".statmethod").hide();
	$("#" + hash).show();
};

function getCost (n) {
	if (n < 14) return n - 8;
	if (n === 14) return 7;
	return 9
}

function choose () {
	if ($("input.choose:checked").length > count) return this.checked = false;

	$(".racial", this.parentNode.parentNode)
		.val(this.checked ? amount : 0);
	changeTotal()
}

function changeRace () {
	const race = this.value;
	const stats = raceData
		.find(({name}) => name === race).ability;

	$(".racial").val(0);
	for (const key in stats) $(`#${key} .racial`).val(stats[key])

	changeTotal();
	$(".choose").hide().prop("checked", false);

	if (!stats.choose) return;

	const {from} = stats.choose[0];
	amount = stats.choose[0].amount || 1;
	count = stats.choose[0].count;

	$("td.choose").text(`Choose ${count}`).show();
	from.forEach(key => $(`#${key} .choose`).show())
}

function changeTotal () {
	$("#pointbuy tr[id]").each((i, el) => {
		const [base, racial, total, mod] = $("input", el).get();
		const raw = total.value = Number(base.value) + Number(racial.value);
		mod.value = Math.floor((raw - 10) / 2)
	})
}

function changeBase (e) {
	const budget = Number($("#budget").val());

	let cost = 0;
	$(".base").each((i, el) => cost += getCost(Number(el.value)));

	this.value = this.dataset.prev;
	if (cost > budget) return this.value;

	this.dataset.prev = this.value;
	$("#remaining").val(budget - cost);

	changeTotal()
}

function rollstats () {
	var rolls = [];
	for (var i = 0; i < 6; i++) {
		var curroll = droll.roll("4d6").rolls.sort().splice(1);
		curroll = curroll[0] + curroll[1] + curroll[2];
		rolls.push(curroll);
	}

	$("#rolled #rolls").prepend("
" + rolls.join(", ") + "
");
	$("#rolled #rolls p:eq(10)").remove();
}
<commit_msg>refactor(statgen) merge and lint<commit_after>"use strict";
const RACE_JSON_URL = "data/races.json";

let amount, count;

let raceData;

function loadRaceJson () {
	loadJSON(RACE_JSON_URL, onJsonLoad)
}

window.onload = function load () {
	loadRaceJson();
	prevent();
};

function onJsonLoad (data) {
	raceData = data.race;

	$("#rollbutton").click(rollstats);
	$(".base").on("input", changeBase);
	$("input.choose").on("change", choose);

	const names = raceData.map(x => x.name).sort();
	const options = names.map(name => `<option>${name}</option>`).join();
	$("#race").append(options).change(changeRace).change();

	if (window.location.hash) window.onhashchange();
	else window.location.hash = "#rolled";
}

const STATS_MIN = 8;
const STATS_MAX = 15;
function prevent () {
	for (let i = 1; i < 7; ++i) {
		const input = $(`#inputBox${i}`);
		input.on("change", function(e) {
			let num = parseInt(this.value)
			if (isNaN(num)) {
				this.value = 8;
			} else {
				this.value = Math.max(Math.min(num, STATS_MAX), STATS_MIN);
			}
			changeTotal();
		})
	}
}

window.onhashchange = function hashchange () {
	const hash = window.location.hash.slice(1);
	$(".statmethod").hide();
	$("#" + hash).show();
};

function getCost (n) {
	if (n < 14) return n - 8;
	if (n === 14) return 7;
	return 9
}

function choose () {
	if ($("input.choose:checked").length > count) return this.checked = false;

	$(".racial", this.parentNode.parentNode)
		.val(this.checked ? amount : 0);
	changeTotal()
}

function changeRace () {
	const race = this.value;
	const stats = raceData
		.find(({name}) => name === race).ability;

	$(".racial").val(0);
	for (const key in stats) $(`#${key} .racial`).val(stats[key])

	changeTotal();
	$(".choose").hide().prop("checked", false);

	if (!stats.choose) return;

	const {from} = stats.choose[0];
	amount = stats.choose[0].amount || 1;
	count = stats.choose[0].count;

	$("td.choose").text(`Choose ${count}`).show();
	from.forEach(key => $(`#${key} .choose`).show())
}

function changeTotal () {
	$("#pointbuy tr[id]").each((i, el) => {
		const [base, racial, total, mod] = $("input", el).get();
		const raw = total.value = Number(base.value) + Number(racial.value);
		mod.value = Math.floor((raw - 10) / 2)
	})
}

function changeBase (e) {
	const budget = Number($("#budget").val());

	let cost = 0;
	$(".base").each((i, el) => cost += getCost(Number(el.value)));

	this.value = this.dataset.prev;
	if (cost > budget) return this.value;

	this.dataset.prev = this.value;
	$("#remaining").val(budget - cost);

	changeTotal()
}

function rollstats () {
	var rolls = [];
	for (var i = 0; i < 6; i++) {
		var curroll = droll.roll("4d6").rolls.sort().splice(1);
		curroll = curroll[0] + curroll[1] + curroll[2];
		rolls.push(curroll);
	}

	$("#rolled #rolls").prepend("
" + rolls.join(", ") + "
");
	$("#rolled #rolls p:eq(10)").remove();
}
<|endoftext|>


<commit_before>'use strict';

// Required args: data, prefix
function storage_init(args){
    storage_prefix = args['prefix'];

    for(var key in args['data']){
        var data = args['data'][key];
        if(typeof args['data'][key] !== 'object'){
            data = {
              'default': data,
              'type': 'setting',
            };
        }

        storage_info[key] = {
          'default': data['default'],
          'type': data['type'] || 'setting',
        };
        storage_data[key] = window.localStorage.getItem(storage_prefix + key);

        if(storage_data[key] === null){
            storage_data[key] = storage_info[key]['default'];
        }

        storage_data[key] = storage_type_convert({
          'key': key,
          'value': storage_data[key],
        });

        if(storage_info[key]['type'] !== 'setting'){
            storage_info[key]['best'] = storage_data[key];
        }
    }
}

// Optional args: bests
function storage_reset(args){
    args = args || {};
    args['bests'] = args['bests'] || false;

    if(!window.confirm('Reset?')){
        return false;
    }

    for(var key in storage_data){
        if(storage_info[key]['type'] !== 'setting'){
            if(!args['bests']){
                continue;
            }

            storage_info[key]['best'] = storage_info[key]['default'];
        }

        storage_data[key] = storage_info[key]['default'];
        window.localStorage.removeItem(storage_prefix + key);
    }

    if(args['bests']){
        storage_save();
    }
    storage_update();
    return true;
}

// Optional args: bests
function storage_save(args){
    args = args || {};
    args['bests'] = args['bests'] || false;

    for(var key in storage_data){
        var data = '';

        if(storage_info[key]['type'] === 'setting'){
            if(args['bests']){
                continue;
            }

            storage_data[key] = document.getElementById(key)[
              typeof(storage_info[key]['default']) === 'boolean'
                ? 'checked'
                : 'value'
            ];

            data = storage_type_convert({
              'key': key,
              'value': storage_data[key],
            });
            storage_data[key] = data;

        }else{
            data = storage_type_convert({
              'key': key,
              'value': storage_data[key],
            });

            if(storage_info[key]['type'] < 0){
                if(data < storage_info[key]['best']){
                    storage_info[key]['best'] = data;
                }

            }else if(storage_data[key] > storage_info[key]['best']){
                storage_info[key]['best'] = data;
            }
        }

        if(data !== storage_info[key]['default']){
            window.localStorage.setItem(
              storage_prefix + key,
              data
            );

        }else{
            window.localStorage.removeItem(storage_prefix + key);
        }
    }
}

// Required args: key, value
function storage_type_convert(args){
    var storage_default = storage_info[args['key']]['default'];

    if(typeof storage_default === 'string'){
        return args['value'];

    }else if(!isNaN(parseFloat(storage_default))){
        return parseFloat(args['value']);

    }else if(typeof(storage_default) === 'boolean'
      && typeof(args['value']) !== 'boolean'){
        return args['value'] === 'true';
    }

    return args['value'];
}

function storage_update(){
    for(var key in storage_data){
        if(storage_info[key]['type'] !== 'setting'){
            continue;
        }

        document.getElementById(key)[
          typeof(storage_info[key]['default']) === 'boolean'
            ? 'checked'
            : 'value'
        ] = storage_data[key];
    }
}

var storage_data = {};
var storage_info = {};
var storage_prefix = '';
<commit_msg>added common core.js usage to common storage.js<commit_after>'use strict';

// Required args: data, prefix
function storage_init(args){
    storage_prefix = args['prefix'];

    for(var key in args['data']){
        var data = args['data'][key];
        if(typeof args['data'][key] !== 'object'){
            data = {
              'default': data,
              'type': 'setting',
            };
        }

        storage_info[key] = {
          'default': data['default'],
          'type': data['type'] || 'setting',
        };
        storage_data[key] = window.localStorage.getItem(storage_prefix + key);

        if(storage_data[key] === null){
            storage_data[key] = storage_info[key]['default'];
        }

        storage_data[key] = storage_type_convert({
          'key': key,
          'value': storage_data[key],
        });

        if(storage_info[key]['type'] !== 'setting'){
            storage_info[key]['best'] = storage_data[key];
        }
    }
}

// Optional args: bests
function storage_reset(args){
    args = core_args({
      'args': args,
      'defaults': {
        'bests': false,
      },
    });

    if(!window.confirm('Reset?')){
        return false;
    }

    for(var key in storage_data){
        if(storage_info[key]['type'] !== 'setting'){
            if(!args['bests']){
                continue;
            }

            storage_info[key]['best'] = storage_info[key]['default'];
        }

        storage_data[key] = storage_info[key]['default'];
        window.localStorage.removeItem(storage_prefix + key);
    }

    if(args['bests']){
        storage_save();
    }
    storage_update();
    return true;
}

// Optional args: bests
function storage_save(args){
    args = core_args({
      'args': args,
      'defaults': {
        'bests': false,
      },
    });

    for(var key in storage_data){
        var data = '';

        if(storage_info[key]['type'] === 'setting'){
            if(args['bests']){
                continue;
            }

            storage_data[key] = document.getElementById(key)[
              typeof(storage_info[key]['default']) === 'boolean'
                ? 'checked'
                : 'value'
            ];

            data = storage_type_convert({
              'key': key,
              'value': storage_data[key],
            });
            storage_data[key] = data;

        }else{
            data = storage_type_convert({
              'key': key,
              'value': storage_data[key],
            });

            if(storage_info[key]['type'] < 0){
                if(data < storage_info[key]['best']){
                    storage_info[key]['best'] = data;
                }

            }else if(storage_data[key] > storage_info[key]['best']){
                storage_info[key]['best'] = data;
            }
        }

        if(data !== storage_info[key]['default']){
            window.localStorage.setItem(
              storage_prefix + key,
              data
            );

        }else{
            window.localStorage.removeItem(storage_prefix + key);
        }
    }
}

// Required args: key, value
function storage_type_convert(args){
    var storage_default = storage_info[args['key']]['default'];

    if(typeof storage_default === 'string'){
        return args['value'];

    }else if(!isNaN(parseFloat(storage_default))){
        return parseFloat(args['value']);

    }else if(typeof(storage_default) === 'boolean'
      && typeof(args['value']) !== 'boolean'){
        return args['value'] === 'true';
    }

    return args['value'];
}

function storage_update(){
    for(var key in storage_data){
        if(storage_info[key]['type'] !== 'setting'){
            continue;
        }

        document.getElementById(key)[
          typeof(storage_info[key]['default']) === 'boolean'
            ? 'checked'
            : 'value'
        ] = storage_data[key];
    }
}

var storage_data = {};
var storage_info = {};
var storage_prefix = '';
<|endoftext|>


<commit_before>(function() {
    var MetadataTabView = OCA.Files.DetailTabView.extend({
        id: 'metadataTabView',
        className: 'tab metadataTabView',

        getLabel: function() {
            return t('metadata', 'Metadata');
        },

        getIcon: function() {
            return 'icon-details';
        },

        render: function() {
            var fileInfo = this.getFileInfo();

            if (fileInfo) {
                this.$el.html('

'
                    + t('metadata', 'Reading metadata ...')
                    + '

');

                var url = OC.generateUrl('/apps/metadata/get'),
                    data = {source: fileInfo.getFullPath()},
                    _self = this;
                $.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'json',
                    data: data,
                    async: true,
                    success: function(data) {
                        _self.updateDisplay(data);
                    }
                });
            }
        },

        canDisplay: function(fileInfo) {
            if (!fileInfo || fileInfo.isDirectory() || !fileInfo.has('mimetype')) {
                return false;
            }
            var mimetype = fileInfo.get('mimetype');

            return (['audio/flac', 'audio/mp4', 'audio/mpeg', 'audio/ogg', 'audio/wav',
                'image/gif', 'image/jpeg', 'image/png', 'image/tiff', 'image/x-dcraw',
                'video/3gpp', 'video/dvd', 'video/mp4', 'video/mpeg', 'video/quicktime',
                'video/webm', 'video/x-flv', 'video/x-matroska', 'video/x-msvideo'].indexOf(mimetype) > -1);
        },

        formatValue: function(value) {
            return Array.isArray(value) ? value.join('; ') : value;
        },

        updateDisplay: function(data) {
            var html = '';
            var showLocation = false;

            if (data.response === 'success') {
                html += '
';

                var metadata = data.metadata;
                for (m in metadata) {
                    html += '
' + m + ':	' + this.formatValue(metadata[m]) + '
';
                }

                showLocation = (data.loc !== null) || ((data.lat !== null) && (data.lon !== null));
                if (showLocation) {
                    var location;

                    if (data.loc !== null) {
                        var address = [];
                        this.add(data.loc.city, address);
                        this.add(data.loc.state, address);
                        this.add(data.loc.country, address);
                        location = address.join(', ');

                    } else {
                        location = t('metadata', 'Resolving, click here to view on map ...');
                    }

                    if ((data.lat !== null) && (data.lon !== null)) {
                        var url = 'https://nominatim.openstreetmap.org/reverse',
                            params = {lat: data.lat, lon: data.lon, format: 'json', zoom: 18},
                            _self = this;
                        $.ajax({
                            type: 'GET',
                            url: url,
                            dataType: 'json',
                            data: params,
                            async: true,
                            success: function(data) {
                                _self.updateLocation(data);
                            },
                            error: function() {
                                if (data.loc === null) {
                                    _self.updateLocation({error: t('metadata', 'Nominatim service unavailable, click here to view on map')});
                                }
                            }
                        });
                    }

                    html += '
' + t('metadata', 'Location') + ':	' + location + '
';
                }

                html += '
';

            } else {
                html = data.msg;
            }

            this.$el.find('.get-metadata').html(html);

            if (showLocation) {
                var _self = this;

                this.$el.find('.get-location')
                    .click(function() {
                        if ((data.lat === null) || (data.lon === null)) {
                            var url = 'https://nominatim.openstreetmap.org/search',
                                params = {city: data.loc.city, state: data.loc.state, country: data.loc.country, format: 'json', limit: 1};
                            $.ajax({
                                type: 'GET',
                                url: url,
                                dataType: 'json',
                                data: params,
                                async: true,
                                success: function(data) {
                                    if (data.length > 0) {
                                        _self.showMap(data[0]);

                                    } else {
                                        console.log(t('metadata', 'Location could not be determined'));
                                    }
                                },
                                error: function() {
                                    console.log(t('metadata', 'Nominatim service unavailable'));
                                }
                            });

                        } else {
                            _self.showMap(data);
                        }
                    })
            }
        },

        showMap: function(data) {
            var bbox = [data.lon - 0.0051, data.lat - 0.0051, data.lon - -0.0051, data.lat - -0.0051];

            var iframe = document.createElement('iframe');
            iframe.setAttribute('width', '100%');
            iframe.setAttribute('height', '100%');
            iframe.setAttribute('src', 'https://www.openstreetmap.org/export/embed.html?bbox=' + bbox.join() + '&marker=' + data.lat + ',' + data.lon);

            $(document.createElement('div'))
                .prop('title', 'OpenStreetMap')
                .css('background', 'url(' + OC.imagePath('core','loading.gif') + ') center center no-repeat')
                .append(iframe)
                .appendTo($('body'))
                .ocdialog({
                    width: 900,
                    height: 680,
                    closeOnEscape: true,
                    modal: true,
                    close: function() {
                        var _self = this;
                        setTimeout(function() {
                            $(_self).ocdialog('destroy').remove();
                        }, 3000);
                    }
                });
        },

        updateLocation: function(data) {
            var html = '';

            if (data.error) {
                html = data.error;

            } else {
                var location = data.address;
                var address = [];
                this.add(location.building || location.attraction || location.artwork || location.monument || location.viewpoint || location.house_number, address);
                this.add(location.road || location.pedestrian || location.path || location.steps || location.footway || location.cycleway || location.bridleway || location.construction, address);
                this.add(location.city || location.town || location.village || location.hamlet || location.isolated_dwelling, address);
                this.add(location.country, address);
                html = address.join(', ');
            }

            this.$el.find('.get-location').html(html);
        },

        add: function(val, array) {
            if (val) {
                array.push(val);
            }
        },
    });

    OCA.Metadata = OCA.Metadata || {};

    OCA.Metadata.MetadataTabView = MetadataTabView;
})();
<commit_msg>Update tabview.js<commit_after>(function() {
    var MetadataTabView = OCA.Files.DetailTabView.extend({
        id: 'metadataTabView',
        className: 'tab metadataTabView',

        getLabel: function() {
            return t('metadata', 'Metadata');
        },

        getIcon: function() {
            return 'icon-details';
        },

        render: function() {
            var fileInfo = this.getFileInfo();

            if (fileInfo) {
                this.$el.html('

'
                    + t('metadata', 'Reading metadata ...')
                    + '

');

                var url = OC.generateUrl('/apps/metadata/get'),
                    data = {source: fileInfo.getFullPath()},
                    _self = this;
                $.ajax({
                    type: 'GET',
                    url: url,
                    dataType: 'json',
                    data: data,
                    async: true,
                    success: function(data) {
                        _self.updateDisplay(data);
                    }
                });
            }
        },

        canDisplay: function(fileInfo) {
            if (!fileInfo || fileInfo.isDirectory() || !fileInfo.has('mimetype')) {
                return false;
            }
            var mimetype = fileInfo.get('mimetype');

            return (['audio/flac', 'audio/mp4', 'audio/mpeg', 'audio/ogg', 'audio/wav',
                'image/gif', 'image/jpeg', 'image/png', 'image/tiff', 'image/x-dcraw',
                'video/3gpp', 'video/dvd', 'video/mp4', 'video/mpeg', 'video/quicktime',
                'video/webm', 'video/x-flv', 'video/x-matroska', 'video/x-msvideo'].indexOf(mimetype) > -1);
        },

        formatValue: function(value) {
            return Array.isArray(value) ? value.join('; ') : value;
        },

        updateDisplay: function(data) {
            var html = '';
            var showLocation = false;

            if (data.response === 'success') {
                html += '
';

                var metadata = data.metadata;
                for (m in metadata) {
                    html += '
' + m + ':	' + this.formatValue(metadata[m]) + '
';
                }

                showLocation = (data.loc !== null) || ((data.lat !== null) && (data.lon !== null));
                if (showLocation) {
                    var location;

                    if (data.loc !== null) {
                        var address = [];
                        this.add(data.loc.city, address);
                        this.add(data.loc.state, address);
                        this.add(data.loc.country, address);
                        location = address.join(', ');

                    } else {
                        location = t('metadata', 'Resolving, click here to view on map ...');
                    }

                    if ((data.lat !== null) && (data.lon !== null)) {
                        var url = 'https://nominatim.openstreetmap.org/reverse',
                            params = {lat: data.lat, lon: data.lon, format: 'json', zoom: 18},
                            _self = this;
                        $.ajax({
                            type: 'GET',
                            url: url,
                            dataType: 'json',
                            data: params,
                            async: true,
                            success: function(data) {
                                _self.updateLocation(data);
                            },
                            error: function() {
                                if (data.loc === null) {
                                    _self.updateLocation({error: t('metadata', 'Nominatim service unavailable, click here to view on map')});
                                }
                            }
                        });
                    }

                    html += '
' + t('metadata', 'Location') + ':	' + location + '
';
                }

                html += '
';

            } else {
                html = data.msg;
            }

            this.$el.find('.get-metadata').html(html);

            if (showLocation) {
                var _self = this;

                this.$el.find('.get-location')
                    .click(function() {
                        if ((data.lat === null) || (data.lon === null)) {
                            var url = 'https://nominatim.openstreetmap.org/search',
                                params = {city: data.loc.city, state: data.loc.state, country: data.loc.country, format: 'json', limit: 1};
                            $.ajax({
                                type: 'GET',
                                url: url,
                                dataType: 'json',
                                data: params,
                                async: true,
                                success: function(data) {
                                    if (data.length > 0) {
                                        _self.showMap(data[0]);

                                    } else {
                                        console.log(t('metadata', 'Location could not be determined'));
                                    }
                                },
                                error: function() {
                                    console.log(t('metadata', 'Nominatim service unavailable'));
                                }
                            });

                        } else {
                            _self.showMap(data);
                        }
                    })
            }
        },

        showMap: function(data) {
            var bbox = [data.lon - 0.0051, data.lat - 0.0051, data.lon - -0.0051, data.lat - -0.0051];

            var iframe = document.createElement('iframe');
            iframe.setAttribute('width', '100%');
            iframe.setAttribute('height', '100%');
            iframe.setAttribute('src', 'https://www.openstreetmap.org/export/embed.html?bbox=' + bbox.join() + '&marker=' + data.lat + ',' + data.lon);

            $(document.createElement('div'))
                .prop('title', 'OpenStreetMap')
                .css('background', 'url(' + OC.imagePath('core','loading.gif') + ') center center no-repeat')
                .append(iframe)
                .appendTo($('body'))
                .ocdialog({
                    width: 900,
                    height: 680,
                    closeOnEscape: true,
                    modal: true,
                    close: function() {
                        var _self = this;
                        setTimeout(function() {
                            $(_self).ocdialog('destroy').remove();
                        }, 3000);
                    }
                });
        },

        updateLocation: function(data) {
            var html = '';

            if (data.error) {
                html = data.error;

            } else {
                var location = data.address;
                var address = [];
                this.add(location.building || location.attraction || location.artwork || location.monument || location.viewpoint || location.museum || location.cafe || location.garden || location.aerodrome || location.address29 || location.house_number, address);
                this.add(location.road || location.pedestrian || location.path || location.steps || location.footway || location.cycleway || location.bridleway || location.construction, address);
                this.add(location.city || location.town || location.village || location.hamlet || location.isolated_dwelling, address);
                this.add(location.country, address);
                html = address.join(', ');
            }

            this.$el.find('.get-location').html(html);
        },

        add: function(val, array) {
            if (val) {
                array.push(val);
            }
        },
    });

    OCA.Metadata = OCA.Metadata || {};

    OCA.Metadata.MetadataTabView = MetadataTabView;
})();
<|endoftext|>