<commit_before>function Main(){}

//Test objects
var scene = null;
var camera = null;
var camera_rotation = null;
var renderer = null;
var cube = null;

//Cannon stuff
var world;

//Object selection
var raycaster = null;

//VR stuff
var vr_manager = null;
var vr_controls = null;

Main.initialize = function(canvas)
{
	//Create camera and scene
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera(75, canvas.width/canvas.height, 0.1, 100000);
	camera_rotation = new THREE.Vector2(0,0);

	//Raycaster
	raycaster = new THREE.Raycaster();

	//Renderer
	renderer = new THREE.WebGLRenderer({canvas: canvas});
	renderer.setSize(canvas.width, canvas.height);
	renderer.shadowMap.enabled = true;

	//Apply VR headset positional data to camera
	vr_controls = new THREE.VRControls(camera);
	var effect = new THREE.VREffect(renderer);
	effect.setSize(window.innerWidth, window.innerHeight);

	vr_manager = new WebVRManager(renderer, effect, {hideButton: false, isUndistorted: false});

	//Add cube to scene
	var material = new THREE.MeshPhongMaterial();
	cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);
	cube.position.z = -3;
	cube.receiveShadow = true;
	cube.castShadow = true;
	scene.add(cube);

	//Create Floor
	var geometry = new THREE.BoxGeometry(1, 1, 1);
	geometry.scale(100,1,100);

	var floor = new THREE.Mesh(geometry, material);
	floor.position.y = -1;
	floor.receiveShadow = true;
	floor.castShadow = true;
	scene.add(floor);

	//Load eyebot model (normal/specular mapped)
	var mtlLoader = new THREE.MTLLoader();
	mtlLoader.setBaseUrl("data/models/eyebot/");
	mtlLoader.load("data/models/eyebot/eyebot.mtl", function(materials)
	{
		materials.preload();
		var objLoader = new THREE.OBJLoader();
		objLoader.setMaterials(materials);
		objLoader.load("data/models/eyebot/eyebot.obj", function(object)
		{
			object.scale.set(0.03, 0.03, 0.03);
			object.position.set(4, 1, 4);
			setShadowReceiving(object, true);
			setShadowCasting(object, true);
			scene.add(object);
		});
	});

	//Load bane model (multi material obj/mtl)
	var mtlLoader = new THREE.MTLLoader();
	mtlLoader.setBaseUrl("data/models/bane/");
	mtlLoader.load("data/models/bane/bane.mtl", function(materials)
	{
		materials.preload();
		var objLoader = new THREE.OBJLoader();
		objLoader.setMaterials(materials);
		objLoader.load("data/models/bane/bane.obj", function(object)
		{
			object.scale.set(0.008, 0.008, 0.008);
			object.position.set(-4, -0.5, 4);
			setShadowReceiving(object, true);
			setShadowCasting(object, true);
			scene.add(object);
		});
	});

	//Dummy OBJ load test
	var objLoader = new THREE.OBJLoader();
	objLoader.load("data/models/dummy/dummy.obj", function(object)
	{
		object.scale.set(0.01, 0.01, 0.01);
		object.position.set(-4, 0, 0);
		setShadowReceiving(object, true);
		setShadowCasting(object, true);
		scene.add(object);
	});

	//Light
	var light = new THREE.AmbientLight(0x555555);
	scene.add(light);

	light = new THREE.SpotLight(0x330000);
	light.position.set(15, 10, 0);
	light.target.position.set(0, 0, 0);
	light.castShadow = true;
	scene.add(light);

	light = new THREE.SpotLight(0x000033);
	light.position.set(-15, 10, 0);
	light.target.position.set(0, 0, 0);
	light.castShadow = true;

	scene.add(light);

	light = new THREE.SpotLight(0x003300);
	light.position.set(0, 10, -15);
	light.target.position.set(0, 0, 0);
	light.castShadow = true;
	scene.add(light);

	//Grid and Axis Helper
	var gridHelper = new THREE.GridHelper(500, 20);
	scene.add(gridHelper);

	var axisHelper = new THREE.AxisHelper(500);
	scene.add(axisHelper);

	//Initialize Leap Hand
	LeapHand.initialize();
	scene.add(LeapHand.scene);

	//Init cannon
	/*var solver = new CANNON.GSSolver();
	solver.iterations = 7;
	solver.tolerance = 0.1;

	world = new CANNON.World();
	world.quatNormalizeSkip = 0;
	world.quatNormalizeFast = false;
	world.gravity.set(0,-10,0);
	world.broadphase = new CANNON.NaiveBroadphase();
	world.defaultContactMaterial.contactEquationStiffness = 1e9;
	world.defaultContactMaterial.contactEquationRelaxation = 4;
	world.solver = new CANNON.SplitSolver(solver);

	// Create a slippery material (friction coefficient = 0.1)
	var physicsMaterial = new CANNON.Material("slipperyMaterial");
	var physicsContactMaterial = new CANNON.ContactMaterial(physicsMaterial, physicsMaterial, 0.1, 0.3);

	// We must add the contact materials to the world
	world.addContactMaterial(physicsContactMaterial);

	// Create a sphere
	var mass = 5, radius = 1.3;
	var sphereShape = new CANNON.Sphere(radius);
	var sphereBody = new CANNON.Body({mass: mass});
	sphereBody.addShape(sphereShape);
	sphereBody.position.set(0,5,0);
	sphereBody.linearDamping = 0.9;
	world.addBody(sphereBody);

	// Create a plane
	var groundShape = new CANNON.Plane();
	var groundBody = new CANNON.Body({mass: 0});
	groundBody.addShape(groundShape);
	groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0),-Math.PI/2);
	world.addBody(groundBody);*/

}

Main.update = function()
{
	//Rotate cube
	cube.rotation.x += 0.01;

	//Rotate Camera
	if(Keyboard.isKeyPressed(Keyboard.E))
	{
		camera_rotation.x -= 0.02;
	}
	if(Keyboard.isKeyPressed(Keyboard.Q))
	{
		camera_rotation.x += 0.02;
	}

	//Camera Mouse Movement
	camera_rotation.x -= 0.01 * Mouse.SENSITIVITY * Mouse.pos_diff.x;
	camera_rotation.y -= 0.01 * Mouse.SENSITIVITY * Mouse.pos_diff.y;

	//Limit Vertical Rotation to 90 degrees
	var pid2 = 1.5708;
	if(camera_rotation.y < -pid2)
	{
		camera_rotation.y = -pid2;
	}
	else if(camera_rotation.y > pid2)
	{
		camera_rotation.y = pid2;
	}

	//Calculate direction vector
	var cos_angle_y = Math.cos(camera_rotation.y);
    var direction = new THREE.Vector3(Math.sin(camera_rotation.x)*cos_angle_y, Math.sin(camera_rotation.y), Math.cos(camera_rotation.x)*cos_angle_y);

    //Add position offset and set camera direction
    direction.x += camera.position.x;
    direction.y += camera.position.y;
    direction.z += camera.position.z;
    camera.lookAt(direction);

	//Update VR headset position and apply to camera.
	//vr_controls.update();

	//Move Camera with WASD
	var speed_walk = 0.2;
	var angle_cos = Math.cos(camera_rotation.x);
	var angle_sin = Math.sin(camera_rotation.x);
	if(Keyboard.isKeyPressed(Keyboard.S))
	{
		camera.position.z -= speed_walk * angle_cos;
		camera.position.x -= speed_walk * angle_sin;
	}
	if(Keyboard.isKeyPressed(Keyboard.W))
	{
		camera.position.z += speed_walk * angle_cos;
		camera.position.x += speed_walk * angle_sin;
	}

	var angle_cos = Math.cos(camera_rotation.x + Math.PI/2.0);
	var angle_sin = Math.sin(camera_rotation.x + Math.PI/2.0);
	if(Keyboard.isKeyPressed(Keyboard.A))
	{
		camera.position.z += speed_walk * angle_cos;
		camera.position.x += speed_walk * angle_sin;
	}
	if(Keyboard.isKeyPressed(Keyboard.D))
	{
		camera.position.z -= speed_walk * angle_cos;
		camera.position.x -= speed_walk * angle_sin;
	}

	if(Keyboard.isKeyPressed(Keyboard.SPACEBAR))
	{
		camera.position.y += 0.1;
	}
	if(Keyboard.isKeyPressed(Keyboard.CTRL))
	{
		camera.position.y -= 0.1;
	}

	//Enable leap hand shadowing
	setShadowReceiving(LeapHand.scene, true);
	setShadowCasting(LeapHand.scene, true);

	//Rasycast line from camera and mouse position
	if(Mouse.buttonJustPressed(Mouse.LEFT))
	{
		var mouse = new THREE.Vector2((Mouse.pos.x/window.innerWidth )*2 - 1, -(Mouse.pos.y/window.innerHeight)*2 + 1);

		//Update the picking ray with the camera and mouse position
		raycaster.setFromCamera(mouse, camera);

		var intersects = getSceneAllIntersected(scene, raycaster);

		//Change closeste object material
		if(intersects.length > 0)
		{
			intersects[0].object.material = new THREE.MeshNormalMaterial();
		}
	}

}

//Set shadow receiving
function setShadowReceiving(object, state)
{
	object.receiveShadow = true;

	for(var i = 0; i < object.children.length; i++)
	{
		setShadowReceiving(object.children[i], state);
	}
}

//Enable shadow casting
function setShadowCasting(object, state)
{
	object.castShadow = true;

	for(var i = 0; i < object.children.length; i++)
	{
		setShadowCasting(object.children[i], state);
	}
}

//Return a list of all intersected object in a scene
function getSceneAllIntersected(scene, raycaster)
{
	var intersects = raycaster.intersectObjects(scene.children);

	for(var i = 0; i < scene.children.length; i++)
	{
		intersects = intersects.concat(getSceneAllIntersected(scene.children[i], raycaster));
	}

	return intersects;
}

//Draw stuff into screen
Main.draw = function()
{
	vr_manager.render(scene, camera, App.time);
}

//Resize to fit window
Main.resize = function(canvas)
{
	renderer.setSize(canvas.width, canvas.height);
	camera.aspect = canvas.width/canvas.height;
	camera.updateProjectionMatrix();
}<commit_msg>Cannonjs tests added<commit_after>function Main(){}

//Test objects
var scene = null;
var camera = null;
var camera_rotation = null;
var renderer = null;
var cube = null;

//Cannon stuff
var world = null;
var physics_objects = [];
var render_objects = [];

//Object selection
var raycaster = null;

//VR stuff
var vr_manager = null;
var vr_controls = null;

