<commit_before>module.exports = {
    "extends": "eslint:recommended",
    "env" : {
        "browser": true,
        "node": true
    },
    "rules": {
        // enable additional rules, mostly with auto fix...
        "strict" : ["error", "global"],
        "indent": ["error", 4],
        "no-multi-spaces" : ["error"],
        "linebreak-style": ["error", "unix"],
        "quotes": ["error", "single", {"avoidEscape": true}],
        "semi": ["error", "always"],
        "key-spacing": ["error", { "beforeColon": false, "afterColon": true}],
        "keyword-spacing": ["error", { "before": true }],
        "array-bracket-spacing": ["error", "never"],
        "comma-spacing": ["error", {"before": false, "after": true}],
        "semi-spacing": ["error", {"before": false, "after": true}],
        "space-in-parens": ["error", "never"],
        "semi": ["error", "always"],
        "linebreak-style": ["error", "unix"],
        "max-len" : ["error", 80],
        "no-multiple-empty-lines": "error",
        "no-trailing-spaces" : ["error"]
    }
};
<commit_msg>fix eslint config<commit_after>module.exports = {
    "extends": "eslint:recommended",
    "env" : {
        "browser": true,
        "node": true
    },
    "rules": {
        // enable additional rules, mostly with auto fix...
        "strict" : ["error", "global"],
        "indent": ["error", 4],
        "no-multi-spaces" : ["error"],
        "linebreak-style": ["error", "unix"],
        "quotes": ["error", "single", {"avoidEscape": true}],
        "semi": ["error", "always"],
        "key-spacing": ["error", { "beforeColon": false, "afterColon": true}],
        "keyword-spacing": ["error", { "before": true }],
        "array-bracket-spacing": ["error", "never"],
        "comma-spacing": ["error", {"before": false, "after": true}],
        "semi-spacing": ["error", {"before": false, "after": true}],
        "space-in-parens": ["error", "never"],
        "max-len" : ["error", 80],
        "no-multiple-empty-lines": "error",
        "no-trailing-spaces" : ["error"]
    }
};
<|endoftext|>


<commit_before>module.exports = {
    extends: [
        "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
        "plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
        "plugin:prettier/recommended", // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors.
        "prettier"
    ],
    parser: "@typescript-eslint/parser",
    parserOptions: {
        sourceType: "module",
        ecmaVersion: 2020,
        ecmaFeatures: {
            jsx: true // Allows for the parsing of JSX
        }
    },
    plugins: [
        "@typescript-eslint"
    ],
    settings: {
        react: {
            version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
        }
    },
    // Fine tune rules
    rules: {
        "@typescript-eslint/no-var-requires": 0
    },
};
<commit_msg>Remove obsolete entry from eslint config.<commit_after>module.exports = {
    extends: [
        "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react
        "plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
        "plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors.
    ],
    parser: "@typescript-eslint/parser",
    parserOptions: {
        sourceType: "module",
        ecmaVersion: 2020,
        ecmaFeatures: {
            jsx: true // Allows for the parsing of JSX
        }
    },
    plugins: [
        "@typescript-eslint"
    ],
    settings: {
        react: {
            version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use
        }
    },
    // Fine tune rules
    rules: {
        "@typescript-eslint/no-var-requires": 0
    },
};
<|endoftext|>


<commit_before>const normalGlobals = [];

const hueGlobals = [
  // global_js_constants.mako
  'AUTOCOMPLETE_TIMEOUT',
  'CACHEABLE_TTL',
  'CSRF_TOKEN',
  'DOCUMENT_TYPES',
  'DROPZONE_HOME_DIR',
  'ENABLE_SQL_SYNTAX_CHECK',
  'HAS_MULTI_CLUSTER',
  'HAS_CATALOG',
  'HAS_OPTIMIZER',
  'HAS_WORKLOAD_ANALYTICS',
  'HUE_I18n',
  'HUE_VERSION',
  'IS_K8S_ONLY',
  'IS_NEW_INDEXER_ENABLED',
  'IS_S3_ENABLED',
  'isIE11',
  'KO_DATERANGEPICKER_LABELS',
  'LOGGED_USERGROUPS',
  'LOGGED_USERNAME',
  'METASTORE_PARTITION_LIMIT',
  'USER_HOME_DIR',
  'WorkerGlobalScope',

  // other misc
  'ace',
  'CodeMirror',
  'impalaDagre',
  'less',
  'MediumEditor',
  'moment',
  'Role',
  'trackOnGA',
  '__webpack_public_path__',

  // jest
  'afterAll',
  'afterEach',
  'beforeAll',
  'beforeEach',
  'describe',
  'expect',
  'fail',
  'fdescribe',
  'fit',
  'it',
  'jest',
  'spyOn',
  'xdescribe',
  'xit'
];

const globals = normalGlobals.concat(hueGlobals).reduce((acc, key) => {
  acc[key] = true;
  return acc;
}, {});

module.exports = {
  env: {
    browser: true,
    node: true,
    es6: true,
    jasmine: true
  },
  overrides: [
    {
      files: ['*.vue'],
      extends: [
        'plugin:prettier/recommended',
        'plugin:vue/vue3-recommended',
        'plugin:@typescript-eslint/recommended'
      ],
      parser: 'vue-eslint-parser',
      parserOptions: {
        parser: "@typescript-eslint/parser"
      },
      plugins: ['vue', '@typescript-eslint'],
      rules: {
        'vue/max-attributes-per-line': [
          'error',
          {
            singleline: 10,
            multiline: {
              max: 1,
              allowFirstLine: false
            }
          }
        ],
        'vue/html-self-closing': [
          "error",
          {
            "html": {
              "void": "any"
            }
          }
        ],
        'vue/singleline-html-element-content-newline': 0, // Conflicts with prettier
      }
    },
    {
      files: ['*.d.ts'],
      extends: ['plugin:@typescript-eslint/recommended'],
      parser: '@typescript-eslint/parser',
      plugins: ['jest', '@typescript-eslint'],
      rules: {
        'no-useless-constructor': 0
      }
    },
    {
      files: ['*.ts'],
      extends: ['plugin:@typescript-eslint/recommended'],
      parser: '@typescript-eslint/parser',
      plugins: ['jest', '@typescript-eslint']
    }
  ],
  extends: ['plugin:prettier/recommended'],
  globals: globals,
  parser: 'babel-eslint',
  parserOptions: {
    parser: 'babel-eslint',
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      legacyDecorators: true
    }
  },
  plugins: ['jest'],
  rules: {
    'jest/no-focused-tests': 'error',
    'jest/valid-expect': 'error',
    'new-cap': 0,
    'no-console': 0,
    'no-restricted-syntax': [
      'error',
      {
        selector:
          'CallExpression[callee.object.name="console"][callee.property.name!=/^(warn|error|info|trace)$/]',
        message: 'Unexpected property on console object was called'
      }
    ],
    'no-extra-boolean-cast': 0,
    'no-invalid-this': 0,
    'no-lonely-if': 2,
    'no-throw-literal': 0,
    'no-unused-vars': [
      'error',
      {
        vars: 'all',
        args: 'none',
        ignoreRestSiblings: true,
        varsIgnorePattern: '_[a-zA-Z0-9_]+'
      }
    ],
    'no-useless-constructor': 2,
    'no-var': 1,
    'no-undef': 2,
    'one-var': 0,
    'prefer-arrow-callback': 2,
    'prefer-const': ['warn', { destructuring: 'all' }],
    'require-jsdoc': 0,
    strict: 0,
    'valid-jsdoc': 0,
    curly: [2, 'all']
  },
  settings: {}
};
<commit_msg>[frontend] Update eslint rules to allow non-null assertion<commit_after>const normalGlobals = [];

const hueGlobals = [
  // global_js_constants.mako
  'AUTOCOMPLETE_TIMEOUT',
  'CACHEABLE_TTL',
  'CSRF_TOKEN',
  'DOCUMENT_TYPES',
  'DROPZONE_HOME_DIR',
  'ENABLE_SQL_SYNTAX_CHECK',
  'HAS_MULTI_CLUSTER',
  'HAS_CATALOG',
  'HAS_OPTIMIZER',
  'HAS_WORKLOAD_ANALYTICS',
  'HUE_I18n',
  'HUE_VERSION',
  'IS_K8S_ONLY',
  'IS_NEW_INDEXER_ENABLED',
  'IS_S3_ENABLED',
  'isIE11',
  'KO_DATERANGEPICKER_LABELS',
  'LOGGED_USERGROUPS',
  'LOGGED_USERNAME',
  'METASTORE_PARTITION_LIMIT',
  'USER_HOME_DIR',
  'WorkerGlobalScope',

  // other misc
  'ace',
  'CodeMirror',
  'impalaDagre',
  'less',
  'MediumEditor',
  'moment',
  'Role',
  'trackOnGA',
  '__webpack_public_path__',

  // jest
  'afterAll',
  'afterEach',
  'beforeAll',
  'beforeEach',
  'describe',
  'expect',
  'fail',
  'fdescribe',
  'fit',
  'it',
  'jest',
  'spyOn',
  'xdescribe',
  'xit'
];

const globals = normalGlobals.concat(hueGlobals).reduce((acc, key) => {
  acc[key] = true;
  return acc;
}, {});

