<commit_before>var func = require('./' + global.tests_dir +'/start_app/script.js');
var execPath = func.getExecPath();
var fs = require('fs-extra');
var os = require('os');
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;

var app =  new Array();
var child1, child2;
var mac_app_path = path.join('tmp-nw', 'node-webkit.app');
function make_execuable_file(folder_path, done) {
    func.copyExecFiles(function() {
	func.copySourceFiles(folder_path);
	func.zipSourceFiles(function() {
	    func.makeExecuableFile();
	    if (os.platform() == 'darwin') {
		var app_path = 'tmp-nw/node-webkit.app/Contents/Resources/app.nw';
		fs.mkdir(app_path, function(err) {
		    if(err && err.code !== 'EEXIST') throw err
		    fs.copy('tmp-nw/index.html', path.join(app_path, 'index.html'));
		    fs.copy('tmp-nw/package.html', path.join(app_path, 'package.html'));
		});
	    }
	    done();
	});
    });
}

function check_have(i, cmd, options, msg, last, done) {
    var result = false;
    app[i] = spawn(cmd, options);
    app[i].on('exit', function() {
	result = true;
    });

    if (last == 2) {
	setTimeout(function() {
	    if (result) {
		done();
	    } else {
		done(msg);
	    }
	    app[i].kill();
	    app[i - 1].kill();
	}, 3000);
    } else {
	setTimeout(function() {
	    if (result) {
		done(msg);
	    } else {
		done();
	    }
	    if (last == 1) {
		app[i].kill();
		app[i - 1].kill();
	    }
	}, 3000);
    }
}

describe('single-instance', function() {
    this.timeout(0);

    describe('single-instance false', function() {
	before(function(done) {
	    make_execuable_file('single_instance/mul', done);
	});

        after(function() {
	    fs.remove('tmp-nw', function (er) {
                    if (er) throw er;
            });
        });

	it('should have a instance', function(done) {
	    check_have(0, execPath, "", 'not have a instance', 0, done);
	});

	it('should have a second instance', function(done) {
	    check_have(1, execPath, "", 'not have a second instance', 1, done);
	});
    });

    describe('single-instance default', function() {

	before(function(done) {
	    setTimeout(function() {
		make_execuable_file('single_instance/single', done);
	    }, 3000);
	});

        after(function() {
	    fs.remove('tmp-nw', function (er) {
                    if (er) throw er;
            });
        });

	it('should have a instance', function(done) {
	    check_have(2, execPath, "", 'not have a instance', 0, done);
	});

	it('should not have a second instance', function(done) {
	    check_have(3, execPath, "", 'have a second instance', 2, done);
	});
    });

    if (os.platform() == 'darwin') {
        describe('single-instance false(open app)', function(){
                before(function(done) {
                        setTimeout(function() {
                                make_execuable_file('single_instance/open_mul', done);
                            }, 3000);
                });

                after(function() {
                        fs.remove('tmp-nw', function (er) {
                                if (er) throw er;
                            });
                });

                it('should have a instance (open app)', function(done) {
                        child1 = exec('open ' + mac_app_path);
                        setTimeout(function () {
                                var content = fs.readFileSync('tmp-nw/msg');
                                if (content + "" != "")
                                    done();
                                else
                                    done("not have a instance");
                            }, 6000);
                });

                it('should have a second instance (open app)', function(done) {
                        child2 = exec('open ' + mac_app_path);
                        var content = fs.readFileSync('tmp-nw/msg');
                        if (content + "" == "11")
                            done();
                        else
                            done("not have a instance");
                });

        });

        describe('single-instance default(open app)', function(){
                before(function(done) {
                        setTimeout(function() {
                                make_execuable_file('single_instance/open_single', done);
                            }, 3000);
                });

                after(function() {
                        fs.remove('tmp-nw', function (er) {
                                if (er) throw er;
                            });
                });

                it('should have a instance (open app)', function(done) {
                        child1 = exec('open ' + mac_app_path);
                        setTimeout(function () {
                                var content = fs.readFileSync('tmp-nw/msg_s');
                                if (content + "" != "")
                                    done();
                                else
                                    done("not have a instance");
                            }, 6000);
                 });

                it('should not have a second instance (open app)', function(done) {
                        child2 = exec('open ' + mac_app_path);
                        var content = fs.readFileSync('tmp-nw/msg_s');
                        if (content + "" == "11")
                            done("have a second instance");
                        else
                            done();

                });
	    });
	}
});
<commit_msg>[test] update test case for single instance with open method in Mac<commit_after>var func = require('./' + global.tests_dir +'/start_app/script.js');
var execPath = func.getExecPath();
var fs = require('fs-extra');
var os = require('os');
var spawn = require('child_process').spawn;
var exec = require('child_process').exec;

var app =  new Array();
var child1, child2;
var mac_app_path = path.join('tmp-nw', 'node-webkit.app');
function make_execuable_file(folder_path, done) {
    func.copyExecFiles(function() {
	func.copySourceFiles(folder_path);
	func.zipSourceFiles(function() {
	    func.makeExecuableFile();
	    if (os.platform() == 'darwin') {
		var app_path = 'tmp-nw/node-webkit.app/Contents/Resources/app.nw';
		fs.mkdir(app_path, function(err) {
		    if(err && err.code !== 'EEXIST') throw err
		    fs.copy('tmp-nw/index.html', path.join(app_path, 'index.html'));
		    fs.copy('tmp-nw/package.html', path.join(app_path, 'package.html'));
		});
	    }
	    done();
	});
    });
}

function check_have(i, cmd, options, msg, last, done) {
    var result = false;
    app[i] = spawn(cmd, options);
    app[i].on('exit', function() {
	result = true;
    });

    if (last == 2) {
	setTimeout(function() {
	    if (result) {
		done();
	    } else {
		done(msg);
	    }
	    app[i].kill();
	    app[i - 1].kill();
	}, 3000);
    } else {
	setTimeout(function() {
	    if (result) {
		done(msg);
	    } else {
		done();
	    }
	    if (last == 1) {
		app[i].kill();
		app[i - 1].kill();
	    }
	}, 3000);
    }
}

describe('single-instance', function() {
    this.timeout(0);

    describe('single-instance false', function() {
	before(function(done) {
	    make_execuable_file('single_instance/mul', done);
	});

        after(function() {
	    fs.remove('tmp-nw', function (er) {
                    if (er) throw er;
            });
        });

	it('should have a instance', function(done) {
	    check_have(0, execPath, "", 'not have a instance', 0, done);
	});

	it('should have a second instance', function(done) {
	    check_have(1, execPath, "", 'not have a second instance', 1, done);
	});
    });

    describe('single-instance default', function() {

	before(function(done) {
	    setTimeout(function() {
		make_execuable_file('single_instance/single', done);
	    }, 3000);
	});

        after(function() {
	    fs.remove('tmp-nw', function (er) {
                    if (er) throw er;
            });
        });

	it('should have a instance', function(done) {
	    check_have(2, execPath, "", 'not have a instance', 0, done);
	});

	it('should not have a second instance', function(done) {
	    check_have(3, execPath, "", 'have a second instance', 2, done);
	});
    });

    if (os.platform() == 'darwin') {
        describe('single-instance false(open app)', function(){
                before(function(done) {
                        setTimeout(function() {
                                make_execuable_file('single_instance/open_mul', done);
                            }, 3000);
                });

                after(function() {
                        fs.remove('tmp-nw', function (er) {
                                if (er) throw er;
                            });
                });

                it('should have a instance (open app)', function(done) {
                        child1 = exec('open ' + mac_app_path);
                        setTimeout(function () {
                                var content = fs.readFileSync('tmp-nw/msg');
                                if (content + "" != "")
                                    done();
                                else
                                    done("not have a instance");
                            }, 6000);
                });

                it('should not have a second instance (open app)', function(done) {
                        child2 = exec('open ' + mac_app_path);
                        var content = fs.readFileSync('tmp-nw/msg');
                        if (content + "" == "11")
                            done("have a second instance");
                        else
                            done();
                });

        });

        describe('single-instance default(open app)', function(){
                before(function(done) {
                        setTimeout(function() {
                                make_execuable_file('single_instance/open_single', done);
                            }, 3000);
                });

                after(function() {
                        fs.remove('tmp-nw', function (er) {
                                if (er) throw er;
                            });
                });

                it('should have a instance (open app)', function(done) {
                        child1 = exec('open ' + mac_app_path);
                        setTimeout(function () {
                                var content = fs.readFileSync('tmp-nw/msg_s');
                                if (content + "" != "")
                                    done();
                                else
                                    done("not have a instance");
                            }, 6000);
                 });

                it('should not have a second instance (open app)', function(done) {
                        child2 = exec('open ' + mac_app_path);
                        var content = fs.readFileSync('tmp-nw/msg_s');
                        if (content + "" == "11")
                            done("have a second instance");
                        else
                            done();

                });
	    });
	}
});
<|endoftext|>