Main.initialize = function(canvas)
{
	//Create camera and scene
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera(75, canvas.width/canvas.height, 0.1, 100000);
	camera_rotation = new THREE.Vector2(0,0);

	//Raycaster
	raycaster = new THREE.Raycaster();

	//Renderer
	renderer = new THREE.WebGLRenderer({canvas: canvas});
	renderer.setSize(canvas.width, canvas.height);
	renderer.shadowMap.enabled = true;

	//Apply VR headset positional data to camera
	vr_controls = new THREE.VRControls(camera);
	var effect = new THREE.VREffect(renderer);
	effect.setSize(window.innerWidth, window.innerHeight);

	vr_manager = new WebVRManager(renderer, effect, {hideButton: false, isUndistorted: false});

	//Add cube to scene
	var material = new THREE.MeshPhongMaterial();
	cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), material);
	cube.position.z = -3;
	cube.receiveShadow = true;
	cube.castShadow = true;
	scene.add(cube);

	//Create Floor
	var geometry = new THREE.BoxGeometry(1, 1, 1);
	geometry.scale(100,1,100);

	var floor = new THREE.Mesh(geometry, material);
	floor.position.y = -1;
	floor.receiveShadow = true;
	floor.castShadow = true;
	scene.add(floor);

	//Load eyebot model (normal/specular mapped)
	var mtlLoader = new THREE.MTLLoader();
	mtlLoader.setBaseUrl("data/models/eyebot/");
	mtlLoader.load("data/models/eyebot/eyebot.mtl", function(materials)
	{
		materials.preload();
		var objLoader = new THREE.OBJLoader();
		objLoader.setMaterials(materials);
		objLoader.load("data/models/eyebot/eyebot.obj", function(object)
		{
			object.scale.set(0.03, 0.03, 0.03);
			object.position.set(4, 1, 4);
			setShadowReceiving(object, true);
			setShadowCasting(object, true);
			scene.add(object);
		});
	});

	//Load bane model (multi material obj/mtl)
	var mtlLoader = new THREE.MTLLoader();
	mtlLoader.setBaseUrl("data/models/bane/");
	mtlLoader.load("data/models/bane/bane.mtl", function(materials)
	{
		materials.preload();
		var objLoader = new THREE.OBJLoader();
		objLoader.setMaterials(materials);
		objLoader.load("data/models/bane/bane.obj", function(object)
		{
			object.scale.set(0.008, 0.008, 0.008);
			object.position.set(-4, -0.5, 4);
			setShadowReceiving(object, true);
			setShadowCasting(object, true);
			scene.add(object);
		});
	});

	//Dummy OBJ load test
	var objLoader = new THREE.OBJLoader();
	objLoader.load("data/models/dummy/dummy.obj", function(object)
	{
		object.scale.set(0.01, 0.01, 0.01);
		object.position.set(-4, 0, 0);
		setShadowReceiving(object, true);
		setShadowCasting(object, true);
		scene.add(object);
	});

	//Light
	var light = new THREE.AmbientLight(0x555555);
	scene.add(light);

	light = new THREE.SpotLight(0x330000);
	light.position.set(15, 10, 0);
	light.target.position.set(0, 0, 0);
	light.castShadow = true;
	scene.add(light);

	light = new THREE.SpotLight(0x000033);
	light.position.set(-15, 10, 0);
	light.target.position.set(0, 0, 0);
	light.castShadow = true;

	scene.add(light);

	light = new THREE.SpotLight(0x003300);
	light.position.set(0, 10, -15);
	light.target.position.set(0, 0, 0);
	light.castShadow = true;
	scene.add(light);

	//Grid and Axis Helper
	var gridHelper = new THREE.GridHelper(500, 20);
	scene.add(gridHelper);

	var axisHelper = new THREE.AxisHelper(500);
	scene.add(axisHelper);

	//Initialize Leap Hand
	LeapHand.initialize();
	scene.add(LeapHand.scene);

	//Init cannon
	world = new CANNON.World();
	world.broadphase = new CANNON.NaiveBroadphase();
	world.gravity.set(0,-10,0);
	world.solver.tolerance = 0.001;

	// Ground plane
	var plane = new CANNON.Plane();
	var groundBody = new CANNON.Body({ mass: 0 });
	groundBody.addShape(plane);
	groundBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1,0,0),-Math.PI/2);
	world.addBody(groundBody);

	var N = 100;

	//Create N cubes for physics
	var shape = new CANNON.Box(new CANNON.Vec3(0.5,0.5,0.5));
	for(var i = 0; i < N; i++)
	{
		var body = new CANNON.Body({ mass: 1 });
		body.addShape(shape);
		body.position.set(Math.random()-0.5,2.5*i+0.5,Math.random()-0.5);
		physics_objects.push(body);
		world.addBody(body);
	}

	//Create N cubes for render
	var cubeGeo = new THREE.BoxGeometry( 1, 1, 1, 10, 10 );
	var cubeMaterial = new THREE.MeshPhongMaterial( { color: 0x888888 } );
	for(var i = 0; i < N; i++)
	{
		cubeMesh = new THREE.Mesh( cubeGeo, cubeMaterial );
		cubeMesh.castShadow = true;
		render_objects.push(cubeMesh);
		scene.add(cubeMesh);
	}

}

Main.update = function()
{
	//Step physics world
	world.step(1/60);

	for(var i = 0; i < render_objects.length; i++)
	{
		render_objects[i].position.set(physics_objects[i].position.x, physics_objects[i].position.y, physics_objects[i].position.z);
		//render_objects[i].rotation.set(physics_objects[i].rotation.x, physics_objects[i].rotation.y, physics_objects[i].rotation.z);
		//console.log("(" + render_objects[i].position.x + ", " + render_objects[i].position.y + ", " + render_objects[i].position.z + ")");
		//console.log("(" + physics_objects[i].position.x + ", " + physics_objects[i].position.y + ", " + physics_objects[i].position.z + ")");
	}

	//Rotate cube
	cube.rotation.x += 0.01;

	//Rotate Camera
	if(Keyboard.isKeyPressed(Keyboard.E))
	{
		camera_rotation.x -= 0.02;
	}
	if(Keyboard.isKeyPressed(Keyboard.Q))
	{
		camera_rotation.x += 0.02;
	}

	//Camera Mouse Movement
	camera_rotation.x -= 0.01 * Mouse.SENSITIVITY * Mouse.pos_diff.x;
	camera_rotation.y -= 0.01 * Mouse.SENSITIVITY * Mouse.pos_diff.y;

	//Limit Vertical Rotation to 90 degrees
	var pid2 = 1.5708;
	if(camera_rotation.y < -pid2)
	{
		camera_rotation.y = -pid2;
	}
	else if(camera_rotation.y > pid2)
	{
		camera_rotation.y = pid2;
	}

	//Calculate direction vector
	var cos_angle_y = Math.cos(camera_rotation.y);
    var direction = new THREE.Vector3(Math.sin(camera_rotation.x)*cos_angle_y, Math.sin(camera_rotation.y), Math.cos(camera_rotation.x)*cos_angle_y);

    //Add position offset and set camera direction
    direction.x += camera.position.x;
    direction.y += camera.position.y;
    direction.z += camera.position.z;
    camera.lookAt(direction);

	//Update VR headset position and apply to camera.
	//vr_controls.update();

	//Move Camera with WASD
	var speed_walk = 0.2;
	var angle_cos = Math.cos(camera_rotation.x);
	var angle_sin = Math.sin(camera_rotation.x);
	if(Keyboard.isKeyPressed(Keyboard.S))
	{
		camera.position.z -= speed_walk * angle_cos;
		camera.position.x -= speed_walk * angle_sin;
	}
	if(Keyboard.isKeyPressed(Keyboard.W))
	{
		camera.position.z += speed_walk * angle_cos;
		camera.position.x += speed_walk * angle_sin;
	}

	var angle_cos = Math.cos(camera_rotation.x + Math.PI/2.0);
	var angle_sin = Math.sin(camera_rotation.x + Math.PI/2.0);
	if(Keyboard.isKeyPressed(Keyboard.A))
	{
		camera.position.z += speed_walk * angle_cos;
		camera.position.x += speed_walk * angle_sin;
	}
	if(Keyboard.isKeyPressed(Keyboard.D))
	{
		camera.position.z -= speed_walk * angle_cos;
		camera.position.x -= speed_walk * angle_sin;
	}

	if(Keyboard.isKeyPressed(Keyboard.SPACEBAR))
	{
		camera.position.y += 0.1;
	}
	if(Keyboard.isKeyPressed(Keyboard.CTRL))
	{
		camera.position.y -= 0.1;
	}

	//Enable leap hand shadowing
	setShadowReceiving(LeapHand.scene, true);
	setShadowCasting(LeapHand.scene, true);

	//Rasycast line from camera and mouse position
	if(Mouse.buttonJustPressed(Mouse.LEFT))
	{
		var mouse = new THREE.Vector2((Mouse.pos.x/window.innerWidth )*2 - 1, -(Mouse.pos.y/window.innerHeight)*2 + 1);

		//Update the picking ray with the camera and mouse position
		raycaster.setFromCamera(mouse, camera);

		var intersects = getSceneAllIntersected(scene, raycaster);

		//Change closeste object material
		if(intersects.length > 0)
		{
			intersects[0].object.material = new THREE.MeshNormalMaterial();
		}
	}

}

//Set shadow receiving
function setShadowReceiving(object, state)
{
	object.receiveShadow = true;

	for(var i = 0; i < object.children.length; i++)
	{
		setShadowReceiving(object.children[i], state);
	}
}

//Enable shadow casting
function setShadowCasting(object, state)
{
	object.castShadow = true;

	for(var i = 0; i < object.children.length; i++)
	{
		setShadowCasting(object.children[i], state);
	}
}

//Return a list of all intersected object in a scene
function getSceneAllIntersected(scene, raycaster)
{
	var intersects = raycaster.intersectObjects(scene.children);

	for(var i = 0; i < scene.children.length; i++)
	{
		intersects = intersects.concat(getSceneAllIntersected(scene.children[i], raycaster));
	}

	return intersects;
}

//Draw stuff into screen
Main.draw = function()
{
	vr_manager.render(scene, camera, App.time);
}

//Resize to fit window
Main.resize = function(canvas)
{
	renderer.setSize(canvas.width, canvas.height);
	camera.aspect = canvas.width/canvas.height;
	camera.updateProjectionMatrix();
}<|endoftext|>


<commit_before>/**
 *
 */

VK.init({
    apiId: 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray = [];

function getGroupInfo(groupId) {

    VK.api("groups.getById", { 'group_id': Math.abs(groupId), 'fields': 'members_count,photo_100' }, function (data) {
        if (data.error) {
            errorMSG('Error in data. Wrong group data.')
        }else{
            for (var i = 0; i < data.response.length; i++) {
                grp = data.response[i].name;
                us = data.response[i].members_count;
                grpAvatar = data.response[i].photo_100;

                obj[0] = grp;
                obj[1] = us;
                obj[2] = grpAvatar;

            }
            groupViewChanges(getGroupData());
        }
	});

    waiting();//wait
    getGroupMembers(parsed);
}

function getGroupMembers(objTargets){ //,memCount,offset) {
    var aboutPost = objTargets; // 0-group, 1-item_post
    var code = '';
    console.log(aboutPost[0],aboutPost[1]);
    /*code = 'var c=0;var co=1000;var p=[];var i=0;var o=0;var u=[];'+
        'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":'+aboutPost[0]+',"item_id":'+aboutPost[1]+',"filter":"likes","friends_only":0,"offset":o,"count":co});'+
        'c=li.count;u=u+API.users.get({"user_ids":li.items,"fields":"sex"})@.sex;i=i+1;o=o+co;}'+
        'return {"count":c,"user":u,"l":u.length};';*/
    code = 'var c=0;var u=[];' +
        +'var li=API.likes.getList({"type":"post","owner_id":'
        + '-10639516' + ',"item_id":' + '58468105' + ',"filter":"likes","friends_only":0,"offset":0,"count":1000});'
        +'c=li.count;var s=API.users.get({"user_ids":li.items,"fields":"sex"}); u=u+s@.sex;'
        +'return {"count":c,"user":u,"l":u.length};';
    //http://vk.com/mdk?w=wall-10639516_58468105
    VK.api('execute', { 'code': code, }, function (data) {
        console.log(data);
        if (data.response.error) {
            errorMSG('Wrong: Group Member');
            console.log("error");
        } else {

        }
    });
}

function getGroupData() {
    return obj;
}

function getParsedInfo() {
    return parsed;
}

function waiting() {
    var se = 0;
    setTimeout(function () {
        if (se++ > 1) {
            waiting();
            console.log('wait');
        }
    }, 400);
}

    function groupViewChanges(obj) {
        var a = obj;
        document.getElementById('groupName').innerHTML = 'Name: '+a[0];
        document.getElementById('members_count').innerHTML = 'Count: '+a[1];
        document.getElementById('av').src = a[2];
    }

    function parseLink() {
        var link = String(document.getElementById('post').value);

        if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

            if (link.indexOf('=wall') != -1) {
                var adr = link.substring(link.indexOf('=wall') + 5, link.length);
                var p = adr.split('_');
                if ((p[0] === undefined) && (p[1] === undefined)) {
                    errorMSG('Wrong: group or post or both');
                } else {
                    if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
                        parsed[0] = p[0]; parsed[1] = p[1];
                        getGroupInfo(parsed[0]);
                    }

                }
            } else {
                errorMSG('Wrong: not wall post');
            }
        }else{
            errorMSG('Wrong: not vk.com');
        }
    }

    function clearadress() {
        document.getElementById('post').value = '';
    }

    function errorMSG(msg) {
        document.getElementById('post').value = msg;
        setTimeout(clearadress, 1000);
    }<commit_msg>changes<commit_after>/**
 *
 */