module.exports = {
  env: {
    browser: true,
    node: true,
    es6: true,
    jasmine: true
  },
  overrides: [
    {
      files: ['*.vue'],
      extends: [
        'plugin:prettier/recommended',
        'plugin:vue/vue3-recommended',
        'plugin:@typescript-eslint/recommended'
      ],
      parser: 'vue-eslint-parser',
      parserOptions: {
        parser: '@typescript-eslint/parser'
      },
      plugins: ['vue', '@typescript-eslint'],
      rules: {
        'vue/max-attributes-per-line': [
          'error',
          {
            singleline: 10,
            multiline: {
              max: 1,
              allowFirstLine: false
            }
          }
        ],
        'vue/html-self-closing': [
          'error',
          {
            html: {
              void: 'any'
            }
          }
        ],
        'vue/singleline-html-element-content-newline': 0, // Conflicts with prettier
        '@typescript-eslint/no-non-null-assertion': 0
      }
    },
    {
      files: ['*.d.ts'],
      extends: ['plugin:@typescript-eslint/recommended'],
      parser: '@typescript-eslint/parser',
      plugins: ['jest', '@typescript-eslint'],
      rules: {
        'no-useless-constructor': 0,
        '@typescript-eslint/no-non-null-assertion': 0
      }
    },
    {
      files: ['*.ts'],
      extends: ['plugin:@typescript-eslint/recommended'],
      parser: '@typescript-eslint/parser',
      plugins: ['jest', '@typescript-eslint'],
      rules: {
        '@typescript-eslint/no-non-null-assertion': 0
      }
    }
  ],
  extends: ['plugin:prettier/recommended'],
  globals: globals,
  parser: 'babel-eslint',
  parserOptions: {
    parser: 'babel-eslint',
    ecmaVersion: 2017,
    sourceType: 'module',
    ecmaFeatures: {
      legacyDecorators: true
    }
  },
  plugins: ['jest'],
  rules: {
    'jest/no-focused-tests': 'error',
    'jest/valid-expect': 'error',
    'new-cap': 0,
    'no-console': 0,
    'no-restricted-syntax': [
      'error',
      {
        selector:
          'CallExpression[callee.object.name="console"][callee.property.name!=/^(warn|error|info|trace)$/]',
        message: 'Unexpected property on console object was called'
      }
    ],
    'no-extra-boolean-cast': 0,
    'no-invalid-this': 0,
    'no-lonely-if': 2,
    'no-throw-literal': 0,
    'no-unused-vars': [
      'error',
      {
        vars: 'all',
        args: 'none',
        ignoreRestSiblings: true,
        varsIgnorePattern: '_[a-zA-Z0-9_]+'
      }
    ],
    'no-useless-constructor': 2,
    'no-var': 1,
    'no-undef': 2,
    'one-var': 0,
    'prefer-arrow-callback': 2,
    'prefer-const': ['warn', { destructuring: 'all' }],
    'require-jsdoc': 0,
    strict: 0,
    'valid-jsdoc': 0,
    curly: [2, 'all']
  },
  settings: {}
};
<|endoftext|>


<commit_before>module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "parser": "babel-eslint",
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "comma-dangle": ["error", "always-multiline"],
    "no-console":  "error",
    "no-debugger": "error",
    "indent": [
      "error",
      2
    ],
    "no-multiple-empty-lines": [2, { "max": 2, "maxEOF": 0, "maxEOF": 0 }],
    "no-multi-spaces": [2, {
      "exceptions": {
        "Identifier": true,
        "ClassProperty": true,
        "ImportDeclaration": true,
        "VariableDeclarator": true,
        "AssignmentExpression": true
      }
    }],
    "linebreak-style": [
      "error",
      "unix"
    ],
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "always"
    ],
    "react/prefer-stateless-function": [2, {
      "ignorePureComponents": true
    }],
    "react/prop-types": 2,
    "react/jsx-uses-vars": [2],
    "react/jsx-indent": [2, 2],
    "react/jsx-indent-props": [2, 2],
    "key-spacing": [2, {
      "singleLine": {
        "beforeColon": false,
        "afterColon":  true
      },
      "multiLine": {
        "beforeColon": false,
        "afterColon":  true,
        "mode": "minimum"
      }
    }],
  }
};
<commit_msg>a few more rulz<commit_after>module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "parser": "babel-eslint",
  "extends": "eslint:recommended",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "comma-dangle": ["error", "always-multiline"],
    "no-console":  "error",
    "no-debugger": "error",
    "indent": [
      "error",
      2
    ],
    "object-curly-spacing": ["error", "always"],
    "quotes": ["error", "double"],
    "no-multiple-empty-lines": [2, { "max": 2, "maxEOF": 0, "maxEOF": 0 }],
    "no-multi-spaces": [2, {
      "exceptions": {
        "Identifier": true,
        "ClassProperty": true,
        "ImportDeclaration": true,
        "VariableDeclarator": true,
        "AssignmentExpression": true
      }
    }],
    "linebreak-style": [
      "error",
      "unix"
    ],
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "always"
    ],
    "react/prefer-stateless-function": [2, {
      "ignorePureComponents": true
    }],
    "react/prop-types": 2,
    "react/jsx-uses-vars": [2],
    "react/jsx-indent": [2, 2],
    "react/jsx-indent-props": [2, 2],
    "key-spacing": [2, {
      "singleLine": {
        "beforeColon": false,
        "afterColon":  true
      },
      "multiLine": {
        "beforeColon": false,
        "afterColon":  true,
        "mode": "minimum"
      }
    }],
  }
};
<|endoftext|>


<commit_before>var

/**
 * Constats
 */
COLS = 64,
ROWS = 32,

EMPTY = 0,
SNAKE = 1,
SNAKEH = 3,
SNAKE2 = 4,
SNAKEH2 = 5,
FRUIT = 2,

LEFT  = 0,
UP    = 1,
RIGHT = 2,
DOWN  = 3,

KEY_LEFT  = 37,
KEY_UP    = 38,
KEY_RIGHT = 39,
KEY_DOWN  = 40,

KEY_LEFT2 = 65,
KEY_UP2 = 87,
KEY_RIGHT2 = 68,
KEY_DOWN2 = 83,

/**
 * Game objects
 */
canvas,	  /* HTMLCanvas */
ctx,	  /* CanvasRenderingContext2d */
keystate, /* Object, used for keyboard inputs */
flip,
p1name,
p2name,
frames,   /* number, used for animation */
score2,
score;	  /* number, keep track of the player score */

/**
 * Grid datastructor, usefull in games where the game world is
 * confined in absolute sized chunks of data or information.
 *
 * @type {Object}
 */
grid = {

	width: null,  /* number, the number of columns */
	height: null, /* number, the number of rows */
	_grid: null,  /* Array<any>, data representation */

	/**
	 * Initiate and fill a c x r grid with the value of d
	 * @param  {any}    d default value to fill with
	 * @param  {number} c number of columns
	 * @param  {number} r number of rows
	 */
	init: function(d, c, r) {
		this.width = c;
		this.height = r;

		this._grid = [];
		for (var x=0; x < c; x++) {
			this._grid.push([]);
			for (var y=0; y < r; y++) {
				this._grid[x].push(d);
			}
		}
	},

	/**
	 * Set the value of the grid cell at (x, y)
	 *
	 * @param {any}    val what to set
	 * @param {number} x   the x-coordinate
	 * @param {number} y   the y-coordinate
	 */
	set: function(val, x, y) {
		this._grid[x][y] = val;
	},

	/**
	 * Get the value of the cell at (x, y)
	 *
	 * @param  {number} x the x-coordinate
	 * @param  {number} y the y-coordinate
	 * @return {any}   the value at the cell
	 */
	get: function(x, y) {
		return this._grid[x][y];
	}
}

/**
 * The snake, works as a queue (FIFO, first in first out) of data
 * with all the current positions in the grid with the snake id
 *
 * @type {Object}
 */
snake = {

	direction: null, /* number, the direction */
	last: null,		 /* Object, pointer to the last element in
						the queue */
	_queue: null,	 /* Array<number>, data representation*/

	init: function(d, x, y) {
		this.direction = d;

		this._queue = [];
		this.insert(x, y);
	},

	insert: function(x, y) {
		this._queue.unshift({x:x, y:y});
		this.last = this._queue[0];
	},

	remove: function() {
		return this._queue.pop();
	}
};

snake2 = {

	direction: null, /* number, the direction */
	last: null,		 /* Object, pointer to the last element in
						the queue */
	_queue: null,	 /* Array<number>, data representation*/

	init: function(d, x, y) {
		this.direction = d;

		this._queue = [];
		this.insert(x, y);
	},

	insert: function(x, y) {
		this._queue.unshift({x:x, y:y});
		this.last = this._queue[0];
	},

	remove: function() {
		return this._queue.pop();
	}
};

/**
 * Starts the game
 */
function main() {
	// create and initiate the canvas element
	canvas = document.createElement("canvas");
	canvas.width = COLS*20;
	canvas.height = ROWS*20;
	ctx = canvas.getContext("2d");
	// add the canvas element to the body of the document
	document.body.appendChild(canvas);

	// sets an base font for bigger score display
	ctx.font = "16px Helvetica";

	frames = 0;
	keystate = {};
	// keeps track of the keybourd input
	document.addEventListener("keydown", function(evt) {
		keystate[evt.keyCode] = true;
	});
	document.addEventListener("keyup", function(evt) {
		delete keystate[evt.keyCode];
	});

	// intatiate game objects and starts the game loop
	p1name = prompt("Player 1, please enter your name. \nYou will be light blue and you will start on the bottom" , "player 1");
	p2name = prompt("Player 2, please enter your name. \nYou will be dark blue and you will start on the right" , "player 2")
	init();
	loop();
}

/**
 * Resets and inits game objects
 */
function init() {
	score2  = 0
	score = 0;
	flip = 0;

	grid.init(EMPTY, COLS, ROWS);

	var sp = {x:Math.floor(COLS/2), y:ROWS-1};
	var sp2 = {x:COLS-1, y:Math.floor(ROWS/2)};
	snake.init(UP, sp.x, sp.y);
	snake2.init(LEFT, sp2.x, sp2.y);
	grid.set(SNAKE2, sp2.x, sp2.y);
	grid.set(SNAKE, sp.x, sp.y);

}