<commit_before>function TTYPlayer () {
	var frame = $('#frame');
	var binary = null;
	var ttyrec = null;
	var index = 0;
	var buffer = [[]];
	var point = {
		x: 1, y: 1
	};
	var render_frame = function (string) {

		var regexp = new RegExp('\\x1b\\[([0-9;]*)([dmGHJX])');
		var span = {
			foreground: 'white-fg',
			background: 'black-bg',
			light: ''
		};

		var output_characters = function (index) {
			var substring = '';

			if (index == -1) {
				substring = string;
				string = '';
			}
			else {
				substring = string.slice(0, index);
				string = string.slice(index);
			}

			var pre = '';
			var post = '';

			for (var i in substring) {
				var character = substring[i];
				if (character == ' ') {
					character = ' ';
				}

				buffer[point.y - 1][point.x - 1] = pre + character + post;
				point.x++;
			}
		};

		var handle_esc = function() {
			var match = string.match(regexp);
			var value = match[1];
			var c = match[2];

			if (c == 'm') {
				if (value == '') {
					span.foreground = 'white-fg';
					span.background = 'black-bg';
					span.light = '';
				}
				else {
					var values = value.split(';');
					var l = values.length;
					for (var i = 0; i < l; i++) {
						var val = values[i];
						if (val == '0') {
							span.foreground = 'white-fg';
							span.background = 'black-bg';
							span.light = '';
						}
						else if (val == '1') {
							span.light = 'light-';
						}
						else if (val == '30') {
							span.foreground = 'black-fg';
						}
						else if (val == '33') {
							span.foreground = 'yellow-fg';
						}
						else if (val == '37') {
							span.foreground = 'white-fg';
						}
						else if (val == '39') {
							span.foreground = 'white-fg';
						}
						else if (val == '40') {
							span.background = 'black-bg';
						}
						else if (val == '42') {
							span.background = 'green-bg';
						}
						else if (val == '49') {
							span.background = 'black-bg';
						}
						else {
							console.error('Unhandled SGR parameter: ' + val);
						}
					}
				}
			}
			else if (c == 'H') {
				// Moves the point
				if (value == '') {
					point.x = 1;
					point.y = 1;
				}
				else {
					var values = value.split(';');

					if (values[0] != '') {
						var n = parseInt(values[0]);
						for (var i = 0; i + point.y < n; i++) {
							if (buffer[point.y + i] == undefined) {
								buffer[point.y + i] = [];
							}
						}
						point.y = n;
					}
					else {
						point.y = 1;
					}

					if (values.length == 2) {
						point.x = parseInt(values[1]);
					}
					else {
						point.x = 1;
					}
				}
			}
			else if (c == 'G') {
				// Moves the point horizontally.
				point.x = parseInt(value);
			}
			else if (c == 'J') {
				// Clear the buffer
				if (value == '') {
					// Same as 0 case,
					// clear from point to end of buffer.
					console.error('[J needs implementing');
				}
				else {
					var n = parseInt(value);
					if (n == 0) {
						// Same as empty case,
						// clear from point to end of buffer.
						console.error('[0J needs implementing');
					}
					else if (n == 1) {
						// Clear from point to beginning of buffer.
						console.error('[1J needs implementing');
					}
					else if (n == 2) {
						buffer = [[]];
						point.x = 1;
						point.y = 1;
					}
					else {
						console.error('Unhandled value for J: ' + value);
					}
				}
			}
			else {
				console.error('Unhandled escape sequence: ' + match[0]);
			}

			string = string.slice(match[0].length);
		};

		var print_buffer = function () {
			var m = buffer.length;
			for	(var i = 0; i < m; i++) {
				var row = buffer[i];
				var n = row.length;
				for (var j = 0; j < n; j++) {
					var character = row[j];
					if (character == undefined) {
						character = ' ';
					}
					frame.append(character);
				}
				frame.append('
');
			}
		};

		string = string.replace(/\x0f/g, '');

		while (string != '') {
			var index = string.search(regexp);

			if (index == -1 || index > 0) {
				output_characters(index);
			}
			else if (index == 0) {
				handle_esc();
			}
		}

		print_buffer();
	};

	return {
		get_ttyrec: function() {
			return ttyrec;
		},

		clear_frame: function() {
			buffer = [[]];
			point = { x:1, y: 1};
			render_frame('');
		},

		next_frame: function() {
			if (index < ttyrec.length) {
				var t = ttyrec[index];
				var s = binary.getStringAt(t.address, t.len);
				p.render_frame(s);
				index += 1;
			}
		},

		previous_frame: function() {
			if (index > 0) {
				var t = ttyrec[index];
				var s = binary.getStringAt(t.address, t.len);
				p.render_frame(s);
				index -= 1;
			}
		},

		parse_data: function (input) {
			binary = input.binaryResponse;
			ttyrec = [];

			var length = binary.getLength();
			var offset = 0;

			while (offset < length) {
				var sec = binary.getLongAt(offset + 0, false);
				var usec = binary.getLongAt(offset + 4, false);
				var len = binary.getLongAt(offset + 8, false);
				var address = offset + 12;

				ttyrec.push({
								sec: sec,
								usec: usec,
								len: len,
								address: address
							});

				offset += (12 + len);
			}
		},

		render_frame: render_frame
	};
}

var t = "\x1b[39;49m\x1b[37m\x1b[40m\x1b[H\x1b[2J\x1b[33m\x1b[40mWelcome, Shy.\x1b[0;1m\x0f\x1b[33m\x1b[40m Please select your species.\x1b[3;4H\x1b[0m\x0f\x1b[37m\x1b[40ma - Human\x1b[3;29Hi - Halfling\x1b[3;54Hq - Kenku\x1b[4;4Hb - High Elf\x1b[4;29Hj - Kobold\x1b[4;54Hr - Draconian\x1b[5;4Hc - Deep Elf\x1b[5;29Hk - Spriggan\x1b[5;54Hs - Demigod\x1b[6;4Hd - Sludge Elf\x1b[6;29Hl - Naga\x1b[6;54Ht - Demonspawn\x1b[7;4He - Mountain Dwarf\x1b[29Gm - Centaur\x1b[7;54Hu - Mummy\x1b[8;4H\x1b[37m\x1b[42mf - Deep Dwarf          \x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m \x1b[37m\x1b[40mn - Ogre\x1b[8;54Hv - Ghoul\x1b[9;4Hg - Hill Orc\x1b[9;29Ho - Troll\x1b[9;54Hw - Vampire\x1b[10;4Hh - Merfolk\x1b[10;29Hp - Minotaur\x1b[17;4H\x1b[0;1m\x0f\x1b[37m\x1b[40mThey live deep down and cannot regenerate, but they are resilient and have\x1b[0m\x0f\x1b[30m\x1b[40m  \x1b[18;4H\x1b[0;1m\x0f\x1b[37m\x1b[40mtools to heal.\x1b[20;4H\x1b[0m\x0f\x1b[33m\x1b[40m+ - Viable Species\x1b[29G* - Random species\x1b[21;4H# - Viable character\x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m     \x1b[33m\x1b[40m! - Random character\x1b[22;4H% - List aptitudes\x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m   \x1b[33m\x1b[40mSpace - Pick background first\x1b[23;4H? - Help\x1b[23;27HTab - Deep Dwarf Chaos Knight\x1b[8;28H\x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m";

var p;

$().ready(function() {
			  p = TTYPlayer();
			  p.render_frame(t);
			  BinaryAjax('foo.ttyrec', function (data) { p.parse_data(data); });
		  });
<commit_msg>Now emptying the frame out before drawing things.<commit_after>function TTYPlayer () {
	var frame = $('#frame');
	var binary = null;
	var ttyrec = null;
	var index = 0;
	var buffer = [[]];
	var point = {
		x: 1, y: 1
	};
	var render_frame = function (string) {

		var regexp = new RegExp('\\x1b\\[([0-9;]*)([dmGHJX])');
		var span = {
			foreground: 'white-fg',
			background: 'black-bg',
			light: ''
		};

		var output_characters = function (index) {
			var substring = '';

			if (index == -1) {
				substring = string;
				string = '';
			}
			else {
				substring = string.slice(0, index);
				string = string.slice(index);
			}

			var pre = '';
			var post = '';

			for (var i in substring) {
				var character = substring[i];
				if (character == ' ') {
					character = ' ';
				}

				buffer[point.y - 1][point.x - 1] = pre + character + post;
				point.x++;
			}
		};

		var handle_esc = function() {
			var match = string.match(regexp);
			var value = match[1];
			var c = match[2];

			if (c == 'm') {
				if (value == '') {
					span.foreground = 'white-fg';
					span.background = 'black-bg';
					span.light = '';
				}
				else {
					var values = value.split(';');
					var l = values.length;
					for (var i = 0; i < l; i++) {
						var val = values[i];
						if (val == '0') {
							span.foreground = 'white-fg';
							span.background = 'black-bg';
							span.light = '';
						}
						else if (val == '1') {
							span.light = 'light-';
						}
						else if (val == '30') {
							span.foreground = 'black-fg';
						}
						else if (val == '33') {
							span.foreground = 'yellow-fg';
						}
						else if (val == '37') {
							span.foreground = 'white-fg';
						}
						else if (val == '39') {
							span.foreground = 'white-fg';
						}
						else if (val == '40') {
							span.background = 'black-bg';
						}
						else if (val == '42') {
							span.background = 'green-bg';
						}
						else if (val == '49') {
							span.background = 'black-bg';
						}
						else {
							console.error('Unhandled SGR parameter: ' + val);
						}
					}
				}
			}
			else if (c == 'H') {
				// Moves the point
				if (value == '') {
					point.x = 1;
					point.y = 1;
				}
				else {
					var values = value.split(';');

					if (values[0] != '') {
						var n = parseInt(values[0]);
						for (var i = 0; i + point.y < n; i++) {
							if (buffer[point.y + i] == undefined) {
								buffer[point.y + i] = [];
							}
						}
						point.y = n;
					}
					else {
						point.y = 1;
					}

					if (values.length == 2) {
						point.x = parseInt(values[1]);
					}
					else {
						point.x = 1;
					}
				}
			}
			else if (c == 'G') {
				// Moves the point horizontally.
				point.x = parseInt(value);
			}
			else if (c == 'J') {
				// Clear the buffer
				if (value == '') {
					// Same as 0 case,
					// clear from point to end of buffer.
					console.error('[J needs implementing');
				}
				else {
					var n = parseInt(value);
					if (n == 0) {
						// Same as empty case,
						// clear from point to end of buffer.
						console.error('[0J needs implementing');
					}
					else if (n == 1) {
						// Clear from point to beginning of buffer.
						console.error('[1J needs implementing');
					}
					else if (n == 2) {
						buffer = [[]];
						point.x = 1;
						point.y = 1;
					}
					else {
						console.error('Unhandled value for J: ' + value);
					}
				}
			}
			else {
				console.error('Unhandled escape sequence: ' + match[0]);
			}

			string = string.slice(match[0].length);
		};

		var print_buffer = function () {
			frame.empty();

			var m = buffer.length;
			for	(var i = 0; i < m; i++) {
				var row = buffer[i];
				var n = row.length;
				for (var j = 0; j < n; j++) {
					var character = row[j];
					if (character == undefined) {
						character = ' ';
					}
					frame.append(character);
				}
				frame.append('
');
			}
		};

		string = string.replace(/\x0f/g, '');

		while (string != '') {
			var index = string.search(regexp);

			if (index == -1 || index > 0) {
				output_characters(index);
			}
			else if (index == 0) {
				handle_esc();
			}
		}

		print_buffer();
	};

	return {
		get_ttyrec: function() {
			return ttyrec;
		},

		clear_frame: function() {
			buffer = [[]];
			point = { x:1, y: 1};
			render_frame('');
		},

		next_frame: function() {
			if (index < ttyrec.length) {
				var t = ttyrec[index];
				var s = binary.getStringAt(t.address, t.len);
				p.render_frame(s);
				index += 1;
			}
		},

		previous_frame: function() {
			if (index > 0) {
				var t = ttyrec[index];
				var s = binary.getStringAt(t.address, t.len);
				p.render_frame(s);
				index -= 1;
			}
		},

		parse_data: function (input) {
			binary = input.binaryResponse;
			ttyrec = [];

			var length = binary.getLength();
			var offset = 0;

			while (offset < length) {
				var sec = binary.getLongAt(offset + 0, false);
				var usec = binary.getLongAt(offset + 4, false);
				var len = binary.getLongAt(offset + 8, false);
				var address = offset + 12;

				ttyrec.push({
								sec: sec,
								usec: usec,
								len: len,
								address: address
							});

				offset += (12 + len);
			}
		},

		render_frame: render_frame
	};
}

var t = "\x1b[39;49m\x1b[37m\x1b[40m\x1b[H\x1b[2J\x1b[33m\x1b[40mWelcome, Shy.\x1b[0;1m\x0f\x1b[33m\x1b[40m Please select your species.\x1b[3;4H\x1b[0m\x0f\x1b[37m\x1b[40ma - Human\x1b[3;29Hi - Halfling\x1b[3;54Hq - Kenku\x1b[4;4Hb - High Elf\x1b[4;29Hj - Kobold\x1b[4;54Hr - Draconian\x1b[5;4Hc - Deep Elf\x1b[5;29Hk - Spriggan\x1b[5;54Hs - Demigod\x1b[6;4Hd - Sludge Elf\x1b[6;29Hl - Naga\x1b[6;54Ht - Demonspawn\x1b[7;4He - Mountain Dwarf\x1b[29Gm - Centaur\x1b[7;54Hu - Mummy\x1b[8;4H\x1b[37m\x1b[42mf - Deep Dwarf          \x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m \x1b[37m\x1b[40mn - Ogre\x1b[8;54Hv - Ghoul\x1b[9;4Hg - Hill Orc\x1b[9;29Ho - Troll\x1b[9;54Hw - Vampire\x1b[10;4Hh - Merfolk\x1b[10;29Hp - Minotaur\x1b[17;4H\x1b[0;1m\x0f\x1b[37m\x1b[40mThey live deep down and cannot regenerate, but they are resilient and have\x1b[0m\x0f\x1b[30m\x1b[40m  \x1b[18;4H\x1b[0;1m\x0f\x1b[37m\x1b[40mtools to heal.\x1b[20;4H\x1b[0m\x0f\x1b[33m\x1b[40m+ - Viable Species\x1b[29G* - Random species\x1b[21;4H# - Viable character\x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m     \x1b[33m\x1b[40m! - Random character\x1b[22;4H% - List aptitudes\x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m   \x1b[33m\x1b[40mSpace - Pick background first\x1b[23;4H? - Help\x1b[23;27HTab - Deep Dwarf Chaos Knight\x1b[8;28H\x1b[m\x0f\x1b[39;49m\x1b[37m\x1b[40m";

var p;

$().ready(function() {
			  p = TTYPlayer();
			  p.render_frame(t);
			  BinaryAjax('foo.ttyrec', function (data) { p.parse_data(data); });
		  });
<|endoftext|>


<commit_before>console.log('Application is starting.');

var socket = io.connect(window.location.hostname);
//var socket = io();

var canvas;
var ctx;
/*
var ball = {
	x: 200,
	y: 400,
	radius: 20,
	vx: 0,
	vy: 0
}; */
var ball;
var extraRight;
/*
var bounds = {
	left: 0,
	right: 600
};
*/
var bounds;
//var currentX = ball.x;
	var currentX;
//var lastX = currentX;
	var lastX;
//var currentY = ball.y;
	var currentY;
//var lastY = currentY;
	var lastY;
var isDragging = false;
var isTouchMove = false;
var touchobj = false;
var offset;
//var gravity = 5;
	var gravity;
//var bounce = 0.6;
	var bounce;
var mousePosX = 0;
var mousePosY = 0;
var lastSentX;
var lastSentY;
var lastSentAction;
var detecttouch = !! ('ontouchstart' in window) || !! ('ontouchstart' in document.documentElement) || !! window.ontouchstart || !! window.Touch || !! window.onmsgesturechange || (window.DocumentTouch && window.document instanceof window.DocumentTouch)

function drawBall() {

		ctx.clearRect(0,0,bounds.right,600);
		ctx.beginPath();
		ctx.arc(ball.x,ball.y,ball.radius,0,Math.PI * 2, false);
		ctx.stroke();
		ctx.fillStyle = 'red';
		ctx.fill();
		ctx.closePath();

}

socket.on('init', function (data) {
	console.log(bounds);
    ball = data.ballObj;
    bounds = data.boundsObj;
    console.log(data);
    console.log(bounds);
    extraRight = data.extraRight;
    drawBall();
  });

socket.on('ballPos', function (data) {
	ball.y = data.ballPosY;
	ball.x = data.ballPosX - extraRight;
	drawBall();
});

function updatePos(mousePosX, mousePosY, dragStatus) {
/*  console.log('updatePos');
    console.log('mousePosX: '+mousePosX);
	console.log('mousePosY: '+mousePosY);
	console.log('dragStatus: '+dragStatus); */
    if ((mousePosX !== lastSentX) && (mousePosY !== lastSentY) || (lastSentAction !== dragStatus)) {
        // console.log('coordinates or dragStatus new, updating...');
        socket.emit('inputPos',	{
                mousePosX: mousePosX+extraRight,
                mousePosY: mousePosY,
                isDragging: dragStatus
        });
    }
    else {
    // console.log('coordinates the same, not updating...');
    }
    lastSentX = mousePosX;
    lastSentY = mousePosY;
    lastSentAction = dragStatus;
}

function onDown(e) {
	console.log('running onDown');

	isDragging = true;
	if (isTouchMove) {
		touch = e.touches[0]; // Get the information for finger #1
		mousePosX = touch.pageX-canvas.offsetLeft;
		mousePosY = touch.pageY-canvas.offsetTop;
	}
	else {
		mousePosX = e.clientX-canvas.offsetLeft;
		mousePosY = e.clientY-canvas.offsetTop;
	}
	try
	{

		if (detecttouch) {
		    addEventListener('touchmove', function (e) {
		    	isTouchMove = true;
	        	onMove(e);
	        	e.preventDefault()
    		}, false)
		}

		addEventListener('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);

	}
	catch(e)
	{
		// ie
		attachEvent('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);
	}
	updatePos(mousePosX,mousePosY, true);
}

function onUp(e) {
	console.log('running onUp');

	isDragging = false;
	try
	{

		if (detecttouch) {
		    addEventListener('touchmove', function (e) {
		    	isTouchMove = true;
	        	onMove(e);
	        	e.preventDefault()
    		}, false)
		}

		removeEventListener('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);
	}
	catch(e)
	{
		// ie
		detachEvent('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);
	}
	updatePos(mousePosX,mousePosY, false);
}

function onMove(e) {

	if(isDragging) {
		if (isTouchMove) {
			touch = e.touches[0]; // Get the information for finger #1
			mousePosX = touch.pageX-canvas.offsetLeft;
			mousePosY = touch.pageY-canvas.offsetTop;
		}
		else {
			mousePosX = e.clientX-canvas.offsetLeft;
			mousePosY = e.clientY-canvas.offsetTop;
		}
		ball.x = mousePosX;
		ball.y = mousePosY;
		if(ball.x <= bounds.left)
			ball.x = bounds.left;
		else if(ball.x >= bounds.right)
			ball.x = bounds.right;
	updatePos(mousePosX,mousePosY, true);
	}

}

function grab()	{

	try	{

		if (detecttouch) {
			canvas.addEventListener('touchstart', function (e) {
			isTouchMove = true;
        	onDown(e);
        	e.preventDefault()
    	}, false)
 	   canvas.addEventListener('touchend', function (e) {
 	   		isTouchMove = true;
	        onUp(e);
	        e.preventDefault()
	    }, false)

 		}

		canvas.addEventListener('mousedown', function(e) {
			isTouchMove = false;
			onDown(e);
		} , false);
		canvas.addEventListener('mouseup', function(e) {
			isTouchMove = false;
			onUp(e);
		} , false);

	}
	catch(e) {

		// for IE
		canvas.attachEvent('mousedown', function(e) {
			isTouchMove = false;
			onDown(e);
		} , false);
		canvas.attachEvent('mouseup', function(e) {
			isTouchMove = false;
			onUp(e);
		} , false);

	}
	drawBall();
/*	setInterval(animate, 1000 / 60); */

}

/* window.onload = grab; */
window.onload = function () {
	canvas = document.getElementById('viewport');
	ctx = canvas.getContext('2d');
	grab();
}

/* grabity / ball end */<commit_msg>back again<commit_after>console.log('Application is starting.');

var socket = io.connect(window.location.hostname+':8080');
//var socket = io();

var canvas;
var ctx;
/*
var ball = {
	x: 200,
	y: 400,
	radius: 20,
	vx: 0,
	vy: 0
}; */
var ball;
var extraRight;
/*
var bounds = {
	left: 0,
	right: 600
};
*/
var bounds;
//var currentX = ball.x;
	var currentX;
//var lastX = currentX;
	var lastX;
//var currentY = ball.y;
	var currentY;
//var lastY = currentY;
	var lastY;
var isDragging = false;
var isTouchMove = false;
var touchobj = false;
var offset;
//var gravity = 5;
	var gravity;
//var bounce = 0.6;
	var bounce;
var mousePosX = 0;
var mousePosY = 0;
var lastSentX;
var lastSentY;
var lastSentAction;
var detecttouch = !! ('ontouchstart' in window) || !! ('ontouchstart' in document.documentElement) || !! window.ontouchstart || !! window.Touch || !! window.onmsgesturechange || (window.DocumentTouch && window.document instanceof window.DocumentTouch)

function drawBall() {

		ctx.clearRect(0,0,bounds.right,600);
		ctx.beginPath();
		ctx.arc(ball.x,ball.y,ball.radius,0,Math.PI * 2, false);
		ctx.stroke();
		ctx.fillStyle = 'red';
		ctx.fill();
		ctx.closePath();

}

socket.on('init', function (data) {
	console.log(bounds);
    ball = data.ballObj;
    bounds = data.boundsObj;
    console.log(data);
    console.log(bounds);
    extraRight = data.extraRight;
    drawBall();
  });

socket.on('ballPos', function (data) {
	ball.y = data.ballPosY;
	ball.x = data.ballPosX - extraRight;
	drawBall();
});

function updatePos(mousePosX, mousePosY, dragStatus) {
/*  console.log('updatePos');
    console.log('mousePosX: '+mousePosX);
	console.log('mousePosY: '+mousePosY);
	console.log('dragStatus: '+dragStatus); */
    if ((mousePosX !== lastSentX) && (mousePosY !== lastSentY) || (lastSentAction !== dragStatus)) {
        // console.log('coordinates or dragStatus new, updating...');
        socket.emit('inputPos',	{
                mousePosX: mousePosX+extraRight,
                mousePosY: mousePosY,
                isDragging: dragStatus
        });
    }
    else {
    // console.log('coordinates the same, not updating...');
    }
    lastSentX = mousePosX;
    lastSentY = mousePosY;
    lastSentAction = dragStatus;
}

function onDown(e) {
	console.log('running onDown');

	isDragging = true;
	if (isTouchMove) {
		touch = e.touches[0]; // Get the information for finger #1
		mousePosX = touch.pageX-canvas.offsetLeft;
		mousePosY = touch.pageY-canvas.offsetTop;
	}
	else {
		mousePosX = e.clientX-canvas.offsetLeft;
		mousePosY = e.clientY-canvas.offsetTop;
	}
	try
	{

		if (detecttouch) {
		    addEventListener('touchmove', function (e) {
		    	isTouchMove = true;
	        	onMove(e);
	        	e.preventDefault()
    		}, false)
		}

		addEventListener('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);

	}
	catch(e)
	{
		// ie
		attachEvent('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);
	}
	updatePos(mousePosX,mousePosY, true);
}

function onUp(e) {
	console.log('running onUp');

	isDragging = false;
	try
	{

		if (detecttouch) {
		    addEventListener('touchmove', function (e) {
		    	isTouchMove = true;
	        	onMove(e);
	        	e.preventDefault()
    		}, false)
		}

		removeEventListener('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);
	}
	catch(e)
	{
		// ie
		detachEvent('mousemove', function(e) {
			isTouchMove = false;
			onMove(e);
		} , false);
	}
	updatePos(mousePosX,mousePosY, false);
}

function onMove(e) {

	if(isDragging) {
		if (isTouchMove) {
			touch = e.touches[0]; // Get the information for finger #1
			mousePosX = touch.pageX-canvas.offsetLeft;
			mousePosY = touch.pageY-canvas.offsetTop;
		}
		else {
			mousePosX = e.clientX-canvas.offsetLeft;
			mousePosY = e.clientY-canvas.offsetTop;
		}
		ball.x = mousePosX;
		ball.y = mousePosY;
		if(ball.x <= bounds.left)
			ball.x = bounds.left;
		else if(ball.x >= bounds.right)
			ball.x = bounds.right;
	updatePos(mousePosX,mousePosY, true);
	}

}

function grab()	{

	try	{

		if (detecttouch) {
			canvas.addEventListener('touchstart', function (e) {
			isTouchMove = true;
        	onDown(e);
        	e.preventDefault()
    	}, false)
 	   canvas.addEventListener('touchend', function (e) {
 	   		isTouchMove = true;
	        onUp(e);
	        e.preventDefault()
	    }, false)

 		}

		canvas.addEventListener('mousedown', function(e) {
			isTouchMove = false;
			onDown(e);
		} , false);
		canvas.addEventListener('mouseup', function(e) {
			isTouchMove = false;
			onUp(e);
		} , false);

	}
	catch(e) {

		// for IE
		canvas.attachEvent('mousedown', function(e) {
			isTouchMove = false;
			onDown(e);
		} , false);
		canvas.attachEvent('mouseup', function(e) {
			isTouchMove = false;
			onUp(e);
		} , false);

	}
	drawBall();
/*	setInterval(animate, 1000 / 60); */

}

/* window.onload = grab; */
window.onload = function () {
	canvas = document.getElementById('viewport');
	ctx = canvas.getContext('2d');
	grab();
}

/* grabity / ball end */<|endoftext|>


<commit_before>//used for the media picker dialog
angular.module("umbraco").controller("Umbraco.Overlays.LinkPickerController",
    function ($scope, eventsService, dialogService, entityResource, mediaHelper, userService, localizationService, tinyMceService) {
        var dialogOptions = $scope.model;

        var searchText = "Search...";
        localizationService.localize("general_search").then(function (value) {
            searchText = value + "...";
        });

        if (!$scope.model.title) {
            $scope.model.title = localizationService.localize("defaultdialogs_selectLink");
        }

        $scope.dialogTreeEventHandler = $({});
        $scope.model.target = {};
        $scope.searchInfo = {
            searchFromId: null,
            searchFromName: null,
            showSearch: false,
            dataTypeId: dialogOptions.dataTypeId,
            results: [],
            selectedSearchResults: []
        };
        $scope.customTreeParams = dialogOptions.dataTypeId ? "dataTypeId=" + dialogOptions.dataTypeId : "";
        $scope.showTarget = $scope.model.hideTarget !== true;

        if (dialogOptions.currentTarget) {
            // clone the current target so we don't accidentally update the caller's model while manipulating $scope.model.target
            $scope.model.target = angular.copy(dialogOptions.currentTarget);
            //if we have a node ID, we fetch the current node to build the form data
            if ($scope.model.target.id || $scope.model.target.udi) {

                //will be either a udi or an int
                var id = $scope.model.target.udi ? $scope.model.target.udi : $scope.model.target.id;

                // is it a content link?
                if (!$scope.model.target.isMedia) {
                    // get the content path
                    entityResource.getPath(id, "Document").then(function (path) {
                        //now sync the tree to this path
                        $scope.dialogTreeEventHandler.syncTree({
                            path: path,
                            tree: "content"
                        });
                    });

                    entityResource.getUrlAndAnchors(id).then(function(resp){
                        $scope.anchorValues = resp.anchorValues;
                        $scope.model.target.url = resp.url;
                    });
                }
            } else if ($scope.model.target.url.length) {
                // a url but no id/udi indicates an external link - trim the url to remove the anchor/qs
                // only do the substring if there's a # or a ?
                var indexOfAnchor = $scope.model.target.url.search(/(#|\?)/);
                if (indexOfAnchor > -1) {
                    // populate the anchor
                    $scope.model.target.anchor = $scope.model.target.url.substring(indexOfAnchor);
                    // then rewrite the model and populate the link
                    $scope.model.target.url = $scope.model.target.url.substring(0, indexOfAnchor);
                }
            }
        } else if (dialogOptions.anchors) {
            $scope.anchorValues = dialogOptions.anchors;
        }

        function nodeSelectHandler(ev, args) {
            if (args && args.event) {
                args.event.preventDefault();
                args.event.stopPropagation();
            }

            eventsService.emit("dialogs.linkPicker.select", args);

            if ($scope.currentNode) {
                //un-select if there's a current one selected
                $scope.currentNode.selected = false;
            }

            $scope.currentNode = args.node;
            $scope.currentNode.selected = true;
            $scope.model.target.id = args.node.id;
            $scope.model.target.udi = args.node.udi;
            $scope.model.target.name = args.node.name;

            if (args.node.id < 0) {
                $scope.model.target.url = "/";
            } else {
                entityResource.getUrlAndAnchors(args.node.id).then(function(resp){
                    $scope.anchorValues = resp.anchorValues;
                    $scope.model.target.url = resp.url;
                });
            }

            if (!angular.isUndefined($scope.model.target.isMedia)) {
                delete $scope.model.target.isMedia;
            }
        }

        function nodeExpandedHandler(ev, args) {
            // open mini list view for list views
            if (args.node.metaData.isContainer) {
                openMiniListView(args.node);
            }
        }

        $scope.switchToMediaPicker = function () {
            userService.getCurrentUser().then(function (userData) {
                var startNodeId = userData.startMediaIds.length !== 1 ? -1 : userData.startMediaIds[0];
                var startNodeIsVirtual = userData.startMediaIds.length !== 1;

                if (dialogOptions.ignoreUserStartNodes) {
                    startNodeId = -1;
                    startNodeIsVirtual = true;
                }
                $scope.mediaPickerOverlay = {
                    view: "mediapicker",
                    startNodeId: startNodeId,
                    startNodeIsVirtual: startNodeIsVirtual,
                    show: true,
                    dataTypeId: dialogOptions.dataTypeId,
                    submit: function (model) {
                        var media = model.selectedImages[0];

                        $scope.model.target.id = media.id;
                        $scope.model.target.udi = media.udi;
                        $scope.model.target.isMedia = true;
                        $scope.model.target.name = media.name;
                        $scope.model.target.url = media.image;

                        $scope.mediaPickerOverlay.show = false;
                        $scope.mediaPickerOverlay = null;

                        // make sure the content tree has nothing highlighted
                        $scope.dialogTreeEventHandler.syncTree({
                            path: "-1",
                            tree: "content"
                        });
                    }
                };
            });
        };

        $scope.hideSearch = function () {
            $scope.searchInfo.showSearch = false;
            $scope.searchInfo.searchFromId = null;
            $scope.searchInfo.searchFromName = null;
            $scope.searchInfo.results = [];
        }

        // method to select a search result
        $scope.selectResult = function (evt, result) {
            result.selected = result.selected === true ? false : true;
            nodeSelectHandler(evt, {
                event: evt,
                node: result
            });
        };

        //callback when there are search results
        $scope.onSearchResults = function (results) {
            $scope.searchInfo.results = results;
            $scope.searchInfo.showSearch = true;
        };

        $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler);
        $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler);

        $scope.$on('$destroy', function () {
            $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler);
            $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler);
        });

        // Mini list view
        $scope.selectListViewNode = function (node) {
            node.selected = node.selected === true ? false : true;
            nodeSelectHandler({}, {
                node: node
            });
        };

        $scope.closeMiniListView = function () {
            $scope.miniListView = undefined;
        };

        function openMiniListView(node) {
            $scope.miniListView = node;
        }

    });
<commit_msg>Adjust comments<commit_after>//used for the media picker dialog
angular.module("umbraco").controller("Umbraco.Overlays.LinkPickerController",
    function ($scope, eventsService, dialogService, entityResource, mediaHelper, userService, localizationService, tinyMceService) {
        var dialogOptions = $scope.model;

        var searchText = "Search...";
        localizationService.localize("general_search").then(function (value) {
            searchText = value + "...";
        });

        if (!$scope.model.title) {
            $scope.model.title = localizationService.localize("defaultdialogs_selectLink");
        }

        $scope.dialogTreeEventHandler = $({});
        $scope.model.target = {};
        $scope.searchInfo = {
            searchFromId: null,
            searchFromName: null,
            showSearch: false,
            dataTypeId: dialogOptions.dataTypeId,
            results: [],
            selectedSearchResults: []
        };
        $scope.customTreeParams = dialogOptions.dataTypeId ? "dataTypeId=" + dialogOptions.dataTypeId : "";
        $scope.showTarget = $scope.model.hideTarget !== true;

        if (dialogOptions.currentTarget) {
            // clone the current target so we don't accidentally update the caller's model while manipulating $scope.model.target
            $scope.model.target = angular.copy(dialogOptions.currentTarget);
            // if we have a node ID, we fetch the current node to build the form data
            if ($scope.model.target.id || $scope.model.target.udi) {

                // will be either a udi or an int
                var id = $scope.model.target.udi ? $scope.model.target.udi : $scope.model.target.id;

                // is it a content link?
                if (!$scope.model.target.isMedia) {
                    // get the content path
                    entityResource.getPath(id, "Document").then(function (path) {
                        // now sync the tree to this path
                        $scope.dialogTreeEventHandler.syncTree({
                            path: path,
                            tree: "content"
                        });
                    });

                    entityResource.getUrlAndAnchors(id).then(function(resp){
                        $scope.anchorValues = resp.anchorValues;
                        $scope.model.target.url = resp.url;
                    });
                }
            } else if ($scope.model.target.url.length) {
                // a url but no id/udi indicates an external link - trim the url to remove the anchor/qs
                // only do the substring if there's a # or a ?
                var indexOfAnchor = $scope.model.target.url.search(/(#|\?)/);
                if (indexOfAnchor > -1) {
                    // populate the anchor
                    $scope.model.target.anchor = $scope.model.target.url.substring(indexOfAnchor);
                    // then rewrite the model and populate the link
                    $scope.model.target.url = $scope.model.target.url.substring(0, indexOfAnchor);
                }
            }
        } else if (dialogOptions.anchors) {
            $scope.anchorValues = dialogOptions.anchors;
        }

        function nodeSelectHandler(ev, args) {
            if (args && args.event) {
                args.event.preventDefault();
                args.event.stopPropagation();
            }

            eventsService.emit("dialogs.linkPicker.select", args);

            if ($scope.currentNode) {
                //un-select if there's a current one selected
                $scope.currentNode.selected = false;
            }

            $scope.currentNode = args.node;
            $scope.currentNode.selected = true;
            $scope.model.target.id = args.node.id;
            $scope.model.target.udi = args.node.udi;
            $scope.model.target.name = args.node.name;

            if (args.node.id < 0) {
                $scope.model.target.url = "/";
            } else {
                entityResource.getUrlAndAnchors(args.node.id).then(function(resp){
                    $scope.anchorValues = resp.anchorValues;
                    $scope.model.target.url = resp.url;
                });
            }

            if (!angular.isUndefined($scope.model.target.isMedia)) {
                delete $scope.model.target.isMedia;
            }
        }

        function nodeExpandedHandler(ev, args) {
            // open mini list view for list views
            if (args.node.metaData.isContainer) {
                openMiniListView(args.node);
            }
        }

        $scope.switchToMediaPicker = function () {
            userService.getCurrentUser().then(function (userData) {
                var startNodeId = userData.startMediaIds.length !== 1 ? -1 : userData.startMediaIds[0];
                var startNodeIsVirtual = userData.startMediaIds.length !== 1;

                if (dialogOptions.ignoreUserStartNodes) {
                    startNodeId = -1;
                    startNodeIsVirtual = true;
                }
                $scope.mediaPickerOverlay = {
                    view: "mediapicker",
                    startNodeId: startNodeId,
                    startNodeIsVirtual: startNodeIsVirtual,
                    show: true,
                    dataTypeId: dialogOptions.dataTypeId,
                    submit: function (model) {
                        var media = model.selectedImages[0];

                        $scope.model.target.id = media.id;
                        $scope.model.target.udi = media.udi;
                        $scope.model.target.isMedia = true;
                        $scope.model.target.name = media.name;
                        $scope.model.target.url = media.image;

                        $scope.mediaPickerOverlay.show = false;
                        $scope.mediaPickerOverlay = null;

                        // make sure the content tree has nothing highlighted
                        $scope.dialogTreeEventHandler.syncTree({
                            path: "-1",
                            tree: "content"
                        });
                    }
                };
            });
        };

        $scope.hideSearch = function () {
            $scope.searchInfo.showSearch = false;
            $scope.searchInfo.searchFromId = null;
            $scope.searchInfo.searchFromName = null;
            $scope.searchInfo.results = [];
        }

        // method to select a search result
        $scope.selectResult = function (evt, result) {
            result.selected = result.selected === true ? false : true;
            nodeSelectHandler(evt, {
                event: evt,
                node: result
            });
        };

        //callback when there are search results
        $scope.onSearchResults = function (results) {
            $scope.searchInfo.results = results;
            $scope.searchInfo.showSearch = true;
        };

        $scope.dialogTreeEventHandler.bind("treeNodeSelect", nodeSelectHandler);
        $scope.dialogTreeEventHandler.bind("treeNodeExpanded", nodeExpandedHandler);

        $scope.$on('$destroy', function () {
            $scope.dialogTreeEventHandler.unbind("treeNodeSelect", nodeSelectHandler);
            $scope.dialogTreeEventHandler.unbind("treeNodeExpanded", nodeExpandedHandler);
        });

        // Mini list view
        $scope.selectListViewNode = function (node) {
            node.selected = node.selected === true ? false : true;
            nodeSelectHandler({}, {
                node: node
            });
        };

        $scope.closeMiniListView = function () {
            $scope.miniListView = undefined;
        };

        function openMiniListView(node) {
            $scope.miniListView = node;
        }

    });
<|endoftext|>


<commit_before>// Ugis Germanis
// My javascript

// Set up stuff when webcomponents are ready
window.addEventListener('WebComponentsReady', function (e) {
    console.log('webcomponents are ready!!!');
    //Slider events
    music.slider = document.getElementById("slider");
    slider.addEventListener("mousedown", function () {
        music.sliderDrag = true;
    });
    slider.addEventListener("mouseup", function () {
        music.sliderDrag = false;
    });
    slider.addEventListener("change", function (e) {
        var estimate = music.mainSound.durationEstimate;
        music.mainSound.setPosition((estimate / 1000) * e.target.value);
        music.sliderDrag = false;
    });
    document.getElementById("menubutton").addEventListener("click", function (e) {
        startDrawer.toggle();
    });
    //Sorter
    document.getElementById("startDrawer").addEventListener("change", function (e) {
        if (e.target && e.target.nodeName == "PAPER-BUTTON") {
            var sorters = document.getElementsByClassName("sorter");
            for (i = 0; sorters.length > i; i++) {
                sorters[i].active = false;
            }
            music.selected = e.target.id.replace("post-", "");
            e.target.active = true;
            document.dispatchEvent(music.sort);
        }
    }, false);
    //Playback controls
    document.getElementById("next").addEventListener("click", function (e) {
        playnext();
    });
    document.getElementById("previous").addEventListener("click", function (e) {
        playprevious();
    });
    document.getElementById("playit").addEventListener("click", function (e) {
        play();
    });
    document.getElementById("pauseit").addEventListener("click", function (e) {
        pause();
    });
    document.getElementById("favoriteit").addEventListener("click", function (e) {
        //Set or Unset favorite
        $.get(
            [music.url, "/like"].join(""),
            { "like": music.playlist[music.current].ID },
            function (data) {
                document.getElementById("favoriteit").setAttribute("favorited", data);
            }
        );
    });
    //Sort event handler
    //Get the playlist
    document.addEventListener("sort", function (e) {
        $.get(
            [music.url, "/api"].join(""),
            { "sort": music.selected },
            function (data) {
                music.playlist = data;
                $("#playlist").attr('loading', true);
                music.render();
                $("#playlist").attr('loading', false);
            }
        );
    }, false);
    //Init sound object
    soundManager.setup({
        url: 'bower_components/SoundManager2/swf/soundmanager2_flash9.swf',
        flashVersion: 9,
        preferFlash: false,
        onready: function () {
            soundManager.createSound({
                id: "main",
                url: "",
                multiShot: false,
                onfinish: function () {
                    music.previous = music.current;
                    $(["#sound", music.current].join("")).attr("playing", false);
                    if (music.current == (music.playlist.length - 1)) {
                        music.current = 0;
                    } else {
                        music.current++;
                    }
                    this.unload();
                    playSong(music.current);
                    //Count the play
                    $.get(
                        [music.url, "/count"].join(""),
                        { "id": music.playlist[music.previous].ID }
                    );
                },
                onstop: function () {
                    $(["#sound", music.previous].join("")).attr("playing", false);
                    this.unload();
                },
                //Update the slider on playback
                whileplaying: function () {
                    if (music.sliderDrag === false) {
                        music.slider.value = (this.position / this.durationEstimate) * 1000;
                    }
                },
            });
            music.mainSound = soundManager.getSoundById("main");
        }
    });
    //Default sort
    document.getElementById(music.selected).active = true;
    document.dispatchEvent(music.sort);
    //Set up Media Session API controls
    if ('mediaSession' in navigator) {
        navigator.mediaSession.setActionHandler('nexttrack', function () {
            playnext();
        });
        navigator.mediaSession.setActionHandler('previoustrack', function () {
            playprevious();
        });
        navigator.mediaSession.setActionHandler('play', function () {
            play();
        });
        navigator.mediaSession.setActionHandler('pause', function () {
            pause();
        });
    }
});
//Main object
var music = {
    selected: "byartist",
    sort: new Event('sort'),
    playlist: null,
    mainSound: null,
    url: [document.location.protocol, "//", window.location.host].join(""),
    current: 0,
    previous: 0,
    slider: null,
    sliderDrag: false,
    //Render the playlist
    render: function () {
        $("#playlist").empty();
        var playlist = [""];
        for (i = 0; i < this.playlist.length; i++) {
            playlist.push("
", this.playlist[i].Title, " - ", this.playlist[i].Artist, "
");
        }
        $("#playlist").append(playlist.join(""));
        document.getElementById("playlist").addEventListener('click', function (e) {
            if (e.target && e.target.nodeName == "LI") {
                music.previous = music.current;
                music.current = e.target.getAttribute("index");
                playSong(music.current);
            }
        });
    },
};

//Play song by id
function playSong(id) {
    music.mainSound.stop();
    $(["#sound", id].join("")).attr("playing", true);
    music.mainSound.url = [music.url, "/stream?id=", music.playlist[id].ID].join("");
    music.mainSound.play();
    document.getElementsByTagName("body")[0].style.backgroundImage = ["url(", music.url, "/art?id=", music.playlist[id].ID, ")"].join("");
    //Set up media session data
    if ('mediaSession' in navigator) {
        navigator.mediaSession.metadata = new MediaMetadata({
            title: music.playlist[music.current].Title,
            artist: music.playlist[music.current].Artist,
            album: music.playlist[music.current].Album,
            artwork: [{ src: [music.url, "/art?id=", music.playlist[id].ID].join(""), }],
        });
    }
    //Get if liked or not
    $.get(
        [music.url, "/like"].join(""),
        { "id": music.playlist[id].ID },
        function (data) {
            document.getElementById("favoriteit").setAttribute("favorited", data);
        }
    );
}

//Playback functions
function playnext() {
    music.previous = music.current;
    if (music.current >= (music.playlist.length - 1)) {
        music.current = 0;
    } else {
        music.current++;
    }
    playSong(music.current);
}

function playprevious() {
    music.previous = music.current;
    if ((music.current == 0) || (music.current > music.playlist.length - 1)) {
        music.current = music.playlist.length - 1;
    } else {
        music.current--;
    }
    playSong(music.current);
}

function play() {
    if (music.mainSound.paused) {
        music.mainSound.resume();
    } else {
        playSong(music.current);
    }
}

function pause() {
    music.mainSound.pause();
}<commit_msg>hint the json data type<commit_after>// Ugis Germanis
// My javascript

// Set up stuff when webcomponents are ready
window.addEventListener('WebComponentsReady', function (e) {
    console.log('webcomponents are ready!!!');
    //Slider events
    music.slider = document.getElementById("slider");
    slider.addEventListener("mousedown", function () {
        music.sliderDrag = true;
    });
    slider.addEventListener("mouseup", function () {
        music.sliderDrag = false;
    });
    slider.addEventListener("change", function (e) {
        var estimate = music.mainSound.durationEstimate;
        music.mainSound.setPosition((estimate / 1000) * e.target.value);
        music.sliderDrag = false;
    });
    document.getElementById("menubutton").addEventListener("click", function (e) {
        startDrawer.toggle();
    });
    //Sorter
    document.getElementById("startDrawer").addEventListener("change", function (e) {
        if (e.target && e.target.nodeName == "PAPER-BUTTON") {
            var sorters = document.getElementsByClassName("sorter");
            for (i = 0; sorters.length > i; i++) {
                sorters[i].active = false;
            }
            music.selected = e.target.id.replace("post-", "");
            e.target.active = true;
            document.dispatchEvent(music.sort);
        }
    }, false);
    //Playback controls
    document.getElementById("next").addEventListener("click", function (e) {
        playnext();
    });
    document.getElementById("previous").addEventListener("click", function (e) {
        playprevious();
    });
    document.getElementById("playit").addEventListener("click", function (e) {
        play();
    });
    document.getElementById("pauseit").addEventListener("click", function (e) {
        pause();
    });
    document.getElementById("favoriteit").addEventListener("click", function (e) {
        //Set or Unset favorite
        $.get(
            [music.url, "/like"].join(""),
            { "like": music.playlist[music.current].ID },
            function (data) {
                document.getElementById("favoriteit").setAttribute("favorited", data);
            },
            "json"
        );
    });
    //Sort event handler
    //Get the playlist
    document.addEventListener("sort", function (e) {
        $.get(
            [music.url, "/api"].join(""),
            { "sort": music.selected },
            function (data) {
                music.playlist = data;
                $("#playlist").attr('loading', true);
                music.render();
                $("#playlist").attr('loading', false);
            },
            "json"
        );
    }, false);
    //Init sound object
    soundManager.setup({
        url: 'bower_components/SoundManager2/swf/soundmanager2_flash9.swf',
        flashVersion: 9,
        preferFlash: false,
        onready: function () {
            soundManager.createSound({
                id: "main",
                url: "",
                multiShot: false,
                onfinish: function () {
                    music.previous = music.current;
                    $(["#sound", music.current].join("")).attr("playing", false);
                    if (music.current == (music.playlist.length - 1)) {
                        music.current = 0;
                    } else {
                        music.current++;
                    }
                    this.unload();
                    playSong(music.current);
                    //Count the play
                    $.get(
                        [music.url, "/count"].join(""),
                        { "id": music.playlist[music.previous].ID }
                    );
                },
                onstop: function () {
                    $(["#sound", music.previous].join("")).attr("playing", false);
                    this.unload();
                },
                //Update the slider on playback
                whileplaying: function () {
                    if (music.sliderDrag === false) {
                        music.slider.value = (this.position / this.durationEstimate) * 1000;
                    }
                },
            });
            music.mainSound = soundManager.getSoundById("main");
        }
    });
    //Default sort
    document.getElementById(music.selected).active = true;
    document.dispatchEvent(music.sort);
    //Set up Media Session API controls
    if ('mediaSession' in navigator) {
        navigator.mediaSession.setActionHandler('nexttrack', function () {
            playnext();
        });
        navigator.mediaSession.setActionHandler('previoustrack', function () {
            playprevious();
        });
        navigator.mediaSession.setActionHandler('play', function () {
            play();
        });
        navigator.mediaSession.setActionHandler('pause', function () {
            pause();
        });
    }
});
//Main object
var music = {
    selected: "byartist",
    sort: new Event('sort'),
    playlist: null,
    mainSound: null,
    url: [document.location.protocol, "//", window.location.host].join(""),
    current: 0,
    previous: 0,
    slider: null,
    sliderDrag: false,
    //Render the playlist
    render: function () {
        $("#playlist").empty();
        var playlist = [""];
        for (i = 0; i < this.playlist.length; i++) {
            playlist.push("
", this.playlist[i].Title, " - ", this.playlist[i].Artist, "
");
        }
        $("#playlist").append(playlist.join(""));
        document.getElementById("playlist").addEventListener('click', function (e) {
            if (e.target && e.target.nodeName == "LI") {
                music.previous = music.current;
                music.current = e.target.getAttribute("index");
                playSong(music.current);
            }
        });
    },
};

//Play song by id
function playSong(id) {
    music.mainSound.stop();
    $(["#sound", id].join("")).attr("playing", true);
    music.mainSound.url = [music.url, "/stream?id=", music.playlist[id].ID].join("");
    music.mainSound.play();
    document.getElementsByTagName("body")[0].style.backgroundImage = ["url(", music.url, "/art?id=", music.playlist[id].ID, ")"].join("");
    //Set up media session data
    if ('mediaSession' in navigator) {
        navigator.mediaSession.metadata = new MediaMetadata({
            title: music.playlist[music.current].Title,
            artist: music.playlist[music.current].Artist,
            album: music.playlist[music.current].Album,
            artwork: [{ src: [music.url, "/art?id=", music.playlist[id].ID].join(""), }],
        });
    }
    //Get if liked or not
    $.get(
        [music.url, "/like"].join(""),
        { "id": music.playlist[id].ID },
        function (data) {
            document.getElementById("favoriteit").setAttribute("favorited", data);
        },
        "json"
    );
}

//Playback functions
function playnext() {
    music.previous = music.current;
    if (music.current >= (music.playlist.length - 1)) {
        music.current = 0;
    } else {
        music.current++;
    }
    playSong(music.current);
}

function playprevious() {
    music.previous = music.current;
    if ((music.current == 0) || (music.current > music.playlist.length - 1)) {
        music.current = music.playlist.length - 1;
    } else {
        music.current--;
    }
    playSong(music.current);
}

function play() {
    if (music.mainSound.paused) {
        music.mainSound.resume();
    } else {
        playSong(music.current);
    }
}

function pause() {
    music.mainSound.pause();
}<|endoftext|>


<commit_before>/**
 * Base62 Encoding JavaScript implementation
 *
 * @author odan (https://github.com/odan)
 * @license: MIT
 *
 * Thanks to: renmengye
 * https://github.com/renmengye/base62-csharp
 *
 * @example
 *
 * // encode
 * var strBase62 = $d.encodeBase62('test123');
 * console.log(strBase62);
 *
 * // decode
 * var strText = $d.decodeBase62(strBase62);
 * console.log(strText);
 *
 */

// Namespace stuff
if (!$d) {
    var $d = {};
}

/**
 * Utility that read and write bits in byte array
 * @param {type} options
 * @returns {BitStream}
 */
$d.BitStream = function BitStream(options) {
    this.Source = [];

    if (typeof options === 'object') {
        // Initialize the stream with a source byte array
        this.Source = options;
    }

    if (typeof options === 'number') {
        // Initialize the stream with capacity
        var dim = Math.floor(options);
        this.Source = new Array(dim);
    }

    // Bit position of the stream
    this.Position = 0;

    /**
     * Bit length of the stream
     * @returns {Number|@pro;length@this.Source}
     */
    this.Length = function () {
        return this.Source.length * 8;
    };

    /**
     * Read the stream to the buffer
     * @param {Array} buffer Buffer
     * @param {integer} offset Offset bit start position of the stream
     * @param {integer} count Number of bits to read
     * @returns {integer} Number of bits read
     */
    this.Read = function (buffer, offset, count) {
        // Temporary position cursor
        var tempPos = this.Position;
        tempPos += offset;
        // Buffer byte position and in-byte position
        var readPosCount = 0;
        var readPosMod = 0;
        // Stream byte position and in-byte position
        var posCount = tempPos >> 3;
        var posMod = (tempPos - ((tempPos >> 3) << 3));
        while (tempPos < this.Position + offset + count && tempPos < this.Length()) {
            // Copy the bit from the stream to buffer
            if (((this.Source[posCount]) & (0x1 << (7 - posMod))) != 0) {
                buffer[readPosCount] = ((buffer[readPosCount]) | (0x1 << (7 - readPosMod)));
            } else {
                buffer[readPosCount] = ((buffer[readPosCount]) & (0xffffffff - (0x1 << (7 - readPosMod))));
            }

            // Increment position cursors
            tempPos++;
            if (posMod == 7) {
                posMod = 0;
                posCount++;
            } else {
                posMod++;
            }
            if (readPosMod == 7) {
                readPosMod = 0;
                readPosCount++;
            } else {
                readPosMod++;
            }
        }
        var bits = (tempPos - this.Position - offset);
        this.Position = tempPos;
        return bits;
    };

    /**
     * Set up the stream position
     * @param {integer} offset Position
     * @param {integer} origin Position origin
     * @returns {integer} Position after setup
     */
    this.Seek = function (offset, origin) {
        switch (origin) {
            case (1):
                /*SeekOrigin.Begin*/
            {
                this.Position = offset;
                break;
            }
            case (2):
                /*SeekOrigin.Current*/
            {
                this.Position += offset;
                break;
            }
            case (3):
                /*SeekOrigin.End*/
            {
                this.Position = this.Length() + offset;
                break;
            }
        }
        return this.Position;
    };

    /**
     * Write from buffer to the stream
     * @param {type} buffer
     * @param {type} offset Offset start bit position of buffer
     * @param {type} count
     * @returns {undefined} Number of bits
     */
    this.Write = function (buffer, offset, count) {
        // Temporary position cursor
        var tempPos = this.Position;
        // Buffer byte position and in-byte position
        var readPosCount = offset >> 3,
            readPosMod = offset - ((offset >> 3) << 3);
        // Stream byte position and in-byte position
        var posCount = tempPos >> 3;
        var posMod = (tempPos - ((tempPos >> 3) << 3));
        while (tempPos < this.Position + count && tempPos < this.Length()) {
            // Copy the bit from buffer to the stream
            if (((buffer[readPosCount]) & (0x1 << (7 - readPosMod))) != 0) {
                this.Source[posCount] = ((this.Source[posCount]) | (0x1 << (7 - posMod)));
            } else {
                this.Source[posCount] = ((this.Source[posCount]) & (0xffffffff - (0x1 << (7 - posMod))));
            }

            // Increment position cursors
            tempPos++;
            if (posMod == 7) {
                posMod = 0;
                posCount++;
            } else {
                posMod++;
            }
            if (readPosMod == 7) {
                readPosMod = 0;
                readPosCount++;
            } else {
                readPosMod++;
            }
        }
        this.Position = tempPos;
    };
};

/**
 * Base62 Coding Space
 * @type String
 */
$d.Base62CodingSpace = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

/**
 * Convert a byte array
 * @param {String} original Byte array
 * @returns {unresolved} Base62 string
 */
$d.encodeBase62ToString = function encodeBase62ToString(original) {
    var sb = []; // new StringBuilder();
    var stream = new $d.BitStream(original); // Set up the BitStream
    var read = []; // Only read 6-bit at a time
    read.push(0);

    while (true) {
        read[0] = 0;

        var length = stream.Read(read, 0, 6); // Try to read 6 bits
        if (length == 6) // Not reaching the end
        {
            if ((read[0] >> 3) == 0x1f) // First 5-bit is 11111
            {
                sb.push($d.Base62CodingSpace.charAt(61));
                stream.Seek(-1, 2 /*SeekOrigin.Current*/); // Leave the 6th bit to next group
            } else if ((read[0] >> 3) == 0x1e) // First 5-bit is 11110
            {
                sb.push($d.Base62CodingSpace.charAt(60));
                stream.Seek(-1, 2 /*SeekOrigin.Current*/);
            } else // Encode 6-bit
            {
                sb.push($d.Base62CodingSpace.charAt((read[0] >> 2)));
            }
        } else {
            // Padding 0s to make the last bits to 6 bit
            sb.push($d.Base62CodingSpace.charAt((read[0] >> (8 - length))));
            break;
        }
    }
    var str = sb.join('');
    return str;
};

/**
 * Convert a Base62 string to byte array
 * @param {type} base62 Base62 string
 * @returns {Array} Byte array
 */
$d.decodeBase62ToArray = function decodeBase62ToArray(base62) {
    // Character count
    var count = 0;

    // Set up the BitStream
    var stream = new $d.BitStream(base62.length * 6 / 8);
    var len = base62.length;
    for (var i = 0; i < len; i++) {

        var c = base62.charAt(i);
        // Look up coding table
        var index = $d.Base62CodingSpace.indexOf(c);

        // If end is reached
        if (count == base62.length - 1) {
            // Check if the ending is good
            var mod = (stream.Position % 8);
            if (mod > 0) {
                stream.Write([(index << (mod))], 0, 8 - mod);
            }
        } else {
            // If 60 or 61 then only write 5 bits to the stream, otherwise 6 bits.
            if (index == 60) {
                //stream.Write(new byte[] { 0xf0 }, 0, 5);
                stream.Write([0xf0], 0, 5);
            } else if (index == 61) {
                stream.Write([0xf8], 0, 5);
            } else {
                stream.Write([index], 2, 6);
            }
        }
        count++;
    }

    // Dump out the bytes
    var result = new Array(stream.Position / 8);
    stream.Seek(0, 1 /* SeekOrigin.Begin*/);
    stream.Read(result, 0, result.length * 8);
    return result;
};

$d.encodeUtf8 = function (s) {
    return unescape(encodeURIComponent(s));
}

$d.decodeUtf8 = function (s) {
    return decodeURIComponent(escape(s));
}

/**
 * Encodes data with base62
 * @param {String} str The data to encode.
 * @returns {String}
 */
$d.encodeBase62 = function encodeBase62(str) {

    if (typeof str !== 'string' || str === '') {
        return '';
    }

    str = $d.encodeUtf8(str.toString());

    var bytes = [];
    var len = str.length;
    for (var i = 0; i < len; i++) {
        bytes.push(str.charCodeAt(i));
    }
    return this.encodeBase62ToString(bytes);
};

/**
 * Decodes a base62 encoded data.
 * @param {String} str
 * @returns {String} Returns the original data or false on failure.
 * The returned data may be binary.
 */
$d.decodeBase62 = function decodeBase62(str) {

    if (typeof str !== 'string' || str === '') {
        return '';
    }

    str = str.toString();

    var bytes = this.decodeBase62ToArray(str);
    var sb = [];
    var len = bytes.length;

    for (var i = 0; i < len; i++) {
        sb.push(String.fromCharCode(bytes[i]));
    }
    str = sb.join('');
    str = $d.decodeUtf8(str);

    return str;
};

/**
 * Encode base64 url.
 *
 * @param str
 * @returns {string}
 */
$d.encodeBase64url = function (str) {
    str = window.btoa($d.encodeUtf8(str));
    str = str.replace(/\+/g, '-');
    str = str.replace(new RegExp('/', 'g'), '_');
    var result = str.replace(new RegExp('=', 'g'), '');
    return result;
};

/**
 * Decode Base64 url.
 *
 * @param str
 * @returns {string}
 */
$d.decodeBase64url = function (str) {
    str += new Array((4 - (str.length % 4)) + 1).join("=");
    str = str.replace(new RegExp('-', 'g'), '+');
    str = str.replace(new RegExp('_', 'g'), '/');
    var result = window.atob(str);
    result = $d.decodeUtf8(result);
    return result;
};

/**
 * jQuery Plugin - Base62 Encoding
 *
 * @example
 * var strBase62 = $.encodeBase62('test123');
 * var strText = $.decodeBase62(strBase62);
 */
(function ($) {

    /**
     * Encodes data with base62.
     *
     * @param {String} str The data to encode.
     * @returns {String}
     */
    $.encodeBase62 = function encodeBase62(str) {
        return $d.encodeBase62(str);
    };

    /**
     * Decodes a base62 encoded data.
     *
     * @param {String} str
     * @returns {String} Returns the original data or false on failure.
     * The returned data may be binary.
     */
    $.decodeBase62 = function decodeBase62(str) {
        return $d.decodeBase62(str);
    };

    /**
     * Encodes data with base64url.
     *
     * @param {String} str The data to encode.
     * @returns {String}
     */
    $.encodeBase64url = function encodeBase64url(str) {
        return $d.encodeBase64url(str);
    };

    /**
     * Decodes a base64url encoded data.
     *
     * @param {String} str
     * @returns {String} Returns the original data or false on failure.
     * The returned data may be binary.
     */
    $.decodeBase64url = function decodeBase64url(str) {
        return $d.decodeBase64url(str);
    };

})(jQuery);<commit_msg>Added addition check for zero padding issue<commit_after>/**
 * Base62 Encoding JavaScript implementation
 *
 * @author odan (https://github.com/odan)
 * @license: MIT
 *
 * Thanks to: renmengye
 * https://github.com/renmengye/base62-csharp
 *
 * @example
 *
 * // encode
 * var strBase62 = $d.encodeBase62('test123');
 * console.log(strBase62);
 *
 * // decode
 * var strText = $d.decodeBase62(strBase62);
 * console.log(strText);
 *
 */

// Namespace stuff
if (!$d) {
    var $d = {};
}

/**
 * Utility that read and write bits in byte array
 * @param {type} options
 * @returns {BitStream}
 */
$d.BitStream = function BitStream(options) {
    this.Source = [];

    if (typeof options === 'object') {
        // Initialize the stream with a source byte array
        this.Source = options;
    }

    if (typeof options === 'number') {
        // Initialize the stream with capacity
        var dim = Math.floor(options);
        this.Source = new Array(dim);
    }

    // Bit position of the stream
    this.Position = 0;

    /**
     * Bit length of the stream
     * @returns {Number|@pro;length@this.Source}
     */
    this.Length = function () {
        return this.Source.length * 8;
    };

    /**
     * Read the stream to the buffer
     * @param {Array} buffer Buffer
     * @param {integer} offset Offset bit start position of the stream
     * @param {integer} count Number of bits to read
     * @returns {integer} Number of bits read
     */
    this.Read = function (buffer, offset, count) {
        // Temporary position cursor
        var tempPos = this.Position;
        tempPos += offset;
        // Buffer byte position and in-byte position
        var readPosCount = 0;
        var readPosMod = 0;
        // Stream byte position and in-byte position
        var posCount = tempPos >> 3;
        var posMod = (tempPos - ((tempPos >> 3) << 3));
        while (tempPos < this.Position + offset + count && tempPos < this.Length()) {
            // Copy the bit from the stream to buffer
            if (((this.Source[posCount]) & (0x1 << (7 - posMod))) != 0) {
                buffer[readPosCount] = ((buffer[readPosCount]) | (0x1 << (7 - readPosMod)));
            } else {
                buffer[readPosCount] = ((buffer[readPosCount]) & (0xffffffff - (0x1 << (7 - readPosMod))));
            }

            // Increment position cursors
            tempPos++;
            if (posMod == 7) {
                posMod = 0;
                posCount++;
            } else {
                posMod++;
            }
            if (readPosMod == 7) {
                readPosMod = 0;
                readPosCount++;
            } else {
                readPosMod++;
            }
        }
        var bits = (tempPos - this.Position - offset);
        this.Position = tempPos;
        return bits;
    };

    /**
     * Set up the stream position
     * @param {integer} offset Position
     * @param {integer} origin Position origin
     * @returns {integer} Position after setup
     */
    this.Seek = function (offset, origin) {
        switch (origin) {
            case (1):
                /*SeekOrigin.Begin*/
            {
                this.Position = offset;
                break;
            }
            case (2):
                /*SeekOrigin.Current*/
            {
                this.Position += offset;
                break;
            }
            case (3):
                /*SeekOrigin.End*/
            {
                this.Position = this.Length() + offset;
                break;
            }
        }
        return this.Position;
    };

    /**
     * Write from buffer to the stream
     * @param {type} buffer
     * @param {type} offset Offset start bit position of buffer
     * @param {type} count
     * @returns {undefined} Number of bits
     */
    this.Write = function (buffer, offset, count) {
        // Temporary position cursor
        var tempPos = this.Position;
        // Buffer byte position and in-byte position
        var readPosCount = offset >> 3,
            readPosMod = offset - ((offset >> 3) << 3);
        // Stream byte position and in-byte position
        var posCount = tempPos >> 3;
        var posMod = (tempPos - ((tempPos >> 3) << 3));
        while (tempPos < this.Position + count && tempPos < this.Length()) {
            // Copy the bit from buffer to the stream
            if (((buffer[readPosCount]) & (0x1 << (7 - readPosMod))) != 0) {
                this.Source[posCount] = ((this.Source[posCount]) | (0x1 << (7 - posMod)));
            } else {
                this.Source[posCount] = ((this.Source[posCount]) & (0xffffffff - (0x1 << (7 - posMod))));
            }

            // Increment position cursors
            tempPos++;
            if (posMod == 7) {
                posMod = 0;
                posCount++;
            } else {
                posMod++;
            }
            if (readPosMod == 7) {
                readPosMod = 0;
                readPosCount++;
            } else {
                readPosMod++;
            }
        }
        this.Position = tempPos;
    };
};

/**
 * Base62 Coding Space
 * @type String
 */
$d.Base62CodingSpace = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

/**
 * Convert a byte array
 * @param {String} original Byte array
 * @returns {unresolved} Base62 string
 */
$d.encodeBase62ToString = function encodeBase62ToString(original) {
    var sb = []; // new StringBuilder();
    var stream = new $d.BitStream(original); // Set up the BitStream
    var read = []; // Only read 6-bit at a time
    read.push(0);

    while (true) {
        read[0] = 0;

        var length = stream.Read(read, 0, 6); // Try to read 6 bits
        if (length == 6) // Not reaching the end
        {
            if ((read[0] >> 3) == 0x1f) // First 5-bit is 11111
            {
                sb.push($d.Base62CodingSpace.charAt(61));
                stream.Seek(-1, 2 /*SeekOrigin.Current*/); // Leave the 6th bit to next group
            } else if ((read[0] >> 3) == 0x1e) // First 5-bit is 11110
            {
                sb.push($d.Base62CodingSpace.charAt(60));
                stream.Seek(-1, 2 /*SeekOrigin.Current*/);
            } else // Encode 6-bit
            {
                sb.push($d.Base62CodingSpace.charAt((read[0] >> 2)));
            }
            //else if (length == 0)                           // Reached the end completely
            //{
            //    break;
            //}
        } else {
            // Padding 0s to make the last bits to 6 bit
            sb.push($d.Base62CodingSpace.charAt((read[0] >> (8 - length))));
            break;
        }
    }
    var str = sb.join('');
    return str;
};

/**
 * Convert a Base62 string to byte array
 * @param {type} base62 Base62 string
 * @returns {Array} Byte array
 */
$d.decodeBase62ToArray = function decodeBase62ToArray(base62) {
    // Character count
    var count = 0;

    // Set up the BitStream
    var stream = new $d.BitStream(base62.length * 6 / 8);
    var len = base62.length;
    for (var i = 0; i < len; i++) {

        var c = base62.charAt(i);
        // Look up coding table
        var index = $d.Base62CodingSpace.indexOf(c);

        // If end is reached
        if (count == base62.length - 1) {
            // Check if the ending is good
            var mod = (stream.Position % 8);

            if (mod == 0) {
                // InvalidDataException
                throw new Error("An extra character was found");
            }
            if ((index >> (8 - mod)) > 0) {
                // InvalidDataException
                throw new Error("Invalid ending character was found");
            }

            stream.Write([(index << (mod))], 0, 8 - mod);
        } else {
            // If 60 or 61 then only write 5 bits to the stream, otherwise 6 bits.
            if (index == 60) {
                //stream.Write(new byte[] { 0xf0 }, 0, 5);
                stream.Write([0xf0], 0, 5);
            } else if (index == 61) {
                stream.Write([0xf8], 0, 5);
            } else {
                stream.Write([index], 2, 6);
            }
        }
        count++;
    }

    // Dump out the bytes
    var result = new Array(stream.Position / 8);
    stream.Seek(0, 1 /* SeekOrigin.Begin*/);
    stream.Read(result, 0, result.length * 8);
    return result;
};

$d.encodeUtf8 = function (s) {
    return unescape(encodeURIComponent(s));
}

$d.decodeUtf8 = function (s) {
    return decodeURIComponent(escape(s));
}

/**
 * Encodes data with base62
 * @param {String} str The data to encode.
 * @returns {String}
 */
$d.encodeBase62 = function encodeBase62(str) {

    if (typeof str !== 'string' || str === '') {
        return '';
    }

    str = $d.encodeUtf8(str.toString());

    var bytes = [];
    var len = str.length;
    for (var i = 0; i < len; i++) {
        bytes.push(str.charCodeAt(i));
    }
    return this.encodeBase62ToString(bytes);
};

/**
 * Decodes a base62 encoded data.
 * @param {String} str
 * @returns {String} Returns the original data or false on failure.
 * The returned data may be binary.
 */
$d.decodeBase62 = function decodeBase62(str) {

    if (typeof str !== 'string' || str === '') {
        return '';
    }

    str = str.toString();

    var bytes = this.decodeBase62ToArray(str);
    var sb = [];
    var len = bytes.length;

    for (var i = 0; i < len; i++) {
        sb.push(String.fromCharCode(bytes[i]));
    }
    str = sb.join('');
    str = $d.decodeUtf8(str);

    return str;
};

/**
 * Encode base64 url.
 *
 * @param str
 * @returns {string}
 */
$d.encodeBase64url = function (str) {
    str = window.btoa($d.encodeUtf8(str));
    str = str.replace(/\+/g, '-');
    str = str.replace(new RegExp('/', 'g'), '_');
    var result = str.replace(new RegExp('=', 'g'), '');
    return result;
};

/**
 * Decode Base64 url.
 *
 * @param str
 * @returns {string}
 */
$d.decodeBase64url = function (str) {
    str += new Array((4 - (str.length % 4)) + 1).join("=");
    str = str.replace(new RegExp('-', 'g'), '+');
    str = str.replace(new RegExp('_', 'g'), '/');
    var result = window.atob(str);
    result = $d.decodeUtf8(result);
    return result;
};

/**
 * jQuery Plugin - Base62 Encoding
 *
 * @example
 * var strBase62 = $.encodeBase62('test123');
 * var strText = $.decodeBase62(strBase62);
 */
(function ($) {

    /**
     * Encodes data with base62.
     *
     * @param {String} str The data to encode.
     * @returns {String}
     */
    $.encodeBase62 = function encodeBase62(str) {
        return $d.encodeBase62(str);
    };

    /**
     * Decodes a base62 encoded data.
     *
     * @param {String} str
     * @returns {String} Returns the original data or false on failure.
     * The returned data may be binary.
     */
    $.decodeBase62 = function decodeBase62(str) {
        return $d.decodeBase62(str);
    };

    /**
     * Encodes data with base64url.
     *
     * @param {String} str The data to encode.
     * @returns {String}
     */
    $.encodeBase64url = function encodeBase64url(str) {
        return $d.encodeBase64url(str);
    };

    /**
     * Decodes a base64url encoded data.
     *
     * @param {String} str
     * @returns {String} Returns the original data or false on failure.
     * The returned data may be binary.
     */
    $.decodeBase64url = function decodeBase64url(str) {
        return $d.decodeBase64url(str);
    };

})(jQuery);<|endoftext|>


<commit_before>'use strict';

$(document).ready(function() {
	// Sortable init
	$('table.sortable tbody').sortable({
		helper: fixWidthHelper
	}).disableSelection();

	// Helper to keep full width of sortable tr's
	function fixWidthHelper(e, ui) {
		ui.children().each(function() {
			$(this).width($(this).width());
		});

		return ui;
	}

	// If desktop AND cookie says so - show left nav
	if ($(window).width() > 768 && Cookies.get('leftNav') === '1') {
		location.hash = 'main_nav';
	}

	// If click hamburger AND left nav is hidden - set cookie AND show left nav
	$('a.open_menu').on('click', function(event) {
		event.preventDefault();
		Cookies.set('leftNav', '1');
		location.hash = 'main_nav';

		// Make sure stuff in the right place after DOM change
		if (typeof doResizeActions === 'function') {
			doResizeActions();
		}
	});

	// If click hamburger AND left nav is visible - remove cookie AND hide left nav
	$('a.close_menu').on('click', function(event) {
		event.preventDefault();
		Cookies.remove('leftNav');
		location.hash = '';

		// Make sure stuff in the right place after DOM change
		if (typeof doResizeActions === 'function') {
			doResizeActions();
		}
	});

	// If click close msg_box
	$('.msg_box a.close').on('click', function(event) {
		event.preventDefault();
		$(this).closest('.msg_box').remove();
	});
});<commit_msg>error/message handling when saving sorting categories<commit_after>'use strict';

$(document).ready(function() {
	// Sortable init
	$('table.sortable tbody').sortable({
		helper: fixWidthHelper
	}).disableSelection();

	// Helper to keep full width of sortable tr's
	function fixWidthHelper(e, ui) {
		ui.children().each(function() {
			$(this).width($(this).width());
		});

		return ui;
	}

	// If desktop AND cookie says so - show left nav
	if ($(window).width() > 768 && Cookies.get('leftNav') === '1') {
		location.hash = 'main_nav';
	}

	// If click hamburger AND left nav is hidden - set cookie AND show left nav
	$('a.open_menu').on('click', function(event) {
		event.preventDefault();
		Cookies.set('leftNav', '1');
		location.hash = 'main_nav';

		// Make sure stuff in the right place after DOM change
		if (typeof doResizeActions === 'function') {
			doResizeActions();
		}
	});

	// If click hamburger AND left nav is visible - remove cookie AND hide left nav
	$('a.close_menu').on('click', function(event) {
		event.preventDefault();
		Cookies.remove('leftNav');
		location.hash = '';

		// Make sure stuff in the right place after DOM change
		if (typeof doResizeActions === 'function') {
			doResizeActions();
		}
	});

	// Close msg_box
	window.addMsgBoxClose = function() {
		$('.msg_box a.close').on('click', function(event) {
			event.preventDefault();
			$(this).closest('.msg_box').remove();
		});
	}

	addMsgBoxClose();
});<|endoftext|>


<commit_before>/*!
 * jQuery Cookie Plugin
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($, document) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
            options = $.extend({}, $.cookie.defaults, options);

            if (value == null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || $.cookie.defaults || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var cookies = document.cookie.split('; ');
        for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
            if (decode(parts.shift()) === key) {
                return decode(parts.join('='));
            }
        }
        return null;
    };

    $.cookie.defaults = {};

})(jQuery, document);
<commit_msg>Make jshint pass again<commit_after>/*jshint eqnull:true */
/*!
 * jQuery Cookie Plugin
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2011, Klaus Hartl
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/GPL-2.0
 */
(function($, document) {
    $.cookie = function(key, value, options) {

        // key and at least value given, set cookie...
        if (arguments.length > 1 && (!/Object/.test(Object.prototype.toString.call(value)) || value == null)) {
            options = $.extend({}, $.cookie.defaults, options);

            if (value == null) {
                options.expires = -1;
            }

            if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

            value = String(value);

            return (document.cookie = [
                encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
                options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                options.path    ? '; path=' + options.path : '',
                options.domain  ? '; domain=' + options.domain : '',
                options.secure  ? '; secure' : ''
            ].join(''));
        }

        // key and possibly options given, get cookie...
        options = value || $.cookie.defaults || {};
        var decode = options.raw ? function(s) { return s; } : decodeURIComponent;

        var cookies = document.cookie.split('; ');
        for (var i = 0, parts; (parts = cookies[i] && cookies[i].split('=')); i++) {
            if (decode(parts.shift()) === key) {
                return decode(parts.join('='));
            }
        }
        return null;
    };

    $.cookie.defaults = {};

})(jQuery, document);
<|endoftext|>


<commit_before>function AposPreferences() {
  // get the template
  self.schema = apos.data.aposPreferences.schema;

  $('[data-apos-preferences-menu]').click( function() {
    // get the preferences
    var $el = apos.modalFromTemplate('.apos-template.apos-preferences-modal', {});

    loadPreferences($el, function() {
      $el.find('[data-save]').on('click', function(e) {
        $(this).addClass('apos-busy');
        var data = {};
        savePreferences($el);
      });
    });
  });

  function loadPreferences($el, cb) {
    $.getJSON('/apos-preferences', function(data) {
      aposSchemas.populateFields($el, self.schema, data, cb);
    });
  }

  function savePreferences($el) {
    var data= {};
    aposSchemas.convertFields($el, self.schema, data, function(err) {
      if(err) {
        aposSchemas.scrollToError($el);
      }

      $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/apos-preferences',
        data: data,
        success: function(response) {
          apos.change('preferences');
        },
        error: function() {
          apos.notification('There was an error communicating with the server.', { type: 'error' });
        }
      })
    });
  }
}

$( function() {
  window.aposPreferences = new AposPreferences();
});<commit_msg>fixed bug causing selectize fields not to save<commit_after>function AposPreferences() {
  // get the template
  self.schema = apos.data.aposPreferences.schema;

  $('[data-apos-preferences-menu]').click( function() {

    // get the preferences
    var $el = apos.modalFromTemplate('.apos-template.apos-preferences-modal', {
      init: function(callback) {

        $.getJSON('/apos-preferences', function(data) {
          aposSchemas.populateFields($el, self.schema, data, function(){

            // set the save button listener
            $el.find('[data-save]').on('click', function(e) {
              $(this).addClass('apos-busy');
              var data = {};
              savePreferences($el);
            });

            return callback();
          });
        });

      }
    });
  });

  function savePreferences($el) {
    var data= {};
    aposSchemas.convertFields($el, self.schema, data, function(err) {
      if(err) {
        aposSchemas.scrollToError($el);
      }

      $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/apos-preferences',
        data: data,
        success: function(response) {
          apos.change('preferences');
        },
        error: function() {
          apos.notification('There was an error communicating with the server.', { type: 'error' });
        }
      })
    });
  }
}

$( function() {
  window.aposPreferences = new AposPreferences();
});<|endoftext|>