VK.init({
    apiId: 1755175
});

var WRONG_TEXT = 'Something goes wrong. Enter valid post address.';

var grp = '';
var us = '';
var grpAvatar = '';

var obj = [];
var parsed = [0, 0];

var grCount = 0;
var grOffset = 0;

var sexArray = [];

function getGroupInfo(groupId) {

    VK.api("groups.getById", { 'group_id': Math.abs(groupId), 'fields': 'members_count,photo_100' }, function (data) {
        if (data.error) {
            errorMSG('Error in data. Wrong group data.')
        }else{
            for (var i = 0; i < data.response.length; i++) {
                grp = data.response[i].name;
                us = data.response[i].members_count;
                grpAvatar = data.response[i].photo_100;

                obj[0] = grp;
                obj[1] = us;
                obj[2] = grpAvatar;

            }
            groupViewChanges(getGroupData());
        }
	});

    waiting();//wait
    getGroupMembers(parsed);
}

function getGroupMembers(objTargets){ //,memCount,offset) {
    var aboutPost = objTargets; // 0-group, 1-item_post
    var code = '';
    console.log(aboutPost[0],aboutPost[1]);
    /*code = 'var c=0;var co=1000;var p=[];var i=0;var o=0;var u=[];'+
        'while(i!=10) {var li=API.likes.getList({"type":"post","owner_id":'+aboutPost[0]+',"item_id":'+aboutPost[1]+',"filter":"likes","friends_only":0,"offset":o,"count":co});'+
        'c=li.count;u=u+API.users.get({"user_ids":li.items,"fields":"sex"})@.sex;i=i+1;o=o+co;}'+
        'return {"count":c,"user":u,"l":u.length};';*/
    code = 'var c=0;var u=[];'
        +'var li=API.likes.getList({"type":"post","owner_id":'
        +'-10639516' + ',"item_id":' + '58468105' + ',"filter":"likes","friends_only":0,"offset":0,"count":1000});'
        +'c=li.count;var s=API.users.get({"user_ids":li.items,"fields":"sex"}); u=u+s@.sex;'
        +'return {"count":c,"user":u,"l":u.length};';
    //http://vk.com/mdk?w=wall-10639516_58468105
    VK.api('execute', { 'code': code, }, function (data) {
        console.log(data);
        if (data.response.error) {
            errorMSG('Wrong: Group Member');
            console.log("error");
        } else {

        }
    });
}

function getGroupData() {
    return obj;
}

function getParsedInfo() {
    return parsed;
}

function waiting() {
    var se = 0;
    setTimeout(function () {
        if (se++ > 1) {
            waiting();
            console.log('wait');
        }
    }, 400);
}

    function groupViewChanges(obj) {
        var a = obj;
        document.getElementById('groupName').innerHTML = 'Name: '+a[0];
        document.getElementById('members_count').innerHTML = 'Count: '+a[1];
        document.getElementById('av').src = a[2];
    }

    function parseLink() {
        var link = String(document.getElementById('post').value);

        if (link != '' && (link.match('vk.com') == 'vk.com') && (link.match('wall-') == 'wall-')) {

            if (link.indexOf('=wall') != -1) {
                var adr = link.substring(link.indexOf('=wall') + 5, link.length);
                var p = adr.split('_');
                if ((p[0] === undefined) && (p[1] === undefined)) {
                    errorMSG('Wrong: group or post or both');
                } else {
                    if ((/\d+/.test(p[0])) && (/\d+/.test(p[1]))) {
                        parsed[0] = p[0]; parsed[1] = p[1];
                        getGroupInfo(parsed[0]);
                    }

                }
            } else {
                errorMSG('Wrong: not wall post');
            }
        }else{
            errorMSG('Wrong: not vk.com');
        }
    }

    function clearadress() {
        document.getElementById('post').value = '';
    }

    function errorMSG(msg) {
        document.getElementById('post').value = msg;
        setTimeout(clearadress, 1000);
    }<|endoftext|>


<commit_before>angular.module('Universities',[])

.factory('UniversityList',function(){
	return {
		universityofwaterloo:{
			name: 'University Of Waterloo',
			location:{
				city: "Waterloo",
				state: "Ontario",
				country: "Canada"
			},
			commonCreditWeights:[0.25,0.5,0.75,0.80,1],
			percentageGradeToGPA: { //assumes a 4.0 GPA system
				"4.0": {
					value: 4,
					min: 90,
					max: 100
				},
				"3.90":{
					value: 3.9,
					min: 85,
					max: 89
				},
				"3.70":{
					value: 3.7,
					min: 80,
					max: 84
				},
				"3.30":{
					value: 3.3,
					min: 77,
					max: 79
				},
				"3.00":{
					value: 3,
					min: 73,
					max: 76
				},
				"2.70":{
					value: 2.7,
					min: 70,
					max: 72
				},
				"2.30":{
					value: 2.3,
					min: 67,
					max: 69
				},
				"2.00":{
					value: 2,
					min: 63,
					max: 66
				},
				"1.70":{
					value: 1.7,
					min: 60,
					max: 62
				},
				"1.30":{
					value: 1.3,
					min: 57,
					max: 59
				},
				"1.00":{
					value: 1,
					min: 53,
					max: 55
				},
				"0.70":{
					value:0.7 ,
					min: 50,
					max: 52
				},
				"0.00":{
					value: 0,
					min: 0,
					max: 49
				}
			},
			letterGradeToGPA:{
				'4.0':{
					value: 4,
					letters: ['A+']
				},
				'3.90':{
					value: 3.9,
					letters:['A']
				},
				'3.70':{
					value: 3.7,
					letters:['A-']
				},
				'3.30':{
					value: 3.3,
					letters:['B+']
				},
				'3.00':{
					value: 3,
					letters:['B']
				},
				'2.70':{
					value: 2.7,
					letters:['B-']
				},
				'2.30':{
					value: 2.3,
					letters:['C+']
				},
				'2.00':{
					value: 2,
					letters:['C']
				},
				'1.70':{
					value: 1.7,
					letters:['C-']
				},
				'1.30':{
					value: 1.3,
					letters:['D+']
				},
				'1.00':{
					value: 1,
					letters:['D']
				},
				'0.70':{
					value: 0.7,
					letters:['D-']
				},
				'0.00':{
					value: 0,
					letters:['E','F']
				}
			},
			customGradeToGPA:false
		},
		universityoftoronto:{
			name: 'University Of Toronto',
			location:{
				city: "Toronto",
				state: "Ontario",
				country: "Canada"
			},
			commonCreditWeights:[0.25,0.5,0.75,0.80,1],
			percentageGradeToGPA: { //assumes a 4.0 GPA system
				"4.0": {
					value: 4,
					min: 90,
					max: 100
				},
				"3.90":{
					value: 3.9,
					min: 85,
					max: 89
				},
				"3.70":{
					value: 3.7,
					min: 80,
					max: 84
				},
				"3.30":{
					value: 3.3,
					min: 77,
					max: 79
				},
				"3.00":{
					value: 3,
					min: 73,
					max: 76
				},
				"2.70":{
					value: 2.7,
					min: 70,
					max: 72
				},
				"2.30":{
					value: 2.3,
					min: 67,
					max: 69
				},
				"2.00":{
					value: 2,
					min: 63,
					max: 66
				},
				"1.70":{
					value: 1.7,
					min: 60,
					max: 62
				},
				"1.30":{
					value: 1.3,
					min: 57,
					max: 59
				},
				"1.00":{
					value: 1,
					min: 53,
					max: 55
				},
				"0.70":{
					value:0.7 ,
					min: 50,
					max: 52
				},
				"0.00":{
					value: 0,
					min: 0,
					max: 49
				}
			},
			letterGradeToGPA:{
				'4.0':{
					value: 4,
					letters: ['A+']
				},
				'3.90':{
					value: 3.9,
					letters:['A']
				},
				'3.70':{
					value: 3.7,
					letters:['A-']
				},
				'3.30':{
					value: 3.3,
					letters:['B+']
				},
				'3.00':{
					value: 3,
					letters:['B']
				},
				'2.70':{
					value: 2.7,
					letters:['B-']
				},
				'2.30':{
					value: 2.3,
					letters:['C+']
				},
				'2.00':{
					value: 2,
					letters:['C']
				},
				'1.70':{
					value: 1.7,
					letters:['C-']
				},
				'1.30':{
					value: 1.3,
					letters:['D+']
				},
				'1.00':{
					value: 1,
					letters:['D']
				},
				'0.70':{
					value: 0.7,
					letters:['D-']
				},
				'0.00':{
					value: 0,
					letters:['E','F']
				}
			},
			customGradeToGPA:false
		}
	};
});<commit_msg>Redid the datastructure for universities<commit_after>angular.module('Universities', [])

.factory('UniversityList', function() {
    return {
        universityofwaterloo: {
            name: 'University Of Waterloo',
            location: {
                city: "Waterloo",
                state: "Ontario",
                country: "Canada"
            },
            commonCreditWeights: [0.25, 0.5, 0.75, 0.80, 1],
            gradeConversions: [{
                    name: "Percentage (eg. 75%)",
                    type: "number",
                    min_range: 0,
                    max_range: 100,
                    gpaConversion: [{
                        value: 4,
                        min: 90,
                        max: 100
                    }, {
                        value: 3.9,
                        min: 85,
                        max: 89
                    }, {
                        value: 3.7,
                        min: 80,
                        max: 84
                    }, {
                        value: 3.3,
                        min: 77,
                        max: 79
                    }, {
                        value: 3,
                        min: 73,
                        max: 76
                    }, {
                        value: 2.7,
                        min: 70,
                        max: 72
                    }, {
                        value: 2.3,
                        min: 67,
                        max: 69
                    }, {
                        value: 2,
                        min: 63,
                        max: 66
                    }, {
                        value: 1.7,
                        min: 60,
                        max: 62
                    }, {
                        value: 1.3,
                        min: 57,
                        max: 59
                    }, {
                        value: 1,
                        min: 53,
                        max: 55
                    }, {
                        value: 0.7,
                        min: 50,
                        max: 52
                    }, {
                        value: 0,
                        min: 0,
                        max: 49
                    }]
                }, {
                    name: "Letter (eg. B, A+)",
                    type: "letter",
                    gpaConversion: [{
                        value: 4,
                        letters: ['A+']
                    }, {
                        value: 3.9,
                        letters: ['A']
                    }, {
                        value: 3.7,
                        letters: ['A-']
                    }, {
                        value: 3.3,
                        letters: ['B+']
                    }, {
                        value: 3,
                        letters: ['B']
                    }, {
                        value: 2.7,
                        letters: ['B-']
                    }, {
                        value: 2.3,
                        letters: ['C+']
                    }, {
                        value: 2,
                        letters: ['C']
                    }, {
                        value: 1.7,
                        letters: ['C-']
                    }, {
                        value: 1.3,
                        letters: ['D+']
                    }, {
                        value: 1,
                        letters: ['D']
                    }, {
                        value: 0.7,
                        letters: ['D-']
                    }, {
                        value: 0,
                        letters: ['E', 'F']
                    }]
                }
            ]
        },
        universityoftoronto: {
            name: 'University Of Toronto',
            location: {
                city: "Toronto",
                state: "Ontario",
                country: "Canada"
            },
            commonCreditWeights: [0.25, 0.5, 0.75, 0.80, 1],
            gradeConversions: [{
                    name: "Percentage (eg. 75%)",
                    type: "number",
                    min_range: 0,
                    max_range: 100,
                    gpaConversion: [{
                        value: 4,
                        min: 90,
                        max: 100
                    }, {
                        value: 3.9,
                        min: 85,
                        max: 89
                    }, {
                        value: 3.7,
                        min: 80,
                        max: 84
                    }, {
                        value: 3.3,
                        min: 77,
                        max: 79
                    }, {
                        value: 3,
                        min: 73,
                        max: 76
                    }, {
                        value: 2.7,
                        min: 70,
                        max: 72
                    }, {
                        value: 2.3,
                        min: 67,
                        max: 69
                    }, {
                        value: 2,
                        min: 63,
                        max: 66
                    }, {
                        value: 1.7,
                        min: 60,
                        max: 62
                    }, {
                        value: 1.3,
                        min: 57,
                        max: 59
                    }, {
                        value: 1,
                        min: 53,
                        max: 55
                    }, {
                        value: 0.7,
                        min: 50,
                        max: 52
                    }, {
                        value: 0,
                        min: 0,
                        max: 49
                    }]
                }, {
                    name: "Letter (eg. B, A+)",
                    type: "letter",
                    gpaConversion: [{
                        value: 4,
                        letters: ['A+']
                    }, {
                        value: 3.9,
                        letters: ['A']
                    }, {
                        value: 3.7,
                        letters: ['A-']
                    }, {
                        value: 3.3,
                        letters: ['B+']
                    }, {
                        value: 3,
                        letters: ['B']
                    }, {
                        value: 2.7,
                        letters: ['B-']
                    }, {
                        value: 2.3,
                        letters: ['C+']
                    }, {
                        value: 2,
                        letters: ['C']
                    }, {
                        value: 1.7,
                        letters: ['C-']
                    }, {
                        value: 1.3,
                        letters: ['D+']
                    }, {
                        value: 1,
                        letters: ['D']
                    }, {
                        value: 0.7,
                        letters: ['D-']
                    }, {
                        value: 0,
                        letters: ['E', 'F']
                    }]
                }
            ]
        }
    };
});<|endoftext|>