function gameover(x,y) {
	if (x > y){
		// player 1 won
		if (x == 10000) {
			// player 2 hit the wall
			alert("Gameover, "+p1name+" wins because " +p2name+" hit the wall!");
		} else {
			// player 1 won out right
			alert("Gameover, "+p1name+" wins with " + score +" points!");
		}
	} else if (y > x) {
		// player 2 won
		if (y == 10000) {
			// player 1 hit the wall
			alert("Gameover, "+p2name+" wins because " +p1name+" hit the wall!");
		} else {
			// player 2 won out right
			alert("Gameover, "+p2name+" wins with " + score2 +" points!");
		}
	} else {
		// TIE??
		alert("This is a TIE");
	}

	location.reload(true);
}

/**
 * The game loop function, used for game updates and rendering
 */
function loop() {
	update();
	draw();
	// When ready to redraw the canvas call the loop function
	// first. Runs about 60 frames a second
	window.requestAnimationFrame(loop, canvas);
}

/**
 * Updates the game logic
 */
function update() {
	frames++;

	// changing direction of the snake depending on which keys
	// that are pressed

	if (keystate[32]){
		return init();
	}

	if (keystate[KEY_LEFT] && snake.direction !== RIGHT) {
		snake.direction = LEFT;
	}
	if (keystate[KEY_UP] && snake.direction !== DOWN) {
		snake.direction = UP;
	}
	if (keystate[KEY_RIGHT] && snake.direction !== LEFT) {
		snake.direction = RIGHT;
	}
	if (keystate[KEY_DOWN] && snake.direction !== UP) {
		snake.direction = DOWN;
	}

	if (keystate[KEY_LEFT2] && snake2.direction !== RIGHT) {
		snake2.direction = LEFT;
	}
	if (keystate[KEY_UP2] && snake2.direction !== DOWN) {
		snake2.direction = UP;
	}
	if (keystate[KEY_RIGHT2] && snake2.direction !== LEFT) {
		snake2.direction = RIGHT;
	}
	if (keystate[KEY_DOWN2] && snake2.direction !== UP) {
		snake2.direction = DOWN;
	}

	// each five frames update the game state.
	if (frames%5 === 0) {
		// pop the last element from the snake queue i.e. the
		// head
		var nx = snake.last.x;
		var ny = snake.last.y;

		var nx2 = snake2.last.x;
		var ny2 = snake2.last.y;

		grid.set(SNAKE, nx, ny);
		grid.set(SNAKE2, nx2, ny2);

		// updates the position depending on the snake direction
		switch (snake.direction) {
			case LEFT:
				nx--;
				break;
			case UP:
				ny--;
				break;
			case RIGHT:
				nx++;
				break;
			case DOWN:
				ny++;
				break;
		}

		switch (snake2.direction) {
			case LEFT:
				nx2--;
				break;
			case UP:
				ny2--;
				break;
			case RIGHT:
				nx2++;
				break;
			case DOWN:
				ny2++;
				break;
		}

		// checks all gameover conditions || grid.get(nx, ny) === SNAKE
		if (0 > nx || nx > grid.width-1  ||
			0 > ny || ny > grid.height-1
		) {
			gameover(10000,0);
		}

		if (0 > nx2 || nx2 > grid.width-1  ||
			0 > ny2 || ny2 > grid.height-1
		) {
			gameover(0,10000);
		}
		// add a snake id at the new position and append it to
		// the snake queue

		if (grid.get(nx, ny) === EMPTY) {
			score++;
		} else if (grid.get(nx, ny) === SNAKE2) {
			flip++;
			score++;
			score2--;
		}
		else {

		}

		if (grid.get(nx2, ny2) === EMPTY) {
			score2++;
		}else if (grid.get(nx2, ny2) === SNAKE) {
			flip++;
			score2++;
			score--;
		} else {

		}

		if ((score + score2) > 800) {
			gameover(score,score2);
		}

		if (flip>200){
			gameover(score,score2);
		}

		grid.set(SNAKEH, nx, ny);
		grid.set(SNAKEH2, nx2, ny2);
		snake2.insert(nx2, ny2);
		snake.insert(nx, ny);
	}
}

/**
 * Render the grid to the canvas.
 */
function draw() {
	// calculate tile-width and -height
	var tw = canvas.width/grid.width;
	var th = canvas.height/grid.height;
	// iterate through the grid and draw all cells
	for (var x=0; x < grid.width; x++) {
		for (var y=0; y < grid.height; y++) {
			// sets the fillstyle depending on the id of
			// each cell
			switch (grid.get(x, y)) {
				case EMPTY:
					ctx.fillStyle = "#fff";
					break;
				case SNAKE:
					ctx.fillStyle = "#0ff";
					break;
				case SNAKE2:
					ctx.fillStyle = "#00f";
					break;
				case SNAKEH:
					ctx.fillStyle = "#0aa";
					break;
				default:
					ctx.fillStyle = "#a0a";
			}
			ctx.fillRect(x*tw, y*th, tw, th);
		}
	}
	// changes the fillstyle once more and draws the score
	// message to the canvas

	ctx.fillStyle = "#00f";
	ctx.fillText("PLAYER 2: "+p2name+" SCORE: " + score2, 10, canvas.height-10);
	ctx.fillStyle = "#0ff";
	ctx.fillText("PLAYER 1: "+p1name+" SCORE: " + score, 10, canvas.height-30);
	ctx.fillStyle = "#000";
	ctx.fillText("Flips: "+flip+"/200", 10, canvas.height-50);
}

// start and run the game
//main();

<commit_msg>bug fix for double exit?<commit_after>var

/**
 * Constats
 */
COLS = 64,
ROWS = 32,

EMPTY = 0,
SNAKE = 1,
SNAKEH = 3,
SNAKE2 = 4,
SNAKEH2 = 5,
FRUIT = 2,

LEFT  = 0,
UP    = 1,
RIGHT = 2,
DOWN  = 3,

KEY_LEFT  = 37,
KEY_UP    = 38,
KEY_RIGHT = 39,
KEY_DOWN  = 40,

KEY_LEFT2 = 65,
KEY_UP2 = 87,
KEY_RIGHT2 = 68,
KEY_DOWN2 = 83,

/**
 * Game objects
 */
canvas,	  /* HTMLCanvas */
ctx,	  /* CanvasRenderingContext2d */
keystate, /* Object, used for keyboard inputs */
flip,
p1name,
p2name,
frames,   /* number, used for animation */
score2,
score;	  /* number, keep track of the player score */

/**
 * Grid datastructor, usefull in games where the game world is
 * confined in absolute sized chunks of data or information.
 *
 * @type {Object}
 */
grid = {

	width: null,  /* number, the number of columns */
	height: null, /* number, the number of rows */
	_grid: null,  /* Array<any>, data representation */

	/**
	 * Initiate and fill a c x r grid with the value of d
	 * @param  {any}    d default value to fill with
	 * @param  {number} c number of columns
	 * @param  {number} r number of rows
	 */
	init: function(d, c, r) {
		this.width = c;
		this.height = r;

		this._grid = [];
		for (var x=0; x < c; x++) {
			this._grid.push([]);
			for (var y=0; y < r; y++) {
				this._grid[x].push(d);
			}
		}
	},

	/**
	 * Set the value of the grid cell at (x, y)
	 *
	 * @param {any}    val what to set
	 * @param {number} x   the x-coordinate
	 * @param {number} y   the y-coordinate
	 */
	set: function(val, x, y) {
		this._grid[x][y] = val;
	},

	/**
	 * Get the value of the cell at (x, y)
	 *
	 * @param  {number} x the x-coordinate
	 * @param  {number} y the y-coordinate
	 * @return {any}   the value at the cell
	 */
	get: function(x, y) {
		return this._grid[x][y];
	}
}

/**
 * The snake, works as a queue (FIFO, first in first out) of data
 * with all the current positions in the grid with the snake id
 *
 * @type {Object}
 */
snake = {

	direction: null, /* number, the direction */
	last: null,		 /* Object, pointer to the last element in
						the queue */
	_queue: null,	 /* Array<number>, data representation*/

	init: function(d, x, y) {
		this.direction = d;

		this._queue = [];
		this.insert(x, y);
	},

	insert: function(x, y) {
		this._queue.unshift({x:x, y:y});
		this.last = this._queue[0];
	},

	remove: function() {
		return this._queue.pop();
	}
};

snake2 = {

	direction: null, /* number, the direction */
	last: null,		 /* Object, pointer to the last element in
						the queue */
	_queue: null,	 /* Array<number>, data representation*/

	init: function(d, x, y) {
		this.direction = d;

		this._queue = [];
		this.insert(x, y);
	},

	insert: function(x, y) {
		this._queue.unshift({x:x, y:y});
		this.last = this._queue[0];
	},

	remove: function() {
		return this._queue.pop();
	}
};

/**
 * Starts the game
 */
function main() {
	// create and initiate the canvas element
	canvas = document.createElement("canvas");
	canvas.width = COLS*20;
	canvas.height = ROWS*20;
	ctx = canvas.getContext("2d");
	// add the canvas element to the body of the document
	document.body.appendChild(canvas);

	// sets an base font for bigger score display
	ctx.font = "16px Helvetica";

	frames = 0;
	keystate = {};
	// keeps track of the keybourd input
	document.addEventListener("keydown", function(evt) {
		keystate[evt.keyCode] = true;
	});
	document.addEventListener("keyup", function(evt) {
		delete keystate[evt.keyCode];
	});

	// intatiate game objects and starts the game loop
	p1name = prompt("Player 1, please enter your name. \nYou will be light blue and you will start on the bottom" , "player 1");
	p2name = prompt("Player 2, please enter your name. \nYou will be dark blue and you will start on the right" , "player 2")
	init();
	loop();
}

/**
 * Resets and inits game objects
 */
function init() {
	score2  = 0
	score = 0;
	flip = 0;

	grid.init(EMPTY, COLS, ROWS);

	var sp = {x:Math.floor(COLS/2), y:ROWS-1};
	var sp2 = {x:COLS-1, y:Math.floor(ROWS/2)};
	snake.init(UP, sp.x, sp.y);
	snake2.init(LEFT, sp2.x, sp2.y);
	grid.set(SNAKE2, sp2.x, sp2.y);
	grid.set(SNAKE, sp.x, sp.y);

}

function gameover(x,y) {
	if (x > y){
		// player 1 won
		if (x == 10000) {
			// player 2 hit the wall
			alert("Gameover, "+p1name+" wins because " +p2name+" hit the wall!");
		} else {
			// player 1 won out right
			alert("Gameover, "+p1name+" wins with " + score +" points!");
		}
	} else if (y > x) {
		// player 2 won
		if (y == 10000) {
			// player 1 hit the wall
			alert("Gameover, "+p2name+" wins because " +p1name+" hit the wall!");
		} else {
			// player 2 won out right
			alert("Gameover, "+p2name+" wins with " + score2 +" points!");
		}
	} else {
		// TIE??
		alert("This is a TIE");
	}

	location.reload(true);
}

/**
 * The game loop function, used for game updates and rendering
 */
function loop() {
	update();
	draw();
	// When ready to redraw the canvas call the loop function
	// first. Runs about 60 frames a second
	window.requestAnimationFrame(loop, canvas);
}

/**
 * Updates the game logic
 */
function update() {
	frames++;

	// changing direction of the snake depending on which keys
	// that are pressed

	if (keystate[32]){
		return init();
	}

	if (keystate[KEY_LEFT] && snake.direction !== RIGHT) {
		snake.direction = LEFT;
	}
	if (keystate[KEY_UP] && snake.direction !== DOWN) {
		snake.direction = UP;
	}
	if (keystate[KEY_RIGHT] && snake.direction !== LEFT) {
		snake.direction = RIGHT;
	}
	if (keystate[KEY_DOWN] && snake.direction !== UP) {
		snake.direction = DOWN;
	}

	if (keystate[KEY_LEFT2] && snake2.direction !== RIGHT) {
		snake2.direction = LEFT;
	}
	if (keystate[KEY_UP2] && snake2.direction !== DOWN) {
		snake2.direction = UP;
	}
	if (keystate[KEY_RIGHT2] && snake2.direction !== LEFT) {
		snake2.direction = RIGHT;
	}
	if (keystate[KEY_DOWN2] && snake2.direction !== UP) {
		snake2.direction = DOWN;
	}

	// each five frames update the game state.
	if (frames%5 === 0) {
		// pop the last element from the snake queue i.e. the
		// head
		var nx = snake.last.x;
		var ny = snake.last.y;

		var nx2 = snake2.last.x;
		var ny2 = snake2.last.y;

		grid.set(SNAKE, nx, ny);
		grid.set(SNAKE2, nx2, ny2);

		// updates the position depending on the snake direction
		switch (snake.direction) {
			case LEFT:
				nx--;
				break;
			case UP:
				ny--;
				break;
			case RIGHT:
				nx++;
				break;
			case DOWN:
				ny++;
				break;
		}

		switch (snake2.direction) {
			case LEFT:
				nx2--;
				break;
			case UP:
				ny2--;
				break;
			case RIGHT:
				nx2++;
				break;
			case DOWN:
				ny2++;
				break;
		}

		// checks all gameover conditions || grid.get(nx, ny) === SNAKE
		if (0 > nx || nx > grid.width-1  ||
			0 > ny || ny > grid.height-1
		) {
			gameover(10000,0);
		}

		if (0 > nx2 || nx2 > grid.width-1  ||
			0 > ny2 || ny2 > grid.height-1
		) {
			gameover(0,10000);
		}
		// add a snake id at the new position and append it to
		// the snake queue

		if (grid.get(nx, ny) === EMPTY) {
			score++;
		} else if (grid.get(nx, ny) === SNAKE2) {
			flip++;
			score++;
			score2--;
		}
		else {

		}

		if (grid.get(nx2, ny2) === EMPTY) {
			score2++;
		}else if (grid.get(nx2, ny2) === SNAKE) {
			flip++;
			score2++;
			score--;
		} else {

		}

		if ((score + score2) > 800) {
			return gameover(score,score2);
		}

		else if (flip>200){
			return gameover(score,score2);
		}

		grid.set(SNAKEH, nx, ny);
		grid.set(SNAKEH2, nx2, ny2);
		snake2.insert(nx2, ny2);
		snake.insert(nx, ny);
	}
}

/**
 * Render the grid to the canvas.
 */
function draw() {
	// calculate tile-width and -height
	var tw = canvas.width/grid.width;
	var th = canvas.height/grid.height;
	// iterate through the grid and draw all cells
	for (var x=0; x < grid.width; x++) {
		for (var y=0; y < grid.height; y++) {
			// sets the fillstyle depending on the id of
			// each cell
			switch (grid.get(x, y)) {
				case EMPTY:
					ctx.fillStyle = "#fff";
					break;
				case SNAKE:
					ctx.fillStyle = "#0ff";
					break;
				case SNAKE2:
					ctx.fillStyle = "#00f";
					break;
				case SNAKEH:
					ctx.fillStyle = "#0aa";
					break;
				default:
					ctx.fillStyle = "#a0a";
			}
			ctx.fillRect(x*tw, y*th, tw, th);
		}
	}
	// changes the fillstyle once more and draws the score
	// message to the canvas

	ctx.fillStyle = "#00f";
	ctx.fillText("PLAYER 2: "+p2name+" SCORE: " + score2, 10, canvas.height-10);
	ctx.fillStyle = "#0ff";
	ctx.fillText("PLAYER 1: "+p1name+" SCORE: " + score, 10, canvas.height-30);
	ctx.fillStyle = "#000";
	ctx.fillText("Flips: "+flip+"/200", 10, canvas.height-50);
}

// start and run the game
//main();

<|endoftext|>


<commit_before>const config = {
  extends: ['standard', 'prettier', 'prettier/standard'],
  plugins: ['import', 'mocha'],
  rules: {
    'import/no-extraneous-dependencies': [
      'error',
      {
        devDependencies: [
          '**/test/**/*.js',
          '**/bootstrap-unexpected-markdown.js'
        ],
        optionalDependencies: false,
        peerDependencies: false
      }
    ],
    'mocha/no-exclusive-tests': 'error',
    'mocha/no-nested-tests': 'error',
    'mocha/no-identical-title': 'error'
  },
  parserOptions: {
    ecmaVersion: 9,
    ecmaFeatures: {
      globalReturn: true,
      jsx: true
    },
    sourceType: 'module'
  }
};

if (process.stdin.isTTY) {
  // Enable plugin-prettier when running in a terminal. Allows us to have
  // eslint verify prettier formatting, while not being bothered by it in our
  // editors.
  config.plugins.push('prettier');
  config.rules['prettier/prettier'] = 'error';
}

module.exports = config;
<commit_msg>Add mocha env to the eslint config<commit_after>const config = {
  extends: ['standard', 'prettier', 'prettier/standard'],
  plugins: ['import', 'mocha'],
  env: {
    mocha: true
  },
  rules: {
    'import/no-extraneous-dependencies': [
      'error',
      {
        devDependencies: [
          '**/test/**/*.js',
          '**/bootstrap-unexpected-markdown.js'
        ],
        optionalDependencies: false,
        peerDependencies: false
      }
    ],
    'mocha/no-exclusive-tests': 'error',
    'mocha/no-nested-tests': 'error',
    'mocha/no-identical-title': 'error'
  },
  parserOptions: {
    ecmaVersion: 9,
    ecmaFeatures: {
      globalReturn: true,
      jsx: true
    },
    sourceType: 'module'
  }
};

if (process.stdin.isTTY) {
  // Enable plugin-prettier when running in a terminal. Allows us to have
  // eslint verify prettier formatting, while not being bothered by it in our
  // editors.
  config.plugins.push('prettier');
  config.rules['prettier/prettier'] = 'error';
}

module.exports = config;
<|endoftext|>


<commit_before>module.exports = {
  'env': {
    'browser': true,
    'es6': true,
    'node': true
  },
  'extends': [
    'eslint:recommended',
    'plugin:react/recommended'
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'experimentalObjectRestSpread': true,
      'jsx': true
    },
    'sourceType': 'module'
  },
  'plugins': [
    'react'
  ],
  'rules': {
    'indent': [
      'error',
      2,
      {
        'SwitchCase': 1
      }
    ],
    'react/jsx-indent': [
      'error',
      2
    ],
    'react/jsx-indent-props': [
      'error',
      2
    ],
    'react/jsx-closing-bracket-location': [
      'error',
      'tag-aligned'
    ],
    'linebreak-style': [
      'error',
      'unix'
    ],
    'quotes': [
      'error',
      'single'
    ],
    'semi': [
      'error',
      'always'
    ],
    'object-curly-spacing': [
      'error',
      'always'
    ]
  }
};
<commit_msg>lint for react method order<commit_after>module.exports = {
  'env': {
    'browser': true,
    'es6': true,
    'node': true
  },
  'extends': [
    'eslint:recommended',
    'plugin:react/recommended'
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'experimentalObjectRestSpread': true,
      'jsx': true
    },
    'sourceType': 'module'
  },
  'plugins': [
    'react'
  ],
  'rules': {
    'indent': [
      'error',
      2,
      {
        'SwitchCase': 1
      }
    ],
    'react/jsx-indent': [
      'error',
      2
    ],
    'react/jsx-indent-props': [
      'error',
      2
    ],
    'react/jsx-closing-bracket-location': [
      'error',
      'tag-aligned'
    ],
    'react/sort-comp': [1],
    'linebreak-style': [
      'error',
      'unix'
    ],
    'quotes': [
      'error',
      'single'
    ],
    'semi': [
      'error',
      'always'
    ],
    'object-curly-spacing': [
      'error',
      'always'
    ]
  }
};
<|endoftext|>