<commit_before>/*
 *  autocompleteTrigger (based on jQuery-UI Autocomplete)
 *  https://github.com/experteer/autocompleteTrigger
 *
 * Copyright 2013, Experteer GmbH, Munich
 *
 * @version: 1.4
 * @author Daniel Mattes
 *
 * @requires jQuery 1.6> and jQuery-Ui (including Autocomplete)  1.8>
 * @requires https://github.com/accursoft/caret
 *
 * @description
 * autocompleteTrigger allows you to specify a trigger (e. g. @ like twitter or facebook) and bind it to a textarea or input text field.
 * If a user writes the trigger-sign into the textbox, the autocomplete dialog will displayed and the text after the trigger-sign
 * will be used as search-query for the autocomplete options. If one of the suggested items will be selected, the value and trigger
 * will be added to the textfield.
 *
 * Thanks to https://github.com/kof/fieldSelection (getCursorPosition) and
 * http://stackoverflow.com/questions/4564378/jquery-autocomplete-plugin-that-triggers-after-token
 *
 * Dual licensed under MIT or GPLv2 licenses
 *   http://en.wikipedia.org/wiki/MIT_License
 *   http://en.wikipedia.org/wiki/GNU_General_Public_License
 *
 * @example
 * $('input').autocompleteTrigger({
 *   triggerStart : '@',
 *   triggerEnd: '',
 *   source: [
 "Asp",
 "BASIC",
 "COBOL",
 "ColdFusion",
 "Erlang",
 "Fortran",
 "Groovy",
 "Java",
 "JavaScript",
 "Lisp",
 "Perl",
 "PHP",
 "Python",
 "Ruby",
 "Scala",
 "Scheme"
 ]
 *  });
 */

(function ($, window, document, undefined) {
  $.widget("ui.autocompleteTrigger", {

    //Options to be used as defaults
    options: {
      triggerStart: "%{",
      triggerEnd: "}"
    },

    _create: function () {
      this.triggered = false;

      this.element.autocomplete($.extend({

          search: function () {
            /**
             * @description only make a request and suggest items if acTrigger.triggered is true
             */
            var acTrigger = $(this).data("autocompleteTrigger") || $(this).data("uiAutocompleteTrigger");

            return acTrigger.triggered;
          },
          select: function (event, ui) {
            /**
             * @description if a item is selected, insert the value between triggerStart and triggerEnd
             */
            var acTrigger = $(this).data("autocompleteTrigger") || $(this).data("uiAutocompleteTrigger");
            var trigger = acTrigger.options.triggerStart;
            var cursorPosition = acTrigger.getCursorPosition();

            if ($(this).is('input,textarea')) {
              var text = $(this).val();
              var lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
              var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) +
                ui.item.value +
                acTrigger.options.triggerEnd;
              $(this).val(firstTextPart + text.substring(cursorPosition, text.length));
              acTrigger.setCursorPosition(firstTextPart.length);
            } else {

              var text = $(this).text();
              var html = $(this).html();

              var searchTerm = text.substring(0, cursorPosition);

              var i = 0;
              var index = 0;
              while (i < searchTerm.length) {
                index = html.lastIndexOf(searchTerm.substring(i));
                if (index != -1) {
                  break;
                }
                i++;
              }
//            console.log({html: html, index: index, searchTerm: searchTerm.substring(i) })

              var htmlCursorPosition = index + searchTerm.substring(i).length;
              var htmlLastTriggerPosition = html.substring(0, htmlCursorPosition).lastIndexOf(trigger);
              var htmlFirstTextPart = html.substring(0, htmlLastTriggerPosition + trigger.length) +
                ui.item.value +
                acTrigger.options.triggerEnd;
//            console.log({htmlCursorPosition: htmlCursorPosition, htmlLastTriggerPosition: htmlLastTriggerPosition, htmlFirstTextPart: htmlFirstTextPart })

              // necessary to set cursor position
              var lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
              var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) +
                ui.item.value +
                acTrigger.options.triggerEnd;
//            console.log({lastTriggerPosition: lastTriggerPosition, firstTextPart: firstTextPart, length: firstTextPart.length})

              $(this).html(htmlFirstTextPart + html.substring(htmlCursorPosition, html.length));
              acTrigger.setCursorPosition(firstTextPart.length);
            }

            acTrigger.triggered = false;
            return false;
          },
          focus: function () {
            /**
             * @description prevent to replace the hole text, if a item is hovered
             */

            return false;
          },
          minLength: 0
        }, this.options))

        .bind("keyup", function (event) {
          /**
           * @description Bind to keyup-events to detect text changes.
           * If the trigger is found before the cursor, autocomplete will be called
           */
          var widget = $(this);
          var acTrigger = $(this).data("autocompleteTrigger") || $(this).data("uiAutocompleteTrigger");
          var delay = typeof acTrigger.options.delay === 'undefined' ? 0 : acTrigger.options.delay;

          if (event.keyCode != $.ui.keyCode.UP && event.keyCode != $.ui.keyCode.DOWN) {

            if ($(this).is('input,textarea')) {
              var text = $(this).val();
            } else {
              var text = $(this).text();
            }

            acTrigger.textValue = text;
            if (typeof acTrigger.locked === 'undefined') {
              acTrigger.locked = false;
            }

            if (!acTrigger.locked) {
              acTrigger.locked = true;
              acTrigger.timeout = setTimeout(function () {
                acTrigger.launchAutocomplete(acTrigger, widget);
              }, delay);
            }
          }

        });
    },

    /**
     * @description Destroy an instantiated plugin and clean up modifications the widget has made to the DOM
     */
    destroy: function () {

      // this.element.removeStuff();
      // For UI 1.8, destroy must be invoked from the
      // base widget
      $.Widget.prototype.destroy.call(this);
      // For UI 1.9, define _destroy instead and don't
      // worry about
      // calling the base widget
    },

    /**
     * @description calculates the the current cursor position in the bound textfield, area,...
     * @returns {int}  the position of the cursor.
     */
    getCursorPosition: function () {
      var elem = this.element[0];
      return jQuery(elem).caret();
    },

    /**
     * @description set the position of the cursor in a textfield, area,...
     */
    setCursorPosition: function (position) {
      var elem = this.element[0];
      return jQuery(elem).caret(position);
    },

    launchAutocomplete: function (acTrigger, widget) {
      acTrigger.locked = false;
      var text = acTrigger.textValue;
      var textLength = text.length;
      var cursorPosition = acTrigger.getCursorPosition();
      var lastString;
      var query;
      var lastTriggerPosition;
      var trigger = acTrigger.options.triggerStart;
      var triggerEnd = acTrigger.options.triggerEnd;

      lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
      lastTriggerEndPosition = text.substring(0, cursorPosition).lastIndexOf(triggerEnd);

//      console.log('autocomplete: '+text+", lastTriggerPosition: "+lastTriggerPosition+", lastTriggerEndPosition: "+lastTriggerEndPosition + ", cursorPosition: "+cursorPosition);
      if ((lastTriggerEndPosition < lastTriggerPosition || textLength >= trigger.length) && lastTriggerPosition != -1) {
        query = text.substring(lastTriggerPosition + trigger.length, cursorPosition);
//        console.log('query '+query);
        acTrigger.triggered = true;
        widget.autocomplete("search", query);
      } else {
        acTrigger.triggered = false;
        widget.autocomplete("close");
      }

    }

  });
})(jQuery, window, document);<commit_msg>scripts/autocomplete.js cleanup: remove empty lines at wrong places<commit_after>/*
 *  autocompleteTrigger (based on jQuery-UI Autocomplete)
 *  https://github.com/experteer/autocompleteTrigger
 *
 * Copyright 2013, Experteer GmbH, Munich
 *
 * @version: 1.4
 * @author Daniel Mattes
 *
 * @requires jQuery 1.6> and jQuery-Ui (including Autocomplete)  1.8>
 * @requires https://github.com/accursoft/caret
 *
 * @description
 * autocompleteTrigger allows you to specify a trigger (e. g. @ like twitter or facebook) and bind it to a textarea or input text field.
 * If a user writes the trigger-sign into the textbox, the autocomplete dialog will displayed and the text after the trigger-sign
 * will be used as search-query for the autocomplete options. If one of the suggested items will be selected, the value and trigger
 * will be added to the textfield.
 *
 * Thanks to https://github.com/kof/fieldSelection (getCursorPosition) and
 * http://stackoverflow.com/questions/4564378/jquery-autocomplete-plugin-that-triggers-after-token
 *
 * Dual licensed under MIT or GPLv2 licenses
 *   http://en.wikipedia.org/wiki/MIT_License
 *   http://en.wikipedia.org/wiki/GNU_General_Public_License
 *
 * @example
 * $('input').autocompleteTrigger({
 *   triggerStart : '@',
 *   triggerEnd: '',
 *   source: [
 "Asp",
 "BASIC",
 "COBOL",
 "ColdFusion",
 "Erlang",
 "Fortran",
 "Groovy",
 "Java",
 "JavaScript",
 "Lisp",
 "Perl",
 "PHP",
 "Python",
 "Ruby",
 "Scala",
 "Scheme"
 ]
 *  });
 */