<commit_before>module.exports = {
  root: true,
  parser: 'babel-eslint',
  parserOptions: {
    sourceType: 'module'
  },
  // required to lint *.vue files
  plugins: [
    'html'
  ],
  // add your custom rules here
  'rules': {
    // allow debugger during development
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
  }
}
<commit_msg>linit<commit_after>module.exports = {
	root: true,
	parser: 'babel-eslint',
	parserOptions: {
		sourceType: 'module'
	},
	// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
	extends: 'standard',
	// required to lint *.vue files
	plugins: [
		'html'
	],
	'env': {
		'es6': true,
		'browser': true
	},
	// add your custom rules here
	'rules': {
		'indent': ['error', 'tab'],
		// allow paren-less arrow functions
		'arrow-parens': 0,
		// allow async-await
		'generator-star-spacing': 0,
		// allow debugger during development
		'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
		// No semilocons
		'semi': ['error', 'never' ],
		// Single quotes
		'quotes': ['error', 'single']
	}
}
<|endoftext|>


<commit_before>/* @flow */

module.exports = {
    'extends': './node_modules/grumbler-scripts/config/.eslintrc-browser.js',

    'globals': {
        'Promise': false,
        '__PAYPAL_CHECKOUT__': true,
        '__paypal_checkout__': true,
        '__sdk__': true,
        '__LOCALE__': true,
        '__CLIENT_ID__': true,
        '__MERCHANT_ID__': true,
        '__INTENT__': true,
        '__COMMIT__': true,
        '__VAULT__': true,
        '__PORT__': true,
        '__STAGE_HOST__': true,
        '__HOST__': true,
        '__PATH__': true,
        '__COMPONENTS__': true
    },

    'rules': {
        'complexity': 'off',
        'max-nested-callbacks': [ 'error', 5 ],
        'react/prop-types': 'off',
        'react/style-prop-object': 'off',
        'react/display-name': 'off',
        'react/require-default-props': 'off',
        'react/forbid-component-props': 'off'
    }
};<commit_msg>Disable react/no-unused-prop-types<commit_after>/* @flow */

module.exports = {
    'extends': './node_modules/grumbler-scripts/config/.eslintrc-browser.js',

    'globals': {
        'Promise': false,
        '__PAYPAL_CHECKOUT__': true,
        '__paypal_checkout__': true,
        '__sdk__': true,
        '__LOCALE__': true,
        '__CLIENT_ID__': true,
        '__MERCHANT_ID__': true,
        '__INTENT__': true,
        '__COMMIT__': true,
        '__VAULT__': true,
        '__PORT__': true,
        '__STAGE_HOST__': true,
        '__HOST__': true,
        '__PATH__': true,
        '__COMPONENTS__': true
    },

    'rules': {
        'complexity': 'off',
        'max-nested-callbacks': [ 'error', 5 ],
        'react/prop-types': 'off',
        'react/style-prop-object': 'off',
        'react/display-name': 'off',
        'react/require-default-props': 'off',
        'react/forbid-component-props': 'off',
        'react/no-unused-prop-types': 'off'
    }
};<|endoftext|>


<commit_before>o2.require("/js/DOMUtil.js");
o2.require("/o2www/js/windowUtil.js");
o2.require("/js/ajax.js");

o2.popupDialog = {

  submitFunc          : null,
  currentOpenDialogId : null,

  init : function() {
    if (!document.getElementById("o2PopupDialog")) {
      var html;
      html  = '
';
      html += '
';
      html += '
';
      html += '
';
      html += '        <button type="button" class="close" data-dismiss="modal">×Close</button>';
      html += '

';
      html += '
';
      html += '

';
      html += '

';
      html += '
';
      html += '
';
      html += '
';
      $(document.body).append( $(html) );
    }
  },

  define : function(id, params) {
    if (!o2.popupDialog[id]) {
      o2.popupDialog[id] = {};
    }
    o2.popupDialog[id].buttons = [];
    o2.popupDialog[id].params = params;
  },

  addSubmitBtn : function(id, text, func) {
    func = func || function () {
      var form = o2.popupDialog.findForm( document.getElementById("o2PopupDialog") );
      if ( ( form && form.onsubmit && form.onsubmit.call(form) )  ||  (form && !form.onsubmit) ) {
        form.submit();
      }
      o2.popupDialog.hide();
    };
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : "btn-primary",
      "click" : func
    });
  },

  addCloseBtn : function(id, text) {
    o2.popupDialog[id].buttons.push({
      "text"       : text,
      "class"      : "btn-default",
      "isCloseBtn" : true
    });
  },

  addBtn : function(id, text, onClick, className) {
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : className,
      "click" : function () { eval(onClick) }
    });
  },

  display : function(id, extraParams) {
    o2.popupDialog.currentOpenDialogId = id;
    o2.popupDialog.clear();

    if (!o2.popupDialog[id]) {
      o2.popupDialog.define(id, {});
    }
    var submitText = o2.popupDialog[id].params.submitText || o2.popupDialog[id].params.submittext;
    if (submitText) {
      o2.popupDialog.addSubmitBtn(id, submitText);
    }
    var closeText = o2.popupDialog[id].params.closeText || o2.popupDialog[id].params.closetext;
    if (closeText) {
      o2.popupDialog.addCloseBtn(id, closeText);
    }

    var params = o2.popupDialog[id].params;
    for (var key in extraParams) {
      params[key] = extraParams[key];
    }
    var contentId   = params.contentId   || params.contentid;
    var contentUrl  = params.contentUrl  || params.contenturl;
    var contentHtml = params.contentHtml || params.contenthtml;
    $("#o2PopupDialog").unbind();
    if (params.onClose) {
      $("#o2PopupDialog").on("hide.bs.modal", function() { eval(params.onClose); });
    }

    o2.popupDialog.drawButtons(id);
    $("#o2PopupDialog .modal-body"  ).css( "height", params.height );
    $("#o2PopupDialog .modal-dialog").css( "width",  params.width  );
    $("#o2PopupDialog").modal("show");

    var popupDialog = document.getElementById("o2PopupDialog");
    $("#o2PopupDialog .modal-title").html(params.title);
    if (contentHtml) {
      $("#o2PopupDialog .modal-body").html(contentHtml);
    }
    else if (contentId) {
      $("#o2PopupDialog .modal-body").html( document.getElementById(contentId).innerHTML );
    }
    else if (contentUrl) {
      //popupDialog.parentNode.style.display = "none";
      o2.ajax.call({
        serverScript : contentUrl,
        target       : "o2PopupDialogBody",
        where        : "replace",
        onSuccess    : "var elm = document.getElementById('o2PopupDialog').parentNode; elm.id = '" + id + "'; elm.style.display = '';"
      });
    }
    if (window !== top.window) { // The Modal widget doesn't know where to place itself if it's not located in the top frame
      var topPosition = o2.getFrameTopToVisibleFrameTopOffset(window) - $(document).scrollTop();
      if (topPosition < 0) {
        topPosition = 0;
      }
      $("#o2PopupDialog").css("top", topPosition);
    }
  },

  hide : function() {
    $("#o2PopupDialog").modal("hide");
  },

  findForm : function(elm) {
    for (var i = 0; i < elm.childNodes.length; i++) {
      var child = elm.childNodes[i];
      if (child.nodeType == 3) {
        continue;
      }
      if (child.nodeName.toLowerCase() === "form") {
        return child;
      }
      var form = o2.popupDialog.findForm(child);
      if (form) {
        return form;
      }
    }
    return null;
  },

  copyHtmlToHiddenContainer : function() {
    var id = o2.popupDialog.currentOpenDialogId;
    if (!id) {
      return;
    }
  },

  drawButtons : function(id) {
    var buttons = o2.popupDialog[id].buttons;
    for (var i = 0; i < buttons.length; i++) {
      o2.popupDialog.drawButton( id, buttons[i] );
    }
    o2.popupDialog[id].buttons = [];
  },

  drawButton : function(id, button) {
    var buttonElm = $(
        '<button type="button" class="btn '
      + button.class
      + '"'
      + (button.isCloseBtn ? " data-dismiss='modal'" : "")
      + '>'
      + button.text
      + '</button>'
    );
    buttonElm.click(button.click);
    $("#o2PopupDialog .modal-footer").append(buttonElm);
  },

  clear : function() {
    $( "#o2PopupDialogLabel"          ).html("");
    $( "#o2PopupDialogBody"           ).html("");
    $( "#o2PopupDialog .modal-footer" ).html("");
  },
};
<commit_msg>Bug fix.<commit_after>o2.require("/js/DOMUtil.js");
o2.require("/js/windowUtil.js");
o2.require("/js/ajax.js");