(function ($, window, document, undefined) {
  $.widget("ui.autocompleteTrigger", {

    //Options to be used as defaults
    options: {
      triggerStart: "%{",
      triggerEnd: "}"
    },

    _create: function () {
      this.triggered = false;

      this.element.autocomplete($.extend({

          search: function () {
            /**
             * @description only make a request and suggest items if acTrigger.triggered is true
             */
            var acTrigger = $(this).data("autocompleteTrigger") || $(this).data("uiAutocompleteTrigger");

            return acTrigger.triggered;
          },
          select: function (event, ui) {
            /**
             * @description if a item is selected, insert the value between triggerStart and triggerEnd
             */
            var acTrigger = $(this).data("autocompleteTrigger") || $(this).data("uiAutocompleteTrigger");
            var trigger = acTrigger.options.triggerStart;
            var cursorPosition = acTrigger.getCursorPosition();

            if ($(this).is('input,textarea')) {
              var text = $(this).val();
              var lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
              var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) +
                ui.item.value +
                acTrigger.options.triggerEnd;
              $(this).val(firstTextPart + text.substring(cursorPosition, text.length));
              acTrigger.setCursorPosition(firstTextPart.length);
            } else {
              var text = $(this).text();
              var html = $(this).html();
              var searchTerm = text.substring(0, cursorPosition);
              var i = 0;
              var index = 0;

              while (i < searchTerm.length) {
                index = html.lastIndexOf(searchTerm.substring(i));
                if (index != -1) {
                  break;
                }
                i++;
              }
//            console.log({html: html, index: index, searchTerm: searchTerm.substring(i) })

              var htmlCursorPosition = index + searchTerm.substring(i).length;
              var htmlLastTriggerPosition = html.substring(0, htmlCursorPosition).lastIndexOf(trigger);
              var htmlFirstTextPart = html.substring(0, htmlLastTriggerPosition + trigger.length) +
                ui.item.value +
                acTrigger.options.triggerEnd;
//            console.log({htmlCursorPosition: htmlCursorPosition, htmlLastTriggerPosition: htmlLastTriggerPosition, htmlFirstTextPart: htmlFirstTextPart })

              // necessary to set cursor position
              var lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
              var firstTextPart = text.substring(0, lastTriggerPosition + trigger.length) +
                ui.item.value +
                acTrigger.options.triggerEnd;
//            console.log({lastTriggerPosition: lastTriggerPosition, firstTextPart: firstTextPart, length: firstTextPart.length})

              $(this).html(htmlFirstTextPart + html.substring(htmlCursorPosition, html.length));
              acTrigger.setCursorPosition(firstTextPart.length);
            }

            acTrigger.triggered = false;
            return false;
          },
          focus: function () {
            /**
             * @description prevent to replace the hole text, if a item is hovered
             */

            return false;
          },
          minLength: 0
        }, this.options))

        .bind("keyup", function (event) {
          /**
           * @description Bind to keyup-events to detect text changes.
           * If the trigger is found before the cursor, autocomplete will be called
           */
          var widget = $(this);
          var acTrigger = $(this).data("autocompleteTrigger") || $(this).data("uiAutocompleteTrigger");
          var delay = typeof acTrigger.options.delay === 'undefined' ? 0 : acTrigger.options.delay;

          if (event.keyCode != $.ui.keyCode.UP && event.keyCode != $.ui.keyCode.DOWN) {
            if ($(this).is('input,textarea')) {
              var text = $(this).val();
            } else {
              var text = $(this).text();
            }

            acTrigger.textValue = text;
            if (typeof acTrigger.locked === 'undefined') {
              acTrigger.locked = false;
            }

            if (!acTrigger.locked) {
              acTrigger.locked = true;
              acTrigger.timeout = setTimeout(function () {
                acTrigger.launchAutocomplete(acTrigger, widget);
              }, delay);
            }
          }

        });
    },

    /**
     * @description Destroy an instantiated plugin and clean up modifications the widget has made to the DOM
     */
    destroy: function () {
      // this.element.removeStuff();
      // For UI 1.8, destroy must be invoked from the
      // base widget
      $.Widget.prototype.destroy.call(this);
      // For UI 1.9, define _destroy instead and don't
      // worry about
      // calling the base widget
    },

    /**
     * @description calculates the the current cursor position in the bound textfield, area,...
     * @returns {int}  the position of the cursor.
     */
    getCursorPosition: function () {
      var elem = this.element[0];
      return jQuery(elem).caret();
    },

    /**
     * @description set the position of the cursor in a textfield, area,...
     */
    setCursorPosition: function (position) {
      var elem = this.element[0];
      return jQuery(elem).caret(position);
    },

    launchAutocomplete: function (acTrigger, widget) {
      acTrigger.locked = false;
      var text = acTrigger.textValue;
      var textLength = text.length;
      var cursorPosition = acTrigger.getCursorPosition();
      var lastString;
      var query;
      var lastTriggerPosition;
      var trigger = acTrigger.options.triggerStart;
      var triggerEnd = acTrigger.options.triggerEnd;

      lastTriggerPosition = text.substring(0, cursorPosition).lastIndexOf(trigger);
      lastTriggerEndPosition = text.substring(0, cursorPosition).lastIndexOf(triggerEnd);

//      console.log('autocomplete: '+text+", lastTriggerPosition: "+lastTriggerPosition+", lastTriggerEndPosition: "+lastTriggerEndPosition + ", cursorPosition: "+cursorPosition);
      if ((lastTriggerEndPosition < lastTriggerPosition || textLength >= trigger.length)
          && lastTriggerPosition != -1) {
        query = text.substring(lastTriggerPosition + trigger.length, cursorPosition);
//        console.log('query '+query);
        acTrigger.triggered = true;
        widget.autocomplete("search", query);
      } else {
        acTrigger.triggered = false;
        widget.autocomplete("close");
      }
    }
  });
})(jQuery, window, document);
<|endoftext|>


<commit_before>import React from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { resendVerification } from 'actions/PetitionActions';
import settings from 'settings';
import TrustConfirmation from 'components/TrustConfirmation';

const TrustPublishConfirmationContainer = (props) => (

    <Helmet title={settings.trustConfirmationPage.title} />
    <TrustConfirmation {...props} action={'publish'} />

);

export const mapStateToProps = ({ petition }) => ({
  petition,
  me: petition.owner
});

export const mapDispatchToProps = (dispatch) => ({
  resendVerification: (petition, user) => dispatch(resendVerification({ petition, user }))
});

TrustPublishConfirmationContainer.propTypes = {
  petition: React.PropTypes.object.isRequired,
  me: React.PropTypes.object.isRequired
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TrustPublishConfirmationContainer);
<commit_msg>PropTypes<commit_after>import React from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { resendVerification } from 'actions/PetitionActions';
import settings from 'settings';
import TrustConfirmation from 'components/TrustConfirmation';

const TrustPublishConfirmationContainer = (props) => (

    <Helmet title={settings.trustConfirmationPage.title} />
    <TrustConfirmation {...props} action={'publish'} />

);

export const mapStateToProps = ({ petition }) => ({
  petition,
  me: petition.owner
});

export const mapDispatchToProps = (dispatch) => ({
  resendVerification: (petition, user) => dispatch(resendVerification({ petition, user }))
});

TrustPublishConfirmationContainer.propTypes = {
  petition: React.PropTypes.object.isRequired,
  me: React.PropTypes.oneOfType([
    React.PropTypes.object,
    React.PropTypes.bool
  ]).isRequired
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TrustPublishConfirmationContainer);
<|endoftext|>