o2.popupDialog = {

  submitFunc          : null,
  currentOpenDialogId : null,

  init : function() {
    if (!document.getElementById("o2PopupDialog")) {
      var html;
      html  = '
';
      html += '
';
      html += '
';
      html += '
';
      html += '        <button type="button" class="close" data-dismiss="modal">×Close</button>';
      html += '

';
      html += '
';
      html += '

';
      html += '

';
      html += '
';
      html += '
';
      html += '
';
      $(document.body).append( $(html) );
    }
  },

  define : function(id, params) {
    if (!o2.popupDialog[id]) {
      o2.popupDialog[id] = {};
    }
    o2.popupDialog[id].buttons = [];
    o2.popupDialog[id].params = params;
  },

  addSubmitBtn : function(id, text, func) {
    func = func || function () {
      var form = o2.popupDialog.findForm( document.getElementById("o2PopupDialog") );
      if ( ( form && form.onsubmit && form.onsubmit.call(form) )  ||  (form && !form.onsubmit) ) {
        form.submit();
      }
      o2.popupDialog.hide();
    };
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : "btn-primary",
      "click" : func
    });
  },

  addCloseBtn : function(id, text) {
    o2.popupDialog[id].buttons.push({
      "text"       : text,
      "class"      : "btn-default",
      "isCloseBtn" : true
    });
  },

  addBtn : function(id, text, onClick, className) {
    o2.popupDialog[id].buttons.push({
      "text"  : text,
      "class" : className,
      "click" : function () { eval(onClick) }
    });
  },

  display : function(id, extraParams) {
    o2.popupDialog.currentOpenDialogId = id;
    o2.popupDialog.clear();

    if (!o2.popupDialog[id]) {
      o2.popupDialog.define(id, {});
    }
    var submitText = o2.popupDialog[id].params.submitText || o2.popupDialog[id].params.submittext;
    if (submitText) {
      o2.popupDialog.addSubmitBtn(id, submitText);
    }
    var closeText = o2.popupDialog[id].params.closeText || o2.popupDialog[id].params.closetext;
    if (closeText) {
      o2.popupDialog.addCloseBtn(id, closeText);
    }

    var params = o2.popupDialog[id].params;
    for (var key in extraParams) {
      params[key] = extraParams[key];
    }
    var contentId   = params.contentId   || params.contentid;
    var contentUrl  = params.contentUrl  || params.contenturl;
    var contentHtml = params.contentHtml || params.contenthtml;
    $("#o2PopupDialog").unbind();
    if (params.onClose) {
      $("#o2PopupDialog").on("hide.bs.modal", function() { eval(params.onClose); });
    }

    o2.popupDialog.drawButtons(id);
    $("#o2PopupDialog .modal-body"  ).css( "height", params.height );
    $("#o2PopupDialog .modal-dialog").css( "width",  params.width  );
    $("#o2PopupDialog").modal("show");

    var popupDialog = document.getElementById("o2PopupDialog");
    $("#o2PopupDialog .modal-title").html(params.title);
    if (contentHtml) {
      $("#o2PopupDialog .modal-body").html(contentHtml);
    }
    else if (contentId) {
      $("#o2PopupDialog .modal-body").html( document.getElementById(contentId).innerHTML );
    }
    else if (contentUrl) {
      //popupDialog.parentNode.style.display = "none";
      o2.ajax.call({
        serverScript : contentUrl,
        target       : "o2PopupDialogBody",
        where        : "replace",
        onSuccess    : "var elm = document.getElementById('o2PopupDialog').parentNode; elm.id = '" + id + "'; elm.style.display = '';"
      });
    }
    if (window !== top.window) { // The Modal widget doesn't know where to place itself if it's not located in the top frame
      var topPosition = o2.getFrameTopToVisibleFrameTopOffset(window) - $(document).scrollTop();
      if (topPosition < 0) {
        topPosition = 0;
      }
      $("#o2PopupDialog").css("top", topPosition);
    }
  },

  hide : function() {
    $("#o2PopupDialog").modal("hide");
  },

  findForm : function(elm) {
    for (var i = 0; i < elm.childNodes.length; i++) {
      var child = elm.childNodes[i];
      if (child.nodeType == 3) {
        continue;
      }
      if (child.nodeName.toLowerCase() === "form") {
        return child;
      }
      var form = o2.popupDialog.findForm(child);
      if (form) {
        return form;
      }
    }
    return null;
  },

  copyHtmlToHiddenContainer : function() {
    var id = o2.popupDialog.currentOpenDialogId;
    if (!id) {
      return;
    }
  },

  drawButtons : function(id) {
    var buttons = o2.popupDialog[id].buttons;
    for (var i = 0; i < buttons.length; i++) {
      o2.popupDialog.drawButton( id, buttons[i] );
    }
    o2.popupDialog[id].buttons = [];
  },

  drawButton : function(id, button) {
    var buttonElm = $(
        '<button type="button" class="btn '
      + button.class
      + '"'
      + (button.isCloseBtn ? " data-dismiss='modal'" : "")
      + '>'
      + button.text
      + '</button>'
    );
    buttonElm.click(button.click);
    $("#o2PopupDialog .modal-footer").append(buttonElm);
  },

  clear : function() {
    $( "#o2PopupDialogLabel"          ).html("");
    $( "#o2PopupDialogBody"           ).html("");
    $( "#o2PopupDialog .modal-footer" ).html("");
  },
};
<|endoftext|>


<commit_before>(function(ns) {

    var namespaces = [this];

    var attachBehavior = function($element, behavior) {
        var fn = namespaces;

        behavior.replace(/([^.]+)/g, function(object) {
            if(fn === namespaces) {
                for(var nextFn, index = 0; index < fn.length; ++index) {
                    nextFn = fn[index][object];
                    if(nextFn) {
                        fn = nextFn;
                        break;
                    }
                }
            } else if(typeof fn === 'object') {
                fn = fn[object];
            }
        });

        if(typeof fn === 'function') {
            return fn($element);
        } else {
            if (window.console && console.warn) {
                console.warn("elementalJS: Unable to find behavior:", behavior);
            }
        }
    };

    ns.load = function(container) {
        $(container).find("*").andSelf().filter("[data-behavior]").each(function(index, element) {
            var $element = $(element);
            var behaviors = $element.data('behavior');
            behaviors.replace(/([^ ]+)/g, function(behavior) {
                attachBehavior($element, behavior);
            });
        });
    };

    ns.addNamespace = function(namespace) {
        namespaces.push(namespace);
    };

})(window.Elemental = {});
<commit_msg>Performant load query<commit_after>(function(ns) {

    var namespaces = [this];

    var attachBehavior = function($element, behavior) {
        var fn = namespaces;

        behavior.replace(/([^.]+)/g, function(object) {
            if(fn === namespaces) {
                for(var nextFn, index = 0; index < fn.length; ++index) {
                    nextFn = fn[index][object];
                    if(nextFn) {
                        fn = nextFn;
                        break;
                    }
                }
            } else if(typeof fn === 'object') {
                fn = fn[object];
            }
        });

        if(typeof fn === 'function') {
            return fn($element);
        } else {
            if (window.console && console.warn) {
                console.warn("elementalJS: Unable to find behavior:", behavior);
            }
        }
    };

    ns.load = function(container) {
        var $selector;
        if (container === document) {
            $selector = $('[data-behavior]');
        }
        else {
            $selector = $(container).find("*").andSelf().filter("[data-behavior]");
        }

        $selector.each(function(index, element) {
            var $element = $(element);
            var behaviors = $element.data('behavior');
            behaviors.replace(/([^ ]+)/g, function(behavior) {
                attachBehavior($element, behavior);
            });
        });
    };

    ns.addNamespace = function(namespace) {
        namespaces.push(namespace);
    };

})(window.Elemental = {});
<|endoftext|>


<commit_before><commit_msg>Remove blank templates.js<commit_after><|endoftext|>


<commit_before>/**
 * ownCloud
 *
 * @author Bartek Przybylski
 * @copyright 2012 Bartek Przybylski bartek@alefzero.eu
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * this class to ease the usage of jquery dialogs
 */
var OCdialogs = {
	/**
	* displays alert dialog
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press OK
	*/
	alert:function(text, title, callback, modal) {
		var content = '
'+text+'
';
		OCdialogs.message(content, title, OCdialogs.ALERT_DIALOG, OCdialogs.OK_BUTTON, callback, modal);
	},
	/**
	* displays info dialog
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press OK
	*/
	info:function(text, title, callback, modal) {
		var content = '
'+text+'
';
		OCdialogs.message(content, title, OCdialogs.ALERT_DIALOG, OCdialogs.OK_BUTTON, callback, modal);
	},
	/**
	* displays confirmation dialog
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press YES or NO (true or false would be passed to callback respectively)
	*/
	confirm:function(text, title, callback, modal) {
		var content = '
'+text+'
';
		OCdialogs.message(content, title, OCdialogs.ALERT_DIALOG, OCdialogs.YES_NO_BUTTONS, callback, modal);
	},
	/**
	* prompt for user input
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press OK (input text will be passed to callback)
	*/
	prompt:function(text, title, default_value, callback, modal) {
		var content = '
'+text+':
<input type="text" id="oc-dialog-prompt-input" value="'+default_value+'" style="width:90%">
';
		OCdialogs.message(content, title, OCdialogs.PROMPT_DIALOG, OCdialogs.OK_CANCEL_BUTTONS, callback, modal);
	},
	/**
	* prompt user for input with custom form
	* fields should be passed in following format: [{text:'prompt text', name:'return name', type:'input type', value: 'dafault value'},...]
	* @param fields to display
	* @param title dialog title
	* @param callback which will be triggered when user press OK (user answers will be passed to callback in following format: [{name:'return name', value: 'user value'},...])
	*/
	form:function(fields, title, callback, modal) {
		var content = '
';
		for (var a in fields) {
			content += '
'+fields[a].text+'	';
			var type=fields[a].type;
			if (type == 'text' || type == 'checkbox' || type == 'password') {
				content += '<input type="'+type+'" name="'+fields[a].name+'"';
				if (type == 'checkbox') {
					if (fields[a].value != undefined && fields[a].value == true) {
						content += ' checked="checked">';
					} else {
						content += '>';
					}
				} else if (type == 'text' || type == 'password' && fields[a].value) {
					content += ' value="'+fields[a].value+'">';
				}
			} else if (type == 'select') {
				content += '<select name="'+fields[a].name+'"';
				if (fields[a].value != undefined) {
					content += ' value="'+fields[a].value+'"';
				}
				content += '>';
				for (var o in fields[a].options) {
					content += '<option value="'+fields[a].options[o].value+'">'+fields[a].options[o].text+'</option>';
				}
				content += '</select>';
			}
			content += '
';
		}
		content += '
';
		OCdialogs.message(content, title, OCdialogs.FORM_DIALOG, OCdialogs.OK_CANCEL_BUTTONS, callback, modal);
	},
	filepicker:function(title, callback, multiselect, mimetype_filter, modal) {
		var c_name = 'oc-dialog-'+OCdialogs.dialogs_counter+'-content';
		var c_id = '#'+c_name;
		var d = '
<select id="dirtree"><option value="0">'+OC.currentUser+'</option></select>

';
		if (!modal) modal = false; // Huh..
		if (!multiselect) multiselect = false;
		$('body').append(d);
		$(c_id + ' #dirtree').focus(function() {
			var t = $(this);
			t.data('oldval',  t.val())
		}).change({dcid: c_id}, OC.dialogs.handleTreeListSelect);
		$(c_id).ready(function(){
			$.getJSON(OC.filePath('files', 'ajax', 'rawlist.php'), {mimetype: mimetype_filter} ,function(r) {
				OC.dialogs.fillFilePicker(r, c_id, callback)
			});
		}).data('multiselect', multiselect).data('mimetype',mimetype_filter);
		// build buttons
		var b = [{
			text: t('core', 'Choose'),
			click: function(){
				if (callback != undefined) {
					var p;
					if ($(c_id).data('multiselect') == true) {
						p = [];
						$(c_id+' .filepicker_element_selected #filename').each(function(i, elem) {
							p.push(($(c_id).data('path')?$(c_id).data('path'):'')+'/'+$(elem).text());
						});
					} else {
						var p = $(c_id).data('path');
						if (p == undefined) p = '';
						p = p+'/'+$(c_id+' .filepicker_element_selected #filename').text()
					}
					callback(p);
					$(c_id).dialog('close');
				}
			}
		},
		{
			text: t('core', 'Cancel'),
			click: function(){$(c_id).dialog('close'); }}
		];
		$(c_id).dialog({width: ((4*$('body').width())/9), height: 400, modal: modal, buttons: b});
		OCdialogs.dialogs_counter++;
	},
	// guts, dont use, dont touch
	message:function(content, title, dialog_type, buttons, callback, modal) {
		var c_name = 'oc-dialog-'+OCdialogs.dialogs_counter+'-content';
		var c_id = '#'+c_name;
		var d = '
'+content+'
';
		if (modal == undefined) modal = false;
		$('body').append(d);
		var b = [];
		switch (buttons) {
			case OCdialogs.YES_NO_BUTTONS:
				b[1] = {text: t('core', 'No'), click: function(){ if (callback != undefined) callback(false); $(c_id).dialog('close'); }};
				b[0] = {text: t('core', 'Yes'), click: function(){ if (callback != undefined) callback(true); $(c_id).dialog('close');}};
			break;
			case OCdialogs.OK_CANCEL_BUTTONS:
				b[1] = {text: t('core', 'Cancel'), click: function(){$(c_id).dialog('close'); }};
			case OCdialogs.OK_BUTTON: // fallthrough
				var f;
				switch(dialog_type) {
					case OCdialogs.ALERT_DIALOG:
						f = function(){$(c_id).dialog('close'); if(callback) callback();};
					break;
					case OCdialogs.PROMPT_DIALOG:
						f = function(){OCdialogs.prompt_ok_handler(callback, c_id)};
					break;
					case OCdialogs.FORM_DIALOG:
						f = function(){OCdialogs.form_ok_handler(callback, c_id)};
					break;
				}
				b[0] = {text: t('core', 'Ok'), click: f};
			break;
		}
		var possible_height = ($('tr', d).size()+1)*30;
		$(c_id).dialog({width: 4*$(document).width()/9, height: possible_height + 120, modal: modal, buttons: b});
		OCdialogs.dialogs_counter++;
	},
	// dialogs buttons types
	YES_NO_BUTTONS: 70,
	OK_BUTTONS: 71,
	OK_CANCEL_BUTTONS: 72,
	// dialogs types
	ALERT_DIALOG: 80,
	INFO_DIALOG: 81,
	PROMPT_DIALOG: 82,
	FORM_DIALOG: 83,
	dialogs_counter: 0,
	determineValue: function(element) {
		switch ($(element).attr('type')) {
			case 'checkbox': return element.checked;
		}
		return $(element).val();
	},
	prompt_ok_handler: function(callback, c_id) { $(c_id).dialog('close'); if (callback != undefined) callback($(c_id + " input#oc-dialog-prompt-input").val()); },
	form_ok_handler: function(callback, c_id) {
		if (callback != undefined) {
			var r = [];
			var c = 0;
			$(c_id + ' input, '+c_id+' select').each(function(i, elem) {
				r[c] = {name: $(elem).attr('name'), value: OCdialogs.determineValue(elem)};
				c++;
			});
			$(c_id).dialog('close');
			callback(r);
		} else {
			$(c_id).dialog('close');
		}
	},
	fillFilePicker:function(r, dialog_content_id) {
		var entry_template = '
*NAME*
*LASTMODDATE*

';
		var names = '';
		for (var a in r.data) {
			names += entry_template.replace('*LASTMODDATE*', OC.mtime2date(r.data[a].mtime)).replace('*NAME*', r.data[a].name).replace('*MIMETYPEICON*', r.data[a].mimetype_icon).replace('*ENTRYNAME*', r.data[a].name).replace('*ENTRYTYPE*', r.data[a].type);
		}
		$(dialog_content_id + ' #filelist').html(names);
		$(dialog_content_id + ' .filepicker_loader').css('visibility', 'hidden');
	},
	handleTreeListSelect:function(event) {
		var newval = parseInt($(this).val());
		var oldval = parseInt($(this).data('oldval'));
		while (newval != oldval && oldval > 0) {
			$('option:last', this).remove();
			$('option:last', this).attr('selected','selected');
			oldval--;
		}
		var skip_first = true;
		var path = '';
		$(this).children().each(function(i, element) {
			if (skip_first) {
				skip_first = false;
				return;
			}
			path += '/'+$(element).text();
		});
		$(event.data.dcid).data('path', path);
		$(event.data.dcid + ' .filepicker_loader').css('visibility', 'visible');
		$.getJSON(OC.filePath('files', 'ajax', 'rawlist.php'), {dir: path, mimetype: $(event.data.dcid).data('mimetype')}, function(r){OC.dialogs.fillFilePicker(r, event.data.dcid)});
	},
	// this function is in early development state, please dont use it unlsess you know what you are doing
	handlePickerClick:function(element, name, dcid) {
		var p = $(dcid).data('path');
		if (p == undefined) p = '';
		p = p+'/'+name;
		if ($(element).attr('data') == 'file'){
			if ($(dcid).data('multiselect') != true) {
				$(dcid+' .filepicker_element_selected').removeClass('filepicker_element_selected');
			}
			$(element).toggleClass('filepicker_element_selected');
			return;
		}
		$(dcid).data('path', p);
		$(dcid + ' #dirtree option:last').removeAttr('selected');
		var newval = parseInt($(dcid + ' #dirtree option:last').val())+1;
		$(dcid + ' #dirtree').append('<option selected="selected" value="'+newval+'">'+name+'</option>');
		$(dcid + ' .filepicker_loader').css('visibility', 'visible');
		$.getJSON(OC.filePath('files', 'ajax', 'rawlist.php'), {dir: p, mimetype: $(dcid).data('mimetype')}, function(r){OC.dialogs.fillFilePicker(r, dcid)});
	}
};
<commit_msg>Fix for problems using for() function instead of $.each for arrays with IE8<commit_after>/**
 * ownCloud
 *
 * @author Bartek Przybylski
 * @copyright 2012 Bartek Przybylski bartek@alefzero.eu
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/**
 * this class to ease the usage of jquery dialogs
 */