<commit_before>
  /**
   *  Date field -> Place to choose and edit date field
   *  - It accepts a model with {attribute: 'colum', value: '2013-02-12T12:19:58+01:00'}
   *  - It will create a new model to split this value into {day, month, year and time}
   *  var date = new cdb.admin.DateField({ model: model })
   */

  cdb.admin.DateField = cdb.admin.StringField.extend({

    className: 'field date',

    timezone: 2,

    default_options: {
      template_name: 'common/views/forms/date_field',
      label:          false,
      readOnly:       false
    },

    events: {
      'change input.time': '_onChange',
      'keyup input.time':  '_onKeyUp'
    },

    initialize: function() {
      _.defaults(this.options, this.default_options);

      _.bindAll(this, '_onChange', '_onKeyUp', '_onChangeModel');

      this.template_base = this.options.template_base ? _.template(this.options.template_base) : cdb.templates.getTemplate(this.options.template_name);

      // Get date
      var date = this._splitDate((this.model.get('value')));

      // Generate a new date Model (later it will be removed and destroyed)
      this.date_model = new cdb.core.Model(date);

      // Begins as valid
      this.valid = true;

      // Bind changes
      this.date_model.bind('change', this._onChangeModel);

      // On clean
      this.bind('clean', this._reClean);
    },

    render: function() {
      this.$el.html(this.template_base(_.extend(this.model.toJSON(), this.options)));

      // Apply views
      this._initViews();

      // Check readOnly and unbind all events
      if (this.options.readOnly) {
        this.undelegateEvents();
      }

      return this;
    },

    _initViews: function() {
      // Days spinner
      var days = this.days = new cdb.forms.Spinner({
        el: this.$el.find('div.day'),
        model:    this.date_model,
        disabled: this.options.readOnly,
        property: 'day',
        min:      1,
        max:      31,
        inc:      1,
        width:    15,
        noSlider: true,
        pattern:  /^([12]?\d{0,1}|3[01]{0,2})$/
      });
      this.addView(this.days);
      this.$("div.day").append(days.render());

      // Year spinner
      var years = this.years = new cdb.forms.Spinner({
        el: this.$el.find('div.year'),
        model:    this.date_model,
        disabled: this.options.readOnly,
        property: 'year',
        min:      1900,
        max:      2100,
        width:    28,
        noSlider: true,
        pattern:  /^([0-9]{0,4})$/
      });
      this.addView(this.years);
      this.$("div.year").append(years.render());

      // Month selector
      var months = this.months = new cdb.forms.Combo({
        el: this.$el.find('div.month'),
        model:      this.date_model,
        disabled:   this.options.readOnly,
        property:   'month',
        width:      '140px',
        extra:      [['January',1], ['February',2], ['March',3], ['April',4], ['May',5], ['June',6], ['July',7], ['August',8], ['September',9], ['October',10], ['November',11], ['December',12]]
      });
      this.addView(this.months);
      this.$("div.month").append(months.render());

      // Time input
      this.$('input.time').val(this.date_model.get('time'));
    },

    /**
     *  Split the date string
     */
    _splitDate: function(str) {
      var date = {};

      if (str=='') {
        date.day = 1;
        date.month = 1;
        date.year = 2012;
        date.time = '00:00:00';
      } else {
        try {
          var split_date_hour = str.split('T');
          if (split_date_hour.length>1) {
            var split_date = split_date_hour[0].split('-');
            date.time = split_date_hour[1].substr(0,8);
            date.day = parseInt(split_date[2]);
            date.month = parseInt(split_date[1]);
            date.year = parseInt(split_date[0]);
          } else {
            date.day = 1;
            date.month = 1;
            date.year = 2012;
            date.time = '00:00:00';
          }
        } catch (e) {
          date.day = 1;
          date.month = 1;
          date.year = 2012;
          date.time = '00:00:00';
        }
      }
      return date;
    },

    /**
     *  Get the date model and converts to date string
     */
    _toDate: function(date) {
      return date.year + "-" + date.month + "-" + date.day + "T" + date.time + "+0" + this.timezone + ":00"
    },

    /**
     *  Check if the time is well formed or not
     */
    _checkTime: function(time) {
      var pattern = /^([01]{1}[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
      if (pattern.test(time)) {
        return true
      } else {
        return false
      }
    },

    // Events
    _onChange: function(e) {
      var time = this.$('input.time').val();

      if (this._checkTime(time)) {
        this.date_model.set('time', time);
      }
    },

    _onChangeModel: function(m) {
      this.model.set('value', this._toDate(this.date_model.toJSON()));
    },

    _onKeyDown: function() {},

    _onKeyUp: function(e) {
      var time = $(e.target).val();

      if (this._checkTime(time)) {

        if (e.keyCode === 13) {
          e.preventDefault();
          this._triggerEvent('ENTER');
          return false;
        }

        this.valid = true;
        this.date_model.set('time', time);
        $(e.target).removeClass("error");
      } else {
        this.valid = false;
        $(e.target).addClass("error");
      }
    },

    _reClean: function() {
      this.date_model.unbind('change');
      this.date_model.destroy();
    }
  })<commit_msg>date field save by default a date<commit_after>
  /**
   *  Date field -> Place to choose and edit date field
   *  - It accepts a model with {attribute: 'colum', value: '2013-02-12T12:19:58+01:00'}
   *  - It will create a new model to split this value into {day, month, year and time}
   *  var date = new cdb.admin.DateField({ model: model })
   */

  cdb.admin.DateField = cdb.admin.StringField.extend({

    className: 'field date',

    timezone: 2,

    default_options: {
      template_name: 'common/views/forms/date_field',
      label:          false,
      readOnly:       false
    },

    events: {
      'change input.time': '_onChange',
      'keyup input.time':  '_onKeyUp'
    },

    initialize: function() {
      _.defaults(this.options, this.default_options);

      _.bindAll(this, '_onChange', '_onKeyUp', '_onChangeModel');

      this.template_base = this.options.template_base ? _.template(this.options.template_base) : cdb.templates.getTemplate(this.options.template_name);

      // Get date
      var date = this._splitDate((this.model.get('value')));

      // Generate a new date Model (later it will be removed and destroyed)
      this.date_model = new cdb.core.Model();

      // Begins as valid
      this.valid = true;

      // Bind changes
      this.date_model.bind('change', this._onChangeModel);

      // Date model data set
      this.date_model.set(date);

      // On clean
      this.bind('clean', this._reClean);
    },

    render: function() {
      this.$el.html(this.template_base(_.extend(this.model.toJSON(), this.options)));

      // Apply views
      this._initViews();

      // Check readOnly and unbind all events
      if (this.options.readOnly) {
        this.undelegateEvents();
      }

      return this;
    },

    _initViews: function() {
      // Days spinner
      var days = this.days = new cdb.forms.Spinner({
        el: this.$el.find('div.day'),
        model:    this.date_model,
        disabled: this.options.readOnly,
        property: 'day',
        min:      1,
        max:      31,
        inc:      1,
        width:    15,
        noSlider: true,
        pattern:  /^([12]?\d{0,1}|3[01]{0,2})$/
      });
      this.addView(this.days);
      this.$("div.day").append(days.render());

      // Year spinner
      var years = this.years = new cdb.forms.Spinner({
        el: this.$el.find('div.year'),
        model:    this.date_model,
        disabled: this.options.readOnly,
        property: 'year',
        min:      1900,
        max:      2100,
        width:    28,
        noSlider: true,
        pattern:  /^([0-9]{0,4})$/
      });
      this.addView(this.years);
      this.$("div.year").append(years.render());

      // Month selector
      var months = this.months = new cdb.forms.Combo({
        el: this.$el.find('div.month'),
        model:      this.date_model,
        disabled:   this.options.readOnly,
        property:   'month',
        width:      '140px',
        extra:      [['January',1], ['February',2], ['March',3], ['April',4], ['May',5], ['June',6], ['July',7], ['August',8], ['September',9], ['October',10], ['November',11], ['December',12]]
      });
      this.addView(this.months);
      this.$("div.month").append(months.render());

      // Time input
      this.$('input.time').val(this.date_model.get('time'));
    },

    /**
     *  Split the date string
     */
    _splitDate: function(str) {
      var date = {};

      if (str=='') {
        date.day = 1;
        date.month = 1;
        date.year = 2012;
        date.time = '00:00:00';
      } else {
        try {
          var split_date_hour = str.split('T');
          if (split_date_hour.length>1) {
            var split_date = split_date_hour[0].split('-');
            date.time = split_date_hour[1].substr(0,8);
            date.day = parseInt(split_date[2]);
            date.month = parseInt(split_date[1]);
            date.year = parseInt(split_date[0]);
          } else {
            date.day = 1;
            date.month = 1;
            date.year = 2012;
            date.time = '00:00:00';
          }
        } catch (e) {
          date.day = 1;
          date.month = 1;
          date.year = 2012;
          date.time = '00:00:00';
        }
      }
      return date;
    },

    /**
     *  Get the date model and converts to date string
     */
    _toDate: function(date) {
      return date.year + "-" + date.month + "-" + date.day + "T" + date.time + "+0" + this.timezone + ":00"
    },

    /**
     *  Check if the time is well formed or not
     */
    _checkTime: function(time) {
      var pattern = /^([01]{1}[0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/;
      if (pattern.test(time)) {
        return true
      } else {
        return false
      }
    },

    // Events
    _onChange: function(e) {
      var time = this.$('input.time').val();

      if (this._checkTime(time)) {
        this.date_model.set('time', time);
      }
    },

    _onChangeModel: function(m) {
      this.model.set('value', this._toDate(this.date_model.toJSON()));
    },

    _onKeyDown: function() {},

    _onKeyUp: function(e) {
      var time = $(e.target).val();

      if (this._checkTime(time)) {

        if (e.keyCode === 13) {
          e.preventDefault();
          this._triggerEvent('ENTER');
          return false;
        }

        this.valid = true;
        this.date_model.set('time', time);
        $(e.target).removeClass("error");
      } else {
        this.valid = false;
        $(e.target).addClass("error");
      }
    },

    _reClean: function() {
      this.date_model.unbind('change');
      this.date_model.destroy();
    }
  })<|endoftext|>


<commit_before>/*
  kinematics.js --
  This file defines the primary kinematics modules utilizing the keyframe system.
*/

function Kinematics1DModule() {

function initWorld() {
    return Physics(function (world) {
      var canvasId = "viewport";
      var canvasEl = document.getElementById(canvasId);
      var viewportBounds = Physics.aabb(0, 0, canvasEl.clientWidth, canvasEl.clientHeight);// bounds of the window
      var edgeBounce;
      var renderer;
      var integrator;
      world.timestep(0.1); // TODO: should base timestep on dt option

      // create a renderer
      renderer = Physics.renderer('canvas', {el: canvasId});

      // add the renderer
      world.add(renderer);

      // add our custom integrator
      integrator = Physics.integrator('principia-integrator', {});
      world.add(integrator);

      world.on('addComponent', function(data) {

        var variableMap = Globals.variableMap;
        var bodyConstants = Globals.bodyConstants;

        bodyConstants.push({ctype:data.type});

        switch(data.type){
          case "kinematics1D-spring":
            bodyConstants.push({ctype:data.type + "-child"});
            addSpring(data);
            break;
          case "kinematics1D-mass":
            addMass(data);
            break;
          case "kinematics1D-ramp":
            addRamp(data);
            break
          case "kinematics1D-pulley":
            addPulley(data);
            break;
        }

        drawMaster();
      });

      // constrain objects to these bounds
      edgeBounce = Physics.behavior('edge-collision-detection', {
        aabb: viewportBounds,
        restitution: 0.99,
        cof: 0.8
      });

      // resize events
      window.addEventListener('resize', function () {
        // as of 0.7.0 the renderer will auto resize... so we just take the values from the renderer
        viewportBounds = Physics.aabb(0, 0, renderer.width, renderer.height);
        edgeBounce.setAABB(viewportBounds); // update the boundaries
        drawMaster();
      }, true);

      // Note: PhysicsJS zeroes out velocity (ln 8445) - commented out for our simulator
      world.on('interact:grab', function( data ){
        if(data.body){
          selectBody(bIndex(data.body), true);
        }
      });

  world.on('interact:move', function( data ){
    if(data.body) {

      if(bIndex(data.body) === Globals.originObject)
      {
        Globals.origin = [data.x, data.y];
        $("#glob-xorigin").val(data.x) ;
        $("#glob-yorigin").val(data.y) ;
      }

      Globals.didMove = true;
      onPropertyChanged("posx", data.x);
      onPropertyChanged("posy", data.y);
      drawMaster();
    }
  });

  world.on('interact:release', function( data ){
    // Note that PhysicsJS adds to velocity vector upon release - commented out for our simulator
    if(data.body && Globals.didMove){

        // Make move as complete
        Globals.didMove = false;

        // Resimulate if there is only one keyframe
        onPropertyChanged("posx", data.x);
        onPropertyChanged("posy", data.y);

        if(Globals.bodyConstants[bIndex(data.body)].ctype == "kinematics1D-mass")
        {
          attachSpring(data.body);
          detachSpring(data.body);
          attachPulley(data.body);
        }

        drawMaster();
    }
  });

  world.on('interact:poke', function( data ){
    Globals.selectedBody = false;
    document.getElementById("toolbox-tab").click();
    drawMaster();
  });

  // add things to the world
  world.add([
    Physics.behavior('interactive', {el: renderer.container}),
    Physics.behavior('body-impulse-response'),
    Physics.behavior('body-collision-detection'),
    Physics.behavior('sweep-prune'),
    edgeBounce
    ]);
  });
} // end initWorld

  function initModule(json) {
    Globals.world = initWorld();

    // How the solver object works:
    // Try to assign a value to each key using known variables
    // Repeat until no new values can be assigned
    // Note that an overconstrained problem could still be solved with this method, leading to unsound results
    Globals.solver = new Solver(
    {
      xf:
      {
        name:'$x_f$',
        eq:['x0 + vx0*t + 0.5*ax*t^2'],
        pretty:[' using the kinematic equation $x_f = x_0 + {v_x}_0*t + 1/2*a_x*t^2$ '],
        vars:[['x0','vx0','ax','t']],
        prettyvars:[['$x_0$', '${v_x}_0$', '$a_x$', '$t$']]
      },

      yf:
      {
        name:'$y_f$',
        eq:['y0 + vy0*t + 0.5*ay*t^2'],
        pretty:[' using the kinematic equation y_f = y_0 + v_y*t + 1/2*a_y*t^2 '],
        vars:[['y0','vy0','ay','t']],
        prettyvars:[['$y_0$', '${v_y}_0$', '$a_y$', '$t$']]
      },

      vxf:
      {
        name:'${v_x}_f$',
        eq:['vx0 + ax*t'],
        pretty:[' using the kinematic equation ${v_x}_f = v_x + a_x*t$ '],
        vars:[['vx0','ax','t']],
        prettyvars:[['${v_x}_0$','$a_x$','$t$']]
      },

      vyf:
      {
        name:'${v_y}_f$',
        eq:['vy0 + ay*t'],
        pretty:[' using the kinematic equation ${v_y}_f = v_y + a_y*t$ '],
        vars:[['vy0','ay','t']],
        prettyvars:[['${v_y}_0$','$a_y$','$t$']]
      },

      vx0:
      {
        name:'${v_x}_0$',
        eq:['vxf-ax*t'],
        pretty:[' rearranging the kinematic equation {v_x}_f = v_x + a*t'],
        vars:[['vxf','ax','t']],
        prettyvars:[['${v_x}_f$','$a_x$','$t$']]
      },

      vy0:
      {
        name:'${v_y}_0$',
        eq:['vyf-ay*t'],
        pretty:[' rearranging the kinematic equation ${v_y}_f = v_y + a_y*t$'],
        vars:[['vyf','ay','t']],
        prettyvars:[['${v_y}_f$','$a_y$','$t$']]
      },

      x0:
      {
        name:'$x_0$',
        eq:['xf-vx0*t-0.5*ax*t^2'],
        pretty:[' rearranging the kinematic equation $x_f = x + v_x*t + 1/2 a_x*t^2$ '],
        vars:[['xf','vx0','t','ax']],
        prettyvars:[['$x_f$','${v_x}_0$','$t$','$a_x$']]
      },

      y0:
      {
        name:'${y_0}_f$',
        eq:['yf-vy0*t-0.5*ay*t^2'],
        pretty:[' rearranging the kinematic equation $y_f = y + v_y*t + 1/2 a_y*t^2$ '],
        vars:[['yf','vy0','t','ay']],
        prettyvars:[['$y_f$','${v_y}_0$','$t$','$a_y$']]
      },

      t:
      {
        name:'$t$',
        eq:['(vxf-vx0)/ax', '(vyf-vy0)/ay', '(sqrt(2*yf*ay - 2*y0*ay + vy0^2) - vy0)/ay'],
        pretty:[' rearranging the kinematic equation ${v_x}_f = {v_x}_0 + a_x*t$ ', ' rearranging the kinematic equation ${v_y}_f = {v_y}_0 + a_y*t$ ', ' using the kinematic equation $y_f - y_0 = v_0*t + 1/2 a t^2$  '],
        vars:[['vxf','vx0','ax'],['vyf','vy0','ay'],['yf','ay','y0','vy0']],
        prettyvars:[['${v_x}_f$','${v_x}_0$','$a_x$'],['${v_y}_f$','${v_y}_0$','$a_y$'],['yf','ay','y0','vy0']]
      },

      ax:
      {
        name:'$a_x$',
        eq:['(vxf-vx0)/t'],
        pretty:[' rearranging the kinematic equation ${v_x}_f = v_x + a_x*t$ '],
        vars:[['vxf','vx0','t']],
        vars:[['${v_x}_f$','${v_x}_0$','$t$']]
      },

      ay:
      {
        name:'$a_y$',
        eq:['(vyf-vy0)/t'],
        pretty:[' rearranging the kinematic equation ${v_y}_f = v_y + a_y*t$ '],
        vars:[['vyf','vy0','t']],
        prettyvars:[['${v_y}_f$','${v_y}_0$','$t$']]
      }
    });

     if(!json || json == "{}")
      return;

    var restore = $.parseJSON(json);
    for(var key in restore)
    {
      if(key == "keyframeStates") continue;
      if(key == "bodyConstants") continue;
      Globals[key] = restore[key];
    }

    // Stringified keyframes don't interact well with PhysicsJS
    // Solution: Add the real component to get PhysicsJS state object
    // Then transfer tempKF values to real corresponding "real" keyframe
    var tempKF = restore.keyframeStates;
    var tempBC = restore.bodyConstants;

    for(var i=0; i<tempBC.length; i++)
    {
      var type = tempBC[i].ctype;
      var x = tempKF[0][i].pos._[0];
      var y = tempKF[0][i].pos._[1];
      var data = { 'type': type, 'x': x, 'y': y, 'blockSimulation':true};
      if(type != "kinematics1D-spring-child")
        Globals.world.emit('addComponent', data);
      Globals.bodyConstants[i] = tempBC[i];

      Globals.selectedBody = Globals.world.getBodies()[Globals.world.getBodies().length-1];
      if (type == "kinematics1D-mass" || type == "kinematics1D-pulley") {
        onPropertyChanged("image", tempBC[i].img, false);
        onPropertyChanged("size", tempBC[i].size, false);
      } else if (type == "kinematics1D-ramp") {
        onPropertyChanged("width", tempBC[i].width, false);
        onPropertyChanged("height", tempBC[i].height, false);
      }
      Globals.selectedBody = false;
    }

    for(var i=0; i<tempKF.length; i++)
      for(var j=0; j<tempKF[i].length; j++)
      {
        var KF = tempKF[i][j];
        Globals.keyframeStates[i][j].pos.x = KF.pos._[0];
        Globals.keyframeStates[i][j].pos.y = KF.pos._[1];
        Globals.keyframeStates[i][j].vel.x = KF.vel._[0];
        Globals.keyframeStates[i][j].vel.y = KF.vel._[1];
        Globals.keyframeStates[i][j].acc.x = KF.acc._[0];
        Globals.keyframeStates[i][j].acc.y = KF.acc._[1];
        var angular = KF.angular;
        Globals.keyframeStates[i][j].angular = {acc:angular.acc,vel:angular.vel,pos:angular.pos};
      }

    setStateKF(0);

    if(Globals.timelineReady)
      simulate();

    drawMaster();
  }

  function setDt(dt) { Globals.world.timestep(dt); }

  return {
    initWorld:  initWorld,
    initModule: initModule,
    setDt:    setDt
  };
}

var Kinematics1D = Kinematics1DModule();
<commit_msg>updated timestep to be a little faster. 0.1 made everything move really slow<commit_after>/*
  kinematics.js --
  This file defines the primary kinematics modules utilizing the keyframe system.
*/

function Kinematics1DModule() {

function initWorld() {
    return Physics(function (world) {
      var canvasId = "viewport";
      var canvasEl = document.getElementById(canvasId);
      var viewportBounds = Physics.aabb(0, 0, canvasEl.clientWidth, canvasEl.clientHeight);// bounds of the window
      var edgeBounce;
      var renderer;
      var integrator;
      world.timestep(0.5); // TODO: should base timestep on dt option

      // create a renderer
      renderer = Physics.renderer('canvas', {el: canvasId});

      // add the renderer
      world.add(renderer);

      // add our custom integrator
      integrator = Physics.integrator('principia-integrator', {});
      world.add(integrator);

      world.on('addComponent', function(data) {

        var variableMap = Globals.variableMap;
        var bodyConstants = Globals.bodyConstants;

        bodyConstants.push({ctype:data.type});

        switch(data.type){
          case "kinematics1D-spring":
            bodyConstants.push({ctype:data.type + "-child"});
            addSpring(data);
            break;
          case "kinematics1D-mass":
            addMass(data);
            break;
          case "kinematics1D-ramp":
            addRamp(data);
            break
          case "kinematics1D-pulley":
            addPulley(data);
            break;
        }

        drawMaster();
      });

      // constrain objects to these bounds
      edgeBounce = Physics.behavior('edge-collision-detection', {
        aabb: viewportBounds,
        restitution: 0.99,
        cof: 0.8
      });

      // resize events
      window.addEventListener('resize', function () {
        // as of 0.7.0 the renderer will auto resize... so we just take the values from the renderer
        viewportBounds = Physics.aabb(0, 0, renderer.width, renderer.height);
        edgeBounce.setAABB(viewportBounds); // update the boundaries
        drawMaster();
      }, true);

      // Note: PhysicsJS zeroes out velocity (ln 8445) - commented out for our simulator
      world.on('interact:grab', function( data ){
        if(data.body){
          selectBody(bIndex(data.body), true);
        }
      });

  world.on('interact:move', function( data ){
    if(data.body) {

      if(bIndex(data.body) === Globals.originObject)
      {
        Globals.origin = [data.x, data.y];
        $("#glob-xorigin").val(data.x) ;
        $("#glob-yorigin").val(data.y) ;
      }

      Globals.didMove = true;
      onPropertyChanged("posx", data.x);
      onPropertyChanged("posy", data.y);
      drawMaster();
    }
  });

  world.on('interact:release', function( data ){
    // Note that PhysicsJS adds to velocity vector upon release - commented out for our simulator
    if(data.body && Globals.didMove){

        // Make move as complete
        Globals.didMove = false;

        // Resimulate if there is only one keyframe
        onPropertyChanged("posx", data.x);
        onPropertyChanged("posy", data.y);

        if(Globals.bodyConstants[bIndex(data.body)].ctype == "kinematics1D-mass")
        {
          attachSpring(data.body);
          detachSpring(data.body);
          attachPulley(data.body);
        }

        drawMaster();
    }
  });

  world.on('interact:poke', function( data ){
    Globals.selectedBody = false;
    document.getElementById("toolbox-tab").click();
    drawMaster();
  });

  // add things to the world
  world.add([
    Physics.behavior('interactive', {el: renderer.container}),
    Physics.behavior('body-impulse-response'),
    Physics.behavior('body-collision-detection'),
    Physics.behavior('sweep-prune'),
    edgeBounce
    ]);
  });
} // end initWorld

  function initModule(json) {
    Globals.world = initWorld();

    // How the solver object works:
    // Try to assign a value to each key using known variables
    // Repeat until no new values can be assigned
    // Note that an overconstrained problem could still be solved with this method, leading to unsound results
    Globals.solver = new Solver(
    {
      xf:
      {
        name:'$x_f$',
        eq:['x0 + vx0*t + 0.5*ax*t^2'],
        pretty:[' using the kinematic equation $x_f = x_0 + {v_x}_0*t + 1/2*a_x*t^2$ '],
        vars:[['x0','vx0','ax','t']],
        prettyvars:[['$x_0$', '${v_x}_0$', '$a_x$', '$t$']]
      },

      yf:
      {
        name:'$y_f$',
        eq:['y0 + vy0*t + 0.5*ay*t^2'],
        pretty:[' using the kinematic equation y_f = y_0 + v_y*t + 1/2*a_y*t^2 '],
        vars:[['y0','vy0','ay','t']],
        prettyvars:[['$y_0$', '${v_y}_0$', '$a_y$', '$t$']]
      },

      vxf:
      {
        name:'${v_x}_f$',
        eq:['vx0 + ax*t'],
        pretty:[' using the kinematic equation ${v_x}_f = v_x + a_x*t$ '],
        vars:[['vx0','ax','t']],
        prettyvars:[['${v_x}_0$','$a_x$','$t$']]
      },

      vyf:
      {
        name:'${v_y}_f$',
        eq:['vy0 + ay*t'],
        pretty:[' using the kinematic equation ${v_y}_f = v_y + a_y*t$ '],
        vars:[['vy0','ay','t']],
        prettyvars:[['${v_y}_0$','$a_y$','$t$']]
      },

      vx0:
      {
        name:'${v_x}_0$',
        eq:['vxf-ax*t'],
        pretty:[' rearranging the kinematic equation {v_x}_f = v_x + a*t'],
        vars:[['vxf','ax','t']],
        prettyvars:[['${v_x}_f$','$a_x$','$t$']]
      },

      vy0:
      {
        name:'${v_y}_0$',
        eq:['vyf-ay*t'],
        pretty:[' rearranging the kinematic equation ${v_y}_f = v_y + a_y*t$'],
        vars:[['vyf','ay','t']],
        prettyvars:[['${v_y}_f$','$a_y$','$t$']]
      },

      x0:
      {
        name:'$x_0$',
        eq:['xf-vx0*t-0.5*ax*t^2'],
        pretty:[' rearranging the kinematic equation $x_f = x + v_x*t + 1/2 a_x*t^2$ '],
        vars:[['xf','vx0','t','ax']],
        prettyvars:[['$x_f$','${v_x}_0$','$t$','$a_x$']]
      },

      y0:
      {
        name:'${y_0}_f$',
        eq:['yf-vy0*t-0.5*ay*t^2'],
        pretty:[' rearranging the kinematic equation $y_f = y + v_y*t + 1/2 a_y*t^2$ '],
        vars:[['yf','vy0','t','ay']],
        prettyvars:[['$y_f$','${v_y}_0$','$t$','$a_y$']]
      },

      t:
      {
        name:'$t$',
        eq:['(vxf-vx0)/ax', '(vyf-vy0)/ay', '(sqrt(2*yf*ay - 2*y0*ay + vy0^2) - vy0)/ay'],
        pretty:[' rearranging the kinematic equation ${v_x}_f = {v_x}_0 + a_x*t$ ', ' rearranging the kinematic equation ${v_y}_f = {v_y}_0 + a_y*t$ ', ' using the kinematic equation $y_f - y_0 = v_0*t + 1/2 a t^2$  '],
        vars:[['vxf','vx0','ax'],['vyf','vy0','ay'],['yf','ay','y0','vy0']],
        prettyvars:[['${v_x}_f$','${v_x}_0$','$a_x$'],['${v_y}_f$','${v_y}_0$','$a_y$'],['yf','ay','y0','vy0']]
      },

      ax:
      {
        name:'$a_x$',
        eq:['(vxf-vx0)/t'],
        pretty:[' rearranging the kinematic equation ${v_x}_f = v_x + a_x*t$ '],
        vars:[['vxf','vx0','t']],
        vars:[['${v_x}_f$','${v_x}_0$','$t$']]
      },

      ay:
      {
        name:'$a_y$',
        eq:['(vyf-vy0)/t'],
        pretty:[' rearranging the kinematic equation ${v_y}_f = v_y + a_y*t$ '],
        vars:[['vyf','vy0','t']],
        prettyvars:[['${v_y}_f$','${v_y}_0$','$t$']]
      }
    });

     if(!json || json == "{}")
      return;

    var restore = $.parseJSON(json);
    for(var key in restore)
    {
      if(key == "keyframeStates") continue;
      if(key == "bodyConstants") continue;
      Globals[key] = restore[key];
    }

    // Stringified keyframes don't interact well with PhysicsJS
    // Solution: Add the real component to get PhysicsJS state object
    // Then transfer tempKF values to real corresponding "real" keyframe
    var tempKF = restore.keyframeStates;
    var tempBC = restore.bodyConstants;

    for(var i=0; i<tempBC.length; i++)
    {
      var type = tempBC[i].ctype;
      var x = tempKF[0][i].pos._[0];
      var y = tempKF[0][i].pos._[1];
      var data = { 'type': type, 'x': x, 'y': y, 'blockSimulation':true};
      if(type != "kinematics1D-spring-child")
        Globals.world.emit('addComponent', data);
      Globals.bodyConstants[i] = tempBC[i];

      Globals.selectedBody = Globals.world.getBodies()[Globals.world.getBodies().length-1];
      if (type == "kinematics1D-mass" || type == "kinematics1D-pulley") {
        onPropertyChanged("image", tempBC[i].img, false);
        onPropertyChanged("size", tempBC[i].size, false);
      } else if (type == "kinematics1D-ramp") {
        onPropertyChanged("width", tempBC[i].width, false);
        onPropertyChanged("height", tempBC[i].height, false);
      }
      Globals.selectedBody = false;
    }

    for(var i=0; i<tempKF.length; i++)
      for(var j=0; j<tempKF[i].length; j++)
      {
        var KF = tempKF[i][j];
        Globals.keyframeStates[i][j].pos.x = KF.pos._[0];
        Globals.keyframeStates[i][j].pos.y = KF.pos._[1];
        Globals.keyframeStates[i][j].vel.x = KF.vel._[0];
        Globals.keyframeStates[i][j].vel.y = KF.vel._[1];
        Globals.keyframeStates[i][j].acc.x = KF.acc._[0];
        Globals.keyframeStates[i][j].acc.y = KF.acc._[1];
        var angular = KF.angular;
        Globals.keyframeStates[i][j].angular = {acc:angular.acc,vel:angular.vel,pos:angular.pos};
      }

    setStateKF(0);

    if(Globals.timelineReady)
      simulate();

    drawMaster();
  }

  function setDt(dt) { Globals.world.timestep(dt); }

  return {
    initWorld:  initWorld,
    initModule: initModule,
    setDt:    setDt
  };
}

var Kinematics1D = Kinematics1DModule();
<|endoftext|>


<commit_before>jQuery.Controller.extend('MedAdherence.Controllers.MainController',
/* @Static */
{
	onDocument : true
},
/* @Prototype */
{
	"{window} load" : function() {
	    var _this = this;

	    SMART.ready(function() {
		_this.pending_timers = [];

		Smart.Models.Med.get(function(r) {
		    _this.meds = r.graph;
		    Smart.Models.Med.findDispenseEvents();
		    _this.initialize_ui();
		});
	    });
	},

	initialize_ui : function() {
		var meds = this.meds;

		// find chronic meds only
		var ds = Smart.Models.Med.dispenses_by_med;
		var chronics = $.grep(meds, function(x) {
			var n = x.nodename;
			return (ds[n] && ds[n].length > 1);
		});

		$("#chronic-ul").hide().html(this.view("chronics", {
			chronics : chronics
		})).show("slide", {
			direction : "right"
		}, 150);

	},

	".restore_chronics click" : function(el) {
		$("#chronic-ul").show();
		$("#adherence-view").html("");
	},
	".chronic_med click" : function(el) {

		$('#explanation').show();
		$(".selected").removeClass("selected");
		el.addClass("selected");
		var m = el.model();
		this.view_one_med(m);
	},
	addTimer : function(f, delay) {
		var t = setTimeout(f, delay);
		this.pending_timers.push(t);
	},
	clearTimers : function() {
		for ( var i = 0; i < this.pending_timers.length; i++) {
			window.clearTimeout(this.pending_timers[i]);
		}
		this.pending_timers = [];

	},

	view_one_med : function(m) {
		var a = $("#adherence-view");
		a.html("");
		this.clearTimers();

		var canvas = $("<canvas class='adherence_canvas' id='adherence_canvas_"
				+ m.nodename + "'></canvas>");

		var fills = Smart.Models.Med.dispenses_by_med[m.nodename];
		var blocks = this.calculate_blocks(fills);

		var d1 = fills[0].start.toString("MMM yyyy");
		var d2 = fills[fills.length - 1].start.toString("MMM yyyy");
		var lval = blocks.mprs[0];
		lval = Math.round(lval * 100) + "%";
		var rval = blocks.mprs[blocks.mprs.length - 1];
		rval = Math.round(rval * 100) + "%";

		var dates = $("
" + d1 + "
"
				+ lval + "" + d2 + "
" + rval
				+ "");
		var summary = $("

");
		a.append(canvas);

		this.draw_blocks(blocks, canvas);

		var v = parseInt(rval);
		if (v >= 80)
			v = "Good";
		else if (v >= 50)
			v = "Fair";
		else
			v = "Poor";
		var medname = m.properName().split(" ")[0];
		summary.html(medname + " Adherence:  " + v + "");
		a.append(dates);
		a.append(summary);

		$("#chronic-ul").hide();
		$("#adherence-view").append(
				$("<button class='restore_chronics'>Back to list</button>"));
		window.scrollTo(0, 0);
	},

	draw_blocks : function(blocks, canvas) {
		var height = 80;
		var width = 800;
		var ppd = pixels_per_day = width
				/ blocks.goods[blocks.goods.length - 1].start * 1.0;

		var reserve = 0;
		canvas.attr("width", width);
		canvas.attr("height", height);

		var avd = canvas.parent();
		var xdelta = blocks.starts[blocks.starts.length - 2];

		canvas = canvas[canvas.length - 1];

		if (canvas.getContext) {
			var ctx = canvas.getContext("2d");

			ctx.fillStyle = "rgba(0, 200, 0, 0.4)";
			for ( var i = 0; i < blocks.goods.length - 1; i++) {
				var g = blocks.goods[i];

				var m2 = Math.min(blocks.mprs[i + 1]);
				var bar_top = height * (1 - m2 * (1 - reserve));
				var bar_height = height - bar_top;

				ctx.fillRect(g.start * ppd, bar_top, g.duration * ppd,
						bar_height);
			}

			ctx.strokeStyle = 'rgba(0,0,0,1)';
			ctx.lineWidth = 1;
			ctx.beginPath();
			var x = blocks.starts[blocks.starts.length - 1];
			ctx.moveTo(0, height);
			ctx.lineTo(x * ppd, height);
			ctx.stroke();

		}
		canvas = $(canvas);
		canvas.show();// "slide", {direction: "left"}, 300);

	},

	calculate_blocks : function(fills) {

		var goods = [];
		var mprs = [];
		var starts = [];

		var t_0 = fills[0].start.getTime();
		var l = fills.length;

		var pills_on_hand = 0;
		var total_pills_received = 0;

		for ( var i = 0; i < l; i++) {
			var f = fills[i];
			var q = parseInt(f.quantity);

			var start = Math.floor((f.start.getTime() - t_0) / 86400000.0);
			starts.push(start);

			if (start > 0) {
				mprs.push(1.0 * total_pills_received / start);

				var elapsed = start - goods[i - 1].start;
				pills_on_hand -= elapsed;
				pills_on_hand = Math.max(0, pills_on_hand)
			}
			else {
				mprs.push(null);
			}

			pills_on_hand += q;
			total_pills_received += q;

			var g = {
				start : start,
				duration : pills_on_hand
			};
			goods.push(g);

		}
		for (var i = mprs.length-2; i>=0; i--)
			if (mprs[i] == null) mprs[i] = mprs[i+1];

		return {
			starts : starts,
			goods : goods,
			mprs : mprs
		};

	}

});<commit_msg>Fix for med_adherence<commit_after>jQuery.Controller.extend('MedAdherence.Controllers.MainController',
/* @Static */
{
	onDocument : true
},
/* @Prototype */
{
	"{window} load" : function() {
	    var _this = this;

	    SMART.ready(function() {
		_this.pending_timers = [];

		Smart.Models.Med.get(function(data) {
		    _this.meds = data;
		    Smart.Models.Med.findDispenseEvents();
		    _this.initialize_ui();
		});
	    });
	},

	initialize_ui : function() {
		var meds = this.meds;

		// find chronic meds only
		var ds = Smart.Models.Med.dispenses_by_med;
		var chronics = $.grep(meds, function(x) {
			var n = x.nodename;
			return (ds[n] && ds[n].length > 1);
		});

		$("#chronic-ul").hide().html(this.view("chronics", {
			chronics : chronics
		})).show("slide", {
			direction : "right"
		}, 150);

	},

	".restore_chronics click" : function(el) {
		$("#chronic-ul").show();
		$("#adherence-view").html("");
	},
	".chronic_med click" : function(el) {

		$('#explanation').show();
		$(".selected").removeClass("selected");
		el.addClass("selected");
		var m = el.model();
		this.view_one_med(m);
	},
	addTimer : function(f, delay) {
		var t = setTimeout(f, delay);
		this.pending_timers.push(t);
	},
	clearTimers : function() {
		for ( var i = 0; i < this.pending_timers.length; i++) {
			window.clearTimeout(this.pending_timers[i]);
		}
		this.pending_timers = [];

	},

	view_one_med : function(m) {
		var a = $("#adherence-view");
		a.html("");
		this.clearTimers();

		var canvas = $("<canvas class='adherence_canvas' id='adherence_canvas_"
				+ m.nodename + "'></canvas>");

		var fills = Smart.Models.Med.dispenses_by_med[m.nodename];
		var blocks = this.calculate_blocks(fills);

		var d1 = fills[0].start.toString("MMM yyyy");
		var d2 = fills[fills.length - 1].start.toString("MMM yyyy");
		var lval = blocks.mprs[0];
		lval = Math.round(lval * 100) + "%";
		var rval = blocks.mprs[blocks.mprs.length - 1];
		rval = Math.round(rval * 100) + "%";

		var dates = $("
" + d1 + "
"
				+ lval + "" + d2 + "
" + rval
				+ "");
		var summary = $("

");
		a.append(canvas);

		this.draw_blocks(blocks, canvas);

		var v = parseInt(rval);
		if (v >= 80)
			v = "Good";
		else if (v >= 50)
			v = "Fair";
		else
			v = "Poor";
		var medname = m.properName().split(" ")[0];
		summary.html(medname + " Adherence:  " + v + "");
		a.append(dates);
		a.append(summary);

		$("#chronic-ul").hide();
		$("#adherence-view").append(
				$("<button class='restore_chronics'>Back to list</button>"));
		window.scrollTo(0, 0);
	},

	draw_blocks : function(blocks, canvas) {
		var height = 80;
		var width = 800;
		var ppd = pixels_per_day = width
				/ blocks.goods[blocks.goods.length - 1].start * 1.0;

		var reserve = 0;
		canvas.attr("width", width);
		canvas.attr("height", height);

		var avd = canvas.parent();
		var xdelta = blocks.starts[blocks.starts.length - 2];

		canvas = canvas[canvas.length - 1];

		if (canvas.getContext) {
			var ctx = canvas.getContext("2d");

			ctx.fillStyle = "rgba(0, 200, 0, 0.4)";
			for ( var i = 0; i < blocks.goods.length - 1; i++) {
				var g = blocks.goods[i];

				var m2 = Math.min(blocks.mprs[i + 1]);
				var bar_top = height * (1 - m2 * (1 - reserve));
				var bar_height = height - bar_top;

				ctx.fillRect(g.start * ppd, bar_top, g.duration * ppd,
						bar_height);
			}

			ctx.strokeStyle = 'rgba(0,0,0,1)';
			ctx.lineWidth = 1;
			ctx.beginPath();
			var x = blocks.starts[blocks.starts.length - 1];
			ctx.moveTo(0, height);
			ctx.lineTo(x * ppd, height);
			ctx.stroke();

		}
		canvas = $(canvas);
		canvas.show();// "slide", {direction: "left"}, 300);

	},

	calculate_blocks : function(fills) {

		var goods = [];
		var mprs = [];
		var starts = [];

		var t_0 = fills[0].start.getTime();
		var l = fills.length;

		var pills_on_hand = 0;
		var total_pills_received = 0;

		for ( var i = 0; i < l; i++) {
			var f = fills[i];
			var q = parseInt(f.quantity);

			var start = Math.floor((f.start.getTime() - t_0) / 86400000.0);
			starts.push(start);

			if (start > 0) {
				mprs.push(1.0 * total_pills_received / start);

				var elapsed = start - goods[i - 1].start;
				pills_on_hand -= elapsed;
				pills_on_hand = Math.max(0, pills_on_hand)
			}
			else {
				mprs.push(null);
			}

			pills_on_hand += q;
			total_pills_received += q;

			var g = {
				start : start,
				duration : pills_on_hand
			};
			goods.push(g);

		}
		for (var i = mprs.length-2; i>=0; i--)
			if (mprs[i] == null) mprs[i] = mprs[i+1];

		return {
			starts : starts,
			goods : goods,
			mprs : mprs
		};

	}

});<|endoftext|>