var OCdialogs = {
	/**
	* displays alert dialog
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press OK
	*/
	alert:function(text, title, callback, modal) {
		var content = '
'+text+'
';
		OCdialogs.message(content, title, OCdialogs.ALERT_DIALOG, OCdialogs.OK_BUTTON, callback, modal);
	},
	/**
	* displays info dialog
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press OK
	*/
	info:function(text, title, callback, modal) {
		var content = '
'+text+'
';
		OCdialogs.message(content, title, OCdialogs.ALERT_DIALOG, OCdialogs.OK_BUTTON, callback, modal);
	},
	/**
	* displays confirmation dialog
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press YES or NO (true or false would be passed to callback respectively)
	*/
	confirm:function(text, title, callback, modal) {
		var content = '
'+text+'
';
		OCdialogs.message(content, title, OCdialogs.ALERT_DIALOG, OCdialogs.YES_NO_BUTTONS, callback, modal);
	},
	/**
	* prompt for user input
	* @param text content of dialog
	* @param title dialog title
	* @param callback which will be triggered when user press OK (input text will be passed to callback)
	*/
	prompt:function(text, title, default_value, callback, modal) {
		var content = '
'+text+':
<input type="text" id="oc-dialog-prompt-input" value="'+default_value+'" style="width:90%">
';
		OCdialogs.message(content, title, OCdialogs.PROMPT_DIALOG, OCdialogs.OK_CANCEL_BUTTONS, callback, modal);
	},
	/**
	* prompt user for input with custom form
	* fields should be passed in following format: [{text:'prompt text', name:'return name', type:'input type', value: 'dafault value'},...]
	* @param fields to display
	* @param title dialog title
	* @param callback which will be triggered when user press OK (user answers will be passed to callback in following format: [{name:'return name', value: 'user value'},...])
	*/
	form:function(fields, title, callback, modal) {
		var content = '
';
		$.each(fields, function(index, val){
			content += '
'+val.text+'	';
			var type=fields[a].type;

			if (type == 'text' || type == 'checkbox' || type == 'password') {
				content += '<input type="'+type+'" name="'+val.name+'"';
				if (type == 'checkbox') {
					if (val.value != undefined && val.value == true) {
						content += ' checked="checked">';
					} else {
						content += '>';
					}
				} else if (type == 'text' || type == 'password' && val.value) {
					content += ' value="'+val.value+'">';
				}
			} else if (type == 'select') {
				content += '<select name="'+val.name+'"';
				if (fields[a].value != undefined) {
					content += ' value="'+val.value+'"';
				}
				content += '>';
				$.each(val.options, function(index, valo){
				//for (var o in val.options) {
					content += '<option value="'+val.valo.value+'">'+val.valo.text+'</option>';
				});
				content += '</select>';
			}
			content += '
';

		});
		content += '
';
		OCdialogs.message(content, title, OCdialogs.FORM_DIALOG, OCdialogs.OK_CANCEL_BUTTONS, callback, modal);
	},
	filepicker:function(title, callback, multiselect, mimetype_filter, modal) {
		var c_name = 'oc-dialog-'+OCdialogs.dialogs_counter+'-content';
		var c_id = '#'+c_name;
		var d = '
<select id="dirtree"><option value="0">'+OC.currentUser+'</option></select>

';
		if (!modal) modal = false; // Huh..
		if (!multiselect) multiselect = false;
		$('body').append(d);
		$(c_id + ' #dirtree').focus(function() {
			var t = $(this);
			t.data('oldval',  t.val())
		}).change({dcid: c_id}, OC.dialogs.handleTreeListSelect);
		$(c_id).ready(function(){
			$.getJSON(OC.filePath('files', 'ajax', 'rawlist.php'), {mimetype: mimetype_filter} ,function(r) {
				OC.dialogs.fillFilePicker(r, c_id, callback)
			});
		}).data('multiselect', multiselect).data('mimetype',mimetype_filter);
		// build buttons
		var b = [{
			text: t('core', 'Choose'),
			click: function(){
				if (callback != undefined) {
					var p;
					if ($(c_id).data('multiselect') == true) {
						p = [];
						$(c_id+' .filepicker_element_selected #filename').each(function(i, elem) {
							p.push(($(c_id).data('path')?$(c_id).data('path'):'')+'/'+$(elem).text());
						});
					} else {
						var p = $(c_id).data('path');
						if (p == undefined) p = '';
						p = p+'/'+$(c_id+' .filepicker_element_selected #filename').text()
					}
					callback(p);
					$(c_id).dialog('close');
				}
			}
		},
		{
			text: t('core', 'Cancel'),
			click: function(){$(c_id).dialog('close'); }}
		];
		$(c_id).dialog({width: ((4*$('body').width())/9), height: 400, modal: modal, buttons: b});
		OCdialogs.dialogs_counter++;
	},
	// guts, dont use, dont touch
	message:function(content, title, dialog_type, buttons, callback, modal) {
		var c_name = 'oc-dialog-'+OCdialogs.dialogs_counter+'-content';
		var c_id = '#'+c_name;
		var d = '
'+content+'
';
		if (modal == undefined) modal = false;
		$('body').append(d);
		var b = [];
		switch (buttons) {
			case OCdialogs.YES_NO_BUTTONS:
				b[1] = {text: t('core', 'No'), click: function(){ if (callback != undefined) callback(false); $(c_id).dialog('close'); }};
				b[0] = {text: t('core', 'Yes'), click: function(){ if (callback != undefined) callback(true); $(c_id).dialog('close');}};
			break;
			case OCdialogs.OK_CANCEL_BUTTONS:
				b[1] = {text: t('core', 'Cancel'), click: function(){$(c_id).dialog('close'); }};
			case OCdialogs.OK_BUTTON: // fallthrough
				var f;
				switch(dialog_type) {
					case OCdialogs.ALERT_DIALOG:
						f = function(){$(c_id).dialog('close'); if(callback) callback();};
					break;
					case OCdialogs.PROMPT_DIALOG:
						f = function(){OCdialogs.prompt_ok_handler(callback, c_id)};
					break;
					case OCdialogs.FORM_DIALOG:
						f = function(){OCdialogs.form_ok_handler(callback, c_id)};
					break;
				}
				b[0] = {text: t('core', 'Ok'), click: f};
			break;
		}
		var possible_height = ($('tr', d).size()+1)*30;
		$(c_id).dialog({width: 4*$(document).width()/9, height: possible_height + 120, modal: modal, buttons: b});
		OCdialogs.dialogs_counter++;
	},
	// dialogs buttons types
	YES_NO_BUTTONS: 70,
	OK_BUTTONS: 71,
	OK_CANCEL_BUTTONS: 72,
	// dialogs types
	ALERT_DIALOG: 80,
	INFO_DIALOG: 81,
	PROMPT_DIALOG: 82,
	FORM_DIALOG: 83,
	dialogs_counter: 0,
	determineValue: function(element) {
		switch ($(element).attr('type')) {
			case 'checkbox': return element.checked;
		}
		return $(element).val();
	},
	prompt_ok_handler: function(callback, c_id) { $(c_id).dialog('close'); if (callback != undefined) callback($(c_id + " input#oc-dialog-prompt-input").val()); },
	form_ok_handler: function(callback, c_id) {
		if (callback != undefined) {
			var r = [];
			var c = 0;
			$(c_id + ' input, '+c_id+' select').each(function(i, elem) {
				r[c] = {name: $(elem).attr('name'), value: OCdialogs.determineValue(elem)};
				c++;
			});
			$(c_id).dialog('close');
			callback(r);
		} else {
			$(c_id).dialog('close');
		}
	},
	fillFilePicker:function(r, dialog_content_id) {
		var entry_template = '
*NAME*
*LASTMODDATE*

';
		var names = '';
		$.each(r.data, function(index, a) {
			names += entry_template.replace('*LASTMODDATE*', OC.mtime2date(a.mtime)).replace('*NAME*', a.name).replace('*MIMETYPEICON*', a.mimetype_icon).replace('*ENTRYNAME*', a.name).replace('*ENTRYTYPE*', a.type);
		});

		$(dialog_content_id + ' #filelist').html(names);
		$(dialog_content_id + ' .filepicker_loader').css('visibility', 'hidden');
	},
	handleTreeListSelect:function(event) {
		var newval = parseInt($(this).val());
		var oldval = parseInt($(this).data('oldval'));
		while (newval != oldval && oldval > 0) {
			$('option:last', this).remove();
			$('option:last', this).attr('selected','selected');
			oldval--;
		}
		var skip_first = true;
		var path = '';
		$(this).children().each(function(i, element) {
			if (skip_first) {
				skip_first = false;
				return;
			}
			path += '/'+$(element).text();
		});
		$(event.data.dcid).data('path', path);
		$(event.data.dcid + ' .filepicker_loader').css('visibility', 'visible');
		$.getJSON(OC.filePath('files', 'ajax', 'rawlist.php'), {dir: path, mimetype: $(event.data.dcid).data('mimetype')}, function(r){OC.dialogs.fillFilePicker(r, event.data.dcid)});
	},
	// this function is in early development state, please dont use it unlsess you know what you are doing
	handlePickerClick:function(element, name, dcid) {
		var p = $(dcid).data('path');
		if (p == undefined) p = '';
		p = p+'/'+name;
		if ($(element).attr('data') == 'file'){
			if ($(dcid).data('multiselect') != true) {
				$(dcid+' .filepicker_element_selected').removeClass('filepicker_element_selected');
			}
			$(element).toggleClass('filepicker_element_selected');
			return;
		}
		$(dcid).data('path', p);
		$(dcid + ' #dirtree option:last').removeAttr('selected');
		var newval = parseInt($(dcid + ' #dirtree option:last').val())+1;
		$(dcid + ' #dirtree').append('<option selected="selected" value="'+newval+'">'+name+'</option>');
		$(dcid + ' .filepicker_loader').css('visibility', 'visible');
		$.getJSON(OC.filePath('files', 'ajax', 'rawlist.php'), {dir: p, mimetype: $(dcid).data('mimetype')}, function(r){OC.dialogs.fillFilePicker(r, dcid)});
	}
};
<|endoftext|>


<commit_before>/*
 * 2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to team@froggy-commerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade your module to newer
 * versions in the future.
 *
 *  @author         Froggy Commerce <team@froggy-commerce.com>
 *  @copyright      2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *  @version        1.0
 *  @license        http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

$(document).ready(function() {

    // Hide PDF invoice link on orders list when the order status contains "Sellermania"
    var row = 0;
    $('.order tr').each(function() {

        var column = 0;
        var flag_sellermania = 0;

        $(this).find('td').each(function() {
            if (column == 7 && $(this).text().trim().toLowerCase().indexOf("marketplace") >= 0)
                flag_sellermania = 1;
            else if (column == 9 && flag_sellermania == 1)
                $(this).html(' ');
            column++;
        });

        row++;
    });

	if (nb_sellermania_orders_in_error > 0)
		$('.toolbar-placeholder').after('
' + nb_sellermania_orders_in_error + ' ' + txt_sellermania_orders_in_error + '
');

});
<commit_msg>Make compliant PS 1.4 / 1.5<commit_after>/*
 * 2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to team@froggy-commerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade your module to newer
 * versions in the future.
 *
 *  @author         Froggy Commerce <team@froggy-commerce.com>
 *  @copyright      2010-2016 Sellermania / Froggy Commerce / 23Prod SARL
 *  @version        1.0
 *  @license        http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

$(document).ready(function() {

    // Hide PDF invoice link on orders list when the order status contains "Sellermania"
    var row = 0;
    $('.order tr').each(function() {

        var column = 0;
        var id_order = 0;
        var flag_sellermania = 0;

        $(this).find('td').each(function() {
            if (column == 1) {
                id_order = $(this).text();
            }
            if (column == 7 && $(this).text().trim().toLowerCase().indexOf("marketplace") >= 0) {
                flag_sellermania = 1;
            }
            else if (column == 9 && flag_sellermania == 1) {
                $(this).find('span a').each(function() {
                    if ($(this).attr('href').indexOf("generateInvoicePDF") >= 0) {
                        $(this).attr('href', sellermania_invoice_url + '&id_order=' + id_order);
                    } else {
                        $(this).remove();
                    }
                });
            }
            column++;
        });

        row++;
    });

	if (nb_sellermania_orders_in_error > 0)
		$('.toolbar-placeholder').after('
' + nb_sellermania_orders_in_error + ' ' + txt_sellermania_orders_in_error + '
');

});
<|endoftext|>