<commit_before>L.scenograph.director.character_test = function() {
	// scene shit here
	console.log('Character test started')

	L.scenograph.director.camera_state.zoom = 500;
	L.scenograph.director.camera.position.set(
		0,
		0,
		L.scenograph.director.camera_state.zoom
	);
	var character = L.scenograph.director.make_character();
	character.position.y = -25;
	this.scene.add(character);
	this.animation_queue.push(character.animation)
	$('.dg.main ul').append('

');

	// direction (normalized), origin, length, color(hex)
	var origin = new THREE.Vector3(0,-130,0);
	var arrow = new THREE.ArrowHelper(new THREE.Vector3(0,0,1), origin,100, 0xFFCC00);
	this.scene.add(arrow);

	var gridXZ = new THREE.GridHelper(1000, 80);
	gridXZ.setColors( new THREE.Color(0x006600), new THREE.Color(0x006600) );
	gridXZ.position.set( 0,-150,0 );
	this.scene.add(gridXZ);
	var gridXY = new THREE.GridHelper(1000, 80);
	gridXY.setColors( new THREE.Color(0x006600), new THREE.Color(0x006600) );
	gridXY.rotation.z = Math.PI/2;
	gridXY.position.set( 1000,850,0 );
	this.scene.add(gridXY);
	var gridZY = new THREE.GridHelper(1000, 80);
	gridZY.setColors( new THREE.Color(0x006600), new THREE.Color(0x006600) );
	gridZY.rotation.x = Math.PI/2;
	gridZY.position.set( 0,850,1000 );
	this.scene.add(gridZY);

	var wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x666600, wireframe: true, transparent: true } );
	var box1 = new THREE.Mesh(new THREE.BoxGeometry(150, 75, 75), wireframeMaterial);
	box1.position.set(300,-110,300);
	this.scene.add(box1);
	var box2 = new THREE.Mesh(new THREE.BoxGeometry(150, 75, 75), wireframeMaterial);
	box2.position.set(300,-110,400);
	this.scene.add(box2);
	var box3 = new THREE.Mesh(new THREE.BoxGeometry(150, 75, 75), wireframeMaterial);
	box3.position.set(300,-35,300);
	this.scene.add(box3);
};

L.scenograph.director.make_character = function() {
	var texture = new THREE.ImageUtils.loadTexture( '/assets/exordium-male.png' );

	var material = new THREE.MeshBasicMaterial( { map: texture, transparent: true, side:THREE.DoubleSide, alphaTest: 0.5 } );
	var geometry = new THREE.PlaneGeometry(12.5, 30.4);

	var new_character = new THREE.Mesh(geometry, material);
	new_character.world_rotation = 0;
	new_character.animation = new L.scenograph.director.make_animation( new_character, texture, 34, 1, 34, 3400 ); // texture, #horiz, #vert, #total, duration.
	new_character.scale.set(10,10,10);

	return new_character;
}

L.scenograph.director.move_character = function(character) {
	character.animation.moving = false;
	var rY = 0, tZ = 0, radian = (Math.PI / 180);
	if (L.scenograph.keyboard.pressed("W")) {
		tZ += 1.25;
		character.animation.moving = true;
	}
	if (L.scenograph.keyboard.pressed("S")) {
		tZ -= 1.25;
		character.animation.moving = true;
	}
	if (L.scenograph.keyboard.pressed("A")) {
		rY += radian;
		character.animation.moving = true;
	}
	if (L.scenograph.keyboard.pressed("D")) {
		rY -= radian;
		character.animation.moving = true;
	}
	if (rY != 0) {
		character.world_rotation += rY;
	}
	if (tZ != 0) {
		character.position.x += tZ * Math.sin(character.world_rotation);
		character.position.z += tZ * Math.cos(character.world_rotation);
	}
}

L.scenograph.director.make_animation = function( character, texture, tilesHoriz, tilesVert, numTiles, tileDispDuration) {
	this.face = 'front';
	this.last_face = 'front';
	this.moving = true;
	// take in some variables to create a sprite object
	this.tilesHorizontal = tilesHoriz;
	this.tilesVertical = tilesVert;
	// how many images does this spritesheet contain?
	//  usually equals tilesHoriz * tilesVert, but not necessarily,
	//  if there at blank tiles at the bottom of the spritesheet.
	this.numberOfTiles = numTiles;
	texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
	texture.repeat.set( 1 / this.tilesHorizontal, 1 / this.tilesVertical );

	// how long should each image be displayed?
	this.tileDisplayDuration = tileDispDuration;

	// how long has the current image been displayed?
	this.currentDisplayTime = 0;

	// which image is currently being displayed?
	this.currentTile = 0;

	this.animate = function(delta) {
		L.scenograph.director.move_character(character);
		var tile_start = 0, tile_end = 7;
		switch(this.face) {
			case 'front':
				tile_start = 0;
				tile_end = 7;
				break;
			case 'back':
				tile_start = 8;
				tile_end = 15;
				break;
			case 'left':
				tile_start = 25;
				tile_end = 33;
				break;
			case 'right':
				tile_start = 16;
				tile_end = 24;
				break;
		}
		if (this.face != this.last_face) {
			this.currentTile = tile_start;
			this.last_face = this.face;
		}

		character.lookAt(L.scenograph.director.camera.position);
		var axis = new THREE.Vector3( 0, -1, 0 );
		var angle = character.world_rotation;
		var matrix = new THREE.Matrix4().makeRotationAxis( axis, angle );
		var vector = character.position.clone();

		var diff = new THREE.Vector3().subVectors(character.position, L.scenograph.director.camera.position).normalize();
		diff.applyMatrix4(matrix);

		$("#character_stuff").html("rY: " + character.world_rotation + "
x: " + diff.x + "
y: " + diff.y + "
z: " + diff.z);
		if (diff.x < 0.6  && diff.x > -0.6 && diff.z <= 0.0) {
			this.face = 'front';
		}
		if (diff.x > 0.5 && diff.x < 0.8) {
			this.face = 'right';
		}
		if (diff.x < -0.5 && diff.x > -0.8) {
			this.face = 'left';
		}
		if (diff.z > 0.8) {
			this.face = 'back'
		}
		if (this.moving == true) {
			this.currentDisplayTime += delta * 25;
			while (this.currentDisplayTime > this.tileDisplayDuration)
			{
				this.currentDisplayTime -= this.tileDisplayDuration;

				if (this.currentTile >= tile_end) {
					this.currentTile = tile_start;
				}
				else {
					this.currentTile++;
				}
				var currentColumn = this.currentTile % this.tilesHorizontal;
				texture.offset.x = currentColumn / this.tilesHorizontal;
				var currentRow = Math.floor( this.currentTile / this.tilesHorizontal );
				texture.offset.y = currentRow / this.tilesVertical;
			}
		}
		else {
			this.currentTile = tile_start + 1;
			var currentColumn = this.currentTile % this.tilesHorizontal;
				texture.offset.x = currentColumn / this.tilesHorizontal;
				var currentRow = Math.floor( this.currentTile / this.tilesHorizontal );
				texture.offset.y = currentRow / this.tilesVertical;
		}

	}
}

L.scenograph.director.animate_character = function(delta) {

}<commit_msg>- Stripped out dev stuff.. character rotation is working great!!<commit_after>L.scenograph.director.character_test = function() {
	// scene shit here
	console.log('Character test started')

	L.scenograph.director.camera_state.zoom = 500;
	L.scenograph.director.camera.position.set(
		0,
		0,
		L.scenograph.director.camera_state.zoom
	);
	var character = L.scenograph.director.make_character();
	character.position.y = -25;
	this.scene.add(character);
	this.animation_queue.push(character.animation)

	// direction (normalized), origin, length, color(hex)
	var origin = new THREE.Vector3(0,-130,0);
	var arrow = new THREE.ArrowHelper(new THREE.Vector3(0,0,1), origin,100, 0xFFCC00);
	this.scene.add(arrow);

	var gridXZ = new THREE.GridHelper(1000, 80);
	gridXZ.setColors( new THREE.Color(0x006600), new THREE.Color(0x006600) );
	gridXZ.position.set( 0,-150,0 );
	this.scene.add(gridXZ);
	var gridXY = new THREE.GridHelper(1000, 80);
	gridXY.setColors( new THREE.Color(0x006600), new THREE.Color(0x006600) );
	gridXY.rotation.z = Math.PI/2;
	gridXY.position.set( 1000,850,0 );
	this.scene.add(gridXY);
	var gridZY = new THREE.GridHelper(1000, 80);
	gridZY.setColors( new THREE.Color(0x006600), new THREE.Color(0x006600) );
	gridZY.rotation.x = Math.PI/2;
	gridZY.position.set( 0,850,1000 );
	this.scene.add(gridZY);

	var wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x666600, wireframe: true, transparent: true } );
	var box1 = new THREE.Mesh(new THREE.BoxGeometry(150, 75, 75), wireframeMaterial);
	box1.position.set(300,-110,300);
	this.scene.add(box1);
	var box2 = new THREE.Mesh(new THREE.BoxGeometry(150, 75, 75), wireframeMaterial);
	box2.position.set(300,-110,400);
	this.scene.add(box2);
	var box3 = new THREE.Mesh(new THREE.BoxGeometry(150, 75, 75), wireframeMaterial);
	box3.position.set(300,-35,300);
	this.scene.add(box3);
};

L.scenograph.director.make_character = function() {
	var texture = new THREE.ImageUtils.loadTexture( '/assets/exordium-male.png' );

	var material = new THREE.MeshBasicMaterial( { map: texture, transparent: true, side:THREE.DoubleSide, alphaTest: 0.5 } );
	var geometry = new THREE.PlaneGeometry(12.5, 30.4);

	var new_character = new THREE.Mesh(geometry, material);
	new_character.world_rotation = 0;
	new_character.animation = new L.scenograph.director.make_animation( new_character, texture, 34, 1, 34, 3400 ); // texture, #horiz, #vert, #total, duration.
	new_character.scale.set(10,10,10);

	return new_character;
}

L.scenograph.director.move_character = function(character) {
	character.animation.moving = false;
	var rY = 0, tZ = 0, radian = (Math.PI / 180);
	if (L.scenograph.keyboard.pressed("W")) {
		tZ += 1.25;
		character.animation.moving = true;
	}
	if (L.scenograph.keyboard.pressed("S")) {
		tZ -= 1.25;
		character.animation.moving = true;
	}
	if (L.scenograph.keyboard.pressed("A")) {
		rY += radian;
		character.animation.moving = true;
	}
	if (L.scenograph.keyboard.pressed("D")) {
		rY -= radian;
		character.animation.moving = true;
	}
	if (rY != 0) {
		character.world_rotation += rY;
	}
	if (tZ != 0) {
		character.position.x += tZ * Math.sin(character.world_rotation);
		character.position.z += tZ * Math.cos(character.world_rotation);
	}
}

L.scenograph.director.make_animation = function( character, texture, tilesHoriz, tilesVert, numTiles, tileDispDuration) {
	this.face = 'front';
	this.last_face = 'front';
	this.moving = true;
	// take in some variables to create a sprite object
	this.tilesHorizontal = tilesHoriz;
	this.tilesVertical = tilesVert;
	// how many images does this spritesheet contain?
	//  usually equals tilesHoriz * tilesVert, but not necessarily,
	//  if there at blank tiles at the bottom of the spritesheet.
	this.numberOfTiles = numTiles;
	texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
	texture.repeat.set( 1 / this.tilesHorizontal, 1 / this.tilesVertical );

	// how long should each image be displayed?
	this.tileDisplayDuration = tileDispDuration;

	// how long has the current image been displayed?
	this.currentDisplayTime = 0;

	// which image is currently being displayed?
	this.currentTile = 0;

	this.animate = function(delta) {
		L.scenograph.director.move_character(character);
		var tile_start = 0, tile_end = 7;
		switch(this.face) {
			case 'front':
				tile_start = 0;
				tile_end = 6;
				break;
			case 'back':
				tile_start = 8;
				tile_end = 14;
				break;
			case 'left':
				tile_start = 25;
				tile_end = 32;
				break;
			case 'right':
				tile_start = 16;
				tile_end = 23;
				break;
		}
		if (this.face != this.last_face) {
			this.currentTile = tile_start;
			this.last_face = this.face;
		}

		character.lookAt(L.scenograph.director.camera.position);
		var axis = new THREE.Vector3( 0, -1, 0 );
		var angle = character.world_rotation;
		var matrix = new THREE.Matrix4().makeRotationAxis( axis, angle );
		var vector = character.position.clone();

		var diff = new THREE.Vector3().subVectors(character.position, L.scenograph.director.camera.position).normalize();
		diff.applyMatrix4(matrix);

		if (diff.x < 0.6  && diff.x > -0.6 && diff.z <= 0.0) {
			this.face = 'front';
		}
		if (diff.x > 0.5 && diff.x < 0.8) {
			this.face = 'right';
		}
		if (diff.x < -0.5 && diff.x > -0.8) {
			this.face = 'left';
		}
		if (diff.z > 0.8) {
			this.face = 'back'
		}
		if (this.moving == true) {
			this.currentDisplayTime += delta * 25;
			while (this.currentDisplayTime > this.tileDisplayDuration)
			{
				this.currentDisplayTime -= this.tileDisplayDuration;

				if (this.currentTile >= tile_end) {
					this.currentTile = tile_start;
				}
				else {
					this.currentTile++;
				}
				var currentColumn = this.currentTile % this.tilesHorizontal;
				texture.offset.x = currentColumn / this.tilesHorizontal;
				var currentRow = Math.floor( this.currentTile / this.tilesHorizontal );
				texture.offset.y = currentRow / this.tilesVertical;
			}
		}
		else {
			this.currentTile = tile_start + 1;
			var currentColumn = this.currentTile % this.tilesHorizontal;
				texture.offset.x = currentColumn / this.tilesHorizontal;
				var currentRow = Math.floor( this.currentTile / this.tilesHorizontal );
				texture.offset.y = currentRow / this.tilesVertical;
		}

	}
}

L.scenograph.director.animate_character = function(delta) {

}<|endoftext|>


<commit_before>var colors = [
  "#2484c1",
  "#0c6197",
  "#4daa4b",
  "#90c469",
  "#daca61",
  "#e4a14b",
  "#e98125",
  "#cb2121",
  "#830909",
  "#923e99",
  "#ae83d5",
  "#bf273e",
  "#ce2aeb",
  "#bca44a",
  "#618d1b",
  "#1ee67b",
  "#b0ec44",
  "#a4a0c9",
  "#322849",
  "#86f71a",
  "#d1c87f",
  "#7d9058",
  "#44b9b0",
  "#7c37c0",
  "#cc9fb1",
  "#e65414",
  "#8b6834",
  "#248838"];

var pieChart = function(id, title, subtitle, data) {
  var chart = new d3pie(id,
                        { "header": {
                          "title": {
                            "text": title,
                            "fontSize": 24,
                            "font": "open sans"
                          },
                          "subtitle": {
                            "text": subtitle,
                            "color": "#999999",
                            "fontSize": 12,
                            "font": "open sans"
                          },
                          "location": "top-left",
                          "titleSubtitlePadding": 9
                        },
	                  "footer": {
		            "color": "#999999",
		            "fontSize": 10,
		            "font": "open sans",
		            "location": "bottom-left"
	                  },
	                  "size": {
		            "canvasHeight": 300,
		            "canvasWidth": 390,
		            "pieOuterRadius": "90%"
	                  },
	                  "data": {
		            "sortOrder": "value-desc",
	                    "content": data,

	                  },
	                  "labels": {
		            "outer": {
			      "pieDistance": 32
		            },
		            "inner": {
			      "hideWhenLessThanPercentage": 3
		            },
		            "mainLabel": {
			      "fontSize": 11
		            },
		            "percentage": {
			      "color": "#ffffff",
			      "decimalPlaces": 0
		            },
		            "value": {
			      "color": "#adadad",
			      "fontSize": 11
		            },
		            "lines": {
			      "enabled": true
		            },
		            "truncation": {
			      "enabled": true
		            }
	                  },
	                  "effects": {
		            "pullOutSegmentOnClick": {
			      "effect": "linear",
			      "speed": 400,
			      "size": 8
		            }
	                  },
	                  "misc": {
		            "gradient": {
			      "enabled": true,
			      "percentage": 100
		            }
	                  }
                        });

};

var polarChart = function(id, title, subtitle, data) {
  var dataValues = [];
  var dataColors = [];
  var dataLabels = [];

  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    dataValues.push(item.value);
    dataColors.push(item.color);
    dataLabels.push(item.label);
  }

  var polarData = {
    datasets: [{
      data: dataValues,
      backgroundColor: dataColors,
      label: [
        title
      ]
    }],
    labels: dataLabels
  };

  var polarOptions = {
    segmentStrokeWidth: 2,
    responsive: true
  };

  var ctx3 = document.getElementById(id).getContext("2d");
  new Chart(ctx3, {type: 'polarArea', data: polarData, options:polarOptions});
}

function barChart(canvas, title, subtitle, data) {
  var dataValues = [];
  var dataColors = [];
  var dataLabels = [];

  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    dataValues.push(item.value);
    dataColors.push(item.color);
    dataLabels.push(item.label);
  }

  var ctx = canvas.getContext("2d");
  return new Chart(ctx, {
    type: 'horizontalBar',
    data: { labels: dataLabels,
            datasets: [{
              label: title,
              backgroundColor: dataColors[0],
              borderColor: dataColors[0],
              borderWidth: 1,
              data: dataValues
            }]},
    options: {
      // Elements options apply to all of the options unless overridden in a dataset
      // In this case, we are setting the border of each horizontal bar to be 2px wide
      elements: {
        rectangle: {
          borderWidth: 2,
        }
      },
      responsive: true,
      legend: {
        position: 'right',
      },
      title: {
        display: true,
        text: subtitle
      }
    }
  });
};

var dependencyTreeChart = function(treeData, treeContainer) {
  var width = 600;
  var height = 600;
  var svg = treeContainer.append("svg").attr("width", width).attr("height", height);
  var g = svg.append("g").attr("transform", "translate(150,0)");

  var tree = d3.cluster()
      .size([height, width - 400]);

  var stratify = d3.stratify(treeData)
      .id(toDependencyId)
      .parentId(fromDependencyId);

  var root = stratify(treeData).sort(dependencyCompare);

  tree(root);

  var link = g.selectAll(".link")
      .data(root.descendants().slice(1))
      .enter().append("path")
      .attr("class", "link")
      .attr("d", function(d) {
        return "M" + d.y + "," + d.x
          + "C" + (d.parent.y + 10) + "," + d.x
          + " " + (d.parent.y + 10) + "," + d.parent.x
          + " " + d.parent.y + "," + d.parent.x;
      });

  var node = g.selectAll(".node")
      .data(root.descendants())
      .enter().append("g")
      .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("circle")
      .attr("r", 2.5);

  node.append("text")
    .attr("dy", function(d) {
      if (!d.parent) {
        return -8;
      }
      return 2; })
    .attr("x", function(d) {
      if (!d.parent) {
        return 8;
      }
      return d.children ? -8 : 8; })
    .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
    .text(function(d) { return d.id; });
//    .text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });
}

<commit_msg>chart cleanup for smaller screens<commit_after>var colors = [
  "#2484c1",
  "#0c6197",
  "#4daa4b",
  "#90c469",
  "#daca61",
  "#e4a14b",
  "#e98125",
  "#cb2121",
  "#830909",
  "#923e99",
  "#ae83d5",
  "#bf273e",
  "#ce2aeb",
  "#bca44a",
  "#618d1b",
  "#1ee67b",
  "#b0ec44",
  "#a4a0c9",
  "#322849",
  "#86f71a",
  "#d1c87f",
  "#7d9058",
  "#44b9b0",
  "#7c37c0",
  "#cc9fb1",
  "#e65414",
  "#8b6834",
  "#248838"];

var pieChart = function(id, title, subtitle, data) {
  var chart = new d3pie(id,
                        { "header": {
                          "title": {
                            "text": title,
                            "fontSize": 24,
                            "font": "open sans"
                          },
                          "subtitle": {
                            "text": subtitle,
                            "color": "#999999",
                            "fontSize": 12,
                            "font": "open sans"
                          },
                          "location": "top-left",
                          "titleSubtitlePadding": 9
                        },
	                  "footer": {
		            "color": "#999999",
		            "fontSize": 10,
		            "font": "open sans",
		            "location": "bottom-left"
	                  },
	                  "size": {
		            "canvasHeight": 300,
		            "canvasWidth": 390,
		            "pieOuterRadius": "90%"
	                  },
	                  "data": {
		            "sortOrder": "value-desc",
	                    "content": data,

	                  },
	                  "labels": {
		            "outer": {
			      "pieDistance": 32
		            },
		            "inner": {
			      "hideWhenLessThanPercentage": 3
		            },
		            "mainLabel": {
			      "fontSize": 11
		            },
		            "percentage": {
			      "color": "#ffffff",
			      "decimalPlaces": 0
		            },
		            "value": {
			      "color": "#adadad",
			      "fontSize": 11
		            },
		            "lines": {
			      "enabled": true
		            },
		            "truncation": {
			      "enabled": true
		            }
	                  },
	                  "effects": {
		            "pullOutSegmentOnClick": {
			      "effect": "linear",
			      "speed": 400,
			      "size": 8
		            }
	                  },
	                  "misc": {
		            "gradient": {
			      "enabled": true,
			      "percentage": 100
		            }
	                  }
                        });

};

var polarChart = function(id, title, subtitle, data) {
  var dataValues = [];
  var dataColors = [];
  var dataLabels = [];

  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    dataValues.push(item.value);
    dataColors.push(item.color);
    dataLabels.push(item.label);
  }

  var polarData = {
    datasets: [{
      data: dataValues,
      backgroundColor: dataColors,
      label: [
        title
      ]
    }],
    labels: dataLabels
  };

  var polarOptions = {
    segmentStrokeWidth: 2,
    responsive: true
  };

  var ctx3 = document.getElementById(id).getContext("2d");
  new Chart(ctx3, {type: 'polarArea', data: polarData, options:polarOptions});
}

function barChart(canvas, title, subtitle, data) {
  var dataValues = [];
  var dataColors = [];
  var dataLabels = [];

  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    dataValues.push(item.value);
    dataColors.push(item.color);
    dataLabels.push(item.label);
  }

  var ctx = canvas.getContext("2d");
  return new Chart(ctx, {
    type: 'horizontalBar',
    data: { labels: dataLabels,
            datasets: [{
              label: title,
              backgroundColor: dataColors[0],
              borderColor: dataColors[0],
              borderWidth: 1,
              data: dataValues
            }]},
    options: {
      // Elements options apply to all of the options unless overridden in a dataset
      // In this case, we are setting the border of each horizontal bar to be 2px wide
      elements: {
        rectangle: {
          borderWidth: 2,
        }
      },
      responsive: true,
      legend: {
        position: 'right',
      },
      title: {
        display: true,
        text: subtitle
      }
    }
  });
};

var dependencyTreeChart = function(treeData, treeContainer) {
  var width = 500;
  var height = 300;
  var svg = treeContainer.append("svg").attr("width", width).attr("height", height);
  var g = svg.append("g").attr("transform", "translate(150,0)");

  var tree = d3.cluster()
      .size([height, width - 400]);

  var stratify = d3.stratify(treeData)
      .id(toDependencyId)
      .parentId(fromDependencyId);

  var root = stratify(treeData).sort(dependencyCompare);

  tree(root);

  var link = g.selectAll(".link")
      .data(root.descendants().slice(1))
      .enter().append("path")
      .attr("class", "link")
      .attr("d", function(d) {
        return "M" + d.y + "," + d.x
          + "C" + (d.parent.y + 10) + "," + d.x
          + " " + (d.parent.y + 10) + "," + d.parent.x
          + " " + d.parent.y + "," + d.parent.x;
      });

  var node = g.selectAll(".node")
      .data(root.descendants())
      .enter().append("g")
      .attr("class", function(d) { return "node" + (d.children ? " node--internal" : " node--leaf"); })
      .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

  node.append("circle")
      .attr("r", 2.5);

  node.append("text")
    .attr("dy", function(d) {
      if (!d.parent) {
        return 2;
      }
      return 2; })
    .attr("x", function(d) {
      if (!d.parent) {
        return -8;
      }
      return d.children ? -8 : 8; })
    .style("text-anchor", function(d) { return d.children ? "end" : "start"; })
    .text(function(d) { return d.id; });
//    .text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });
}

<|endoftext|>


<commit_before>/**
 * $Id$
 *
 * Utilities used with tablesorter
 */

/**
 * Fetch rows from an ajax pagination call
 *
 * @param data
 * @param id
 * @param addcol
 * @param total
 * @returns {{}}
 */
function tsAjaxGetRows (data, id, addcol, total)
{

	//parse HTML string from entire page
	var parsedpage = $.parseHTML(data), table = $(parsedpage).find(id), r = {};
	//extract table body rows from html returned by smarty template file
	r.rows = $(table).find('tbody tr');
	//add any math total columns
	if (addcol) {
		$.each(addcol, function (key, value) {
			$(r.rows).append('	');
		});
	}
	//tablesorter needs total rows
	r.total = total;
	r.headers = null;
	return r;
}

/**
 * Generate an ajax url
 *
 * @param url
 * @param p
 * @param a
 * @returns {*}
 */
function tsAjaxUrl (url, p, a) {
	var vars = {}, urlparams, oneparam, sorts = false, sortindex, sortkey = 'sort-', filterindex, filterkey = 'filter-',
		params = [], dir, offset, newurl;
	if (a.custom !== false) {
		//parse out url parameters
		urlparams = url.slice(url.indexOf('?') + 1).split('&');
		for(var i = 0; i < urlparams.length; i++) {
			oneparam = urlparams[i].split('=');
			if (oneparam[0].search('sort') > -1) {
				sortindex = parseInt(oneparam[0].substr(5, oneparam[0].length - 6));
				if ($.isNumeric(sortindex)) {
					sortkey = a.colselector ? sortkey + $(a.tableid + ' th:eq(' + sortindex + ')').attr('id')
						: sortkey + sortindex;
					vars[sortkey] = oneparam[1];
				}
			} else if (oneparam[0].search('filter') > -1) {
				filterindex = parseInt(oneparam[0].substr(7, oneparam[0].length - 8));
				if ($.isNumeric(filterindex)) {
					filterkey = a.colselector ? filterkey + $(a.tableid + ' th:eq(' + filterindex + ')').attr('id')
						: filterkey + filterindex;
					vars[filterkey] = oneparam[1];
				}
			}
		}
		//iterate through url parameters
		$.each(vars, function(key, value) {
			//handle sort parameters
			if (a.asort && key in a.asort) {
				dir = value == 0 ? '_asc' : '_desc';
				//add sort if not yet defined or add sort for multiple comma-separated sort parameters
				!sorts ? sorts = a.asort[key] + dir : sorts += ',' + a.asort[key] + dir;
			}
			//handle column and external filter parameters
			if ($.inArray(value, a.extfilters) > -1) {
				params.push(decodeURIComponent(value));
			} else if (key in a.colfilters) {
				a.colfilters[key] == value ? params.push(a.colfilters[key][value]) : params.push(a.colfilters[key] + '='
					+ value);
			}
		});
		//convert to tiki sort param sort parameter
		if (sorts) {
			params.push(a.sortparam + '=' + sorts);
		}
		//add any required params
		if (a.requiredparams) {
			$.each(a.requiredparams, function(key, value) {
				params.push(key + '=' + value);
			});
		}
		//offset parameter
		offset = ((p.page * p.size) >= p.filteredRows) ? '' : '&' + a.offset + '=' + (p.page * p.size);
		//build url, starting with no parameters
		newurl = url.slice(0,url.indexOf('?'));
		newurl = newurl + '?' + a.numrows + '=' + p.size + offset + '&tsAjax=y';
		$.each(params, function(key, value) {
			newurl = newurl + '&' + value;
		});
	} else {
		offset = ((p.page * p.size) >= p.filteredRows) ? '' : '&' + a.offset + '=' + (p.page * p.size);
		newurl = url + '&tsAjax=y' + offset + '&numrows=' + p.size;
	}
	return newurl;
}
var pdfUrl='';
var bindCalls=0;
var ajaxCalls=0;

function storeSortTable(tableName,tableHTML){
	  bindCalls++;
	  if($('.icon-pdf').parent().attr('href')!="#")
	  {
		  pdfUrl=$('.icon-pdf').parent().attr('href');
		  $('.icon-pdf').parent().attr('href',"#");

	  }
	  //calling ajax function to store tableHTML in case of pdf button is clicked
	  //this is the ajax action once the confirm submit button is clicked;
	  tableHTML=tableHTML;
	  tableName=tableName.replace("table#","#");

	  tableHTML=tableHTML.replace("on<x>click=","");
	$.ajax({
		type: 'POST',
		url: 'tiki-ajax_services.php',
		dataType: 'json',
		data: {
			    controller: 'AutoSave',
				action: 'storeTable',
				tableName:tableName,
				tableHTML:tableHTML

		},
		success: function (data) {
		$('#tikifeedback').hide();
	    	        ajaxCalls++;
				if(ajaxCalls==bindCalls)
                {
				  window.location.href=pdfUrl;
			      $('.icon-pdf').parent().attr('href',pdfUrl);
				}

		}
	});
	}<commit_msg>[FIX] tablesorter: missed filtered rows value when converting to functions in r59339<commit_after>/**
 * $Id$
 *
 * Utilities used with tablesorter
 */

/**
 * Fetch rows from an ajax pagination call
 *
 * @param data
 * @param id
 * @param addcol
 * @param total
 * @returns {{}}
 */
function tsAjaxGetRows (data, id, addcol, total)
{

	//parse HTML string from entire page
	var parsedpage = $.parseHTML(data), table = $(parsedpage).find(id), r = {};
	//extract table body rows from html returned by smarty template file
	r.rows = $(table).find('tbody tr');
	//add any math total columns
	if (addcol) {
		$.each(addcol, function (key, value) {
			$(r.rows).append('	');
		});
	}
	//tablesorter needs total rows
	r.total = total;
	r.filteredRows = $(table).data('count');
	r.headers = null;
	return r;
}

/**
 * Generate an ajax url
 *
 * @param url
 * @param p
 * @param a
 * @returns {*}
 */
function tsAjaxUrl (url, p, a) {
	var vars = {}, urlparams, oneparam, sorts = false, sortindex, sortkey = 'sort-', filterindex, filterkey = 'filter-',
		params = [], dir, offset, newurl;
	if (a.custom !== false) {
		//parse out url parameters
		urlparams = url.slice(url.indexOf('?') + 1).split('&');
		for(var i = 0; i < urlparams.length; i++) {
			oneparam = urlparams[i].split('=');
			if (oneparam[0].search('sort') > -1) {
				sortindex = parseInt(oneparam[0].substr(5, oneparam[0].length - 6));
				if ($.isNumeric(sortindex)) {
					sortkey = a.colselector ? sortkey + $(a.tableid + ' th:eq(' + sortindex + ')').attr('id')
						: sortkey + sortindex;
					vars[sortkey] = oneparam[1];
				}
			} else if (oneparam[0].search('filter') > -1) {
				filterindex = parseInt(oneparam[0].substr(7, oneparam[0].length - 8));
				if ($.isNumeric(filterindex)) {
					filterkey = a.colselector ? filterkey + $(a.tableid + ' th:eq(' + filterindex + ')').attr('id')
						: filterkey + filterindex;
					vars[filterkey] = oneparam[1];
				}
			}
		}
		//iterate through url parameters
		$.each(vars, function(key, value) {
			//handle sort parameters
			if (a.asort && key in a.asort) {
				dir = value == 0 ? '_asc' : '_desc';
				//add sort if not yet defined or add sort for multiple comma-separated sort parameters
				!sorts ? sorts = a.asort[key] + dir : sorts += ',' + a.asort[key] + dir;
			}
			//handle column and external filter parameters
			if ($.inArray(value, a.extfilters) > -1) {
				params.push(decodeURIComponent(value));
			} else if (key in a.colfilters) {
				a.colfilters[key] == value ? params.push(a.colfilters[key][value]) : params.push(a.colfilters[key] + '='
					+ value);
			}
		});
		//convert to tiki sort param sort parameter
		if (sorts) {
			params.push(a.sortparam + '=' + sorts);
		}
		//add any required params
		if (a.requiredparams) {
			$.each(a.requiredparams, function(key, value) {
				params.push(key + '=' + value);
			});
		}
		//offset parameter
		offset = ((p.page * p.size) >= p.filteredRows) ? '' : '&' + a.offset + '=' + (p.page * p.size);
		//build url, starting with no parameters
		newurl = url.slice(0,url.indexOf('?'));
		newurl = newurl + '?' + a.numrows + '=' + p.size + offset + '&tsAjax=y';
		$.each(params, function(key, value) {
			newurl = newurl + '&' + value;
		});
	} else {
		offset = ((p.page * p.size) >= p.filteredRows) ? '' : '&' + a.offset + '=' + (p.page * p.size);
		newurl = url + '&tsAjax=y' + offset + '&numrows=' + p.size;
	}
	return newurl;
}
var pdfUrl='';
var bindCalls=0;
var ajaxCalls=0;

function storeSortTable(tableName,tableHTML){
	  bindCalls++;
	  if($('.icon-pdf').parent().attr('href')!="#")
	  {
		  pdfUrl=$('.icon-pdf').parent().attr('href');
		  $('.icon-pdf').parent().attr('href',"#");

	  }
	  //calling ajax function to store tableHTML in case of pdf button is clicked
	  //this is the ajax action once the confirm submit button is clicked;
	  tableHTML=tableHTML;
	  tableName=tableName.replace("table#","#");

	  tableHTML=tableHTML.replace("on<x>click=","");
	$.ajax({
		type: 'POST',
		url: 'tiki-ajax_services.php',
		dataType: 'json',
		data: {
			    controller: 'AutoSave',
				action: 'storeTable',
				tableName:tableName,
				tableHTML:tableHTML

		},
		success: function (data) {
		$('#tikifeedback').hide();
	    	        ajaxCalls++;
				if(ajaxCalls==bindCalls)
                {
				  window.location.href=pdfUrl;
			      $('.icon-pdf').parent().attr('href',pdfUrl);
				}

		}
	});
	}<|endoftext|>


<commit_before>// $Id$
// JavaScript glue for JQuery (1.3.2) in TikiWiki (3.0)

var $jq = jQuery.noConflict();

$jq(document).ready( function() { // JQuery's DOM is ready event - before onload

	var jqNoAnimElements = ['help_sections', 'ajaxLoading'];

	// override existing show/hide routines here
	show = function (foo,f,section) {
		if (jQuery.inArray(foo, jqNoAnimElements) > -1) {		// exceptions that don't animate reliably
			$jq("#" + foo).show();
		} else if ($jq("#" + foo).hasClass("tabcontent")) {		// different anim prefs for tabs
			showJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
		} else {
			showJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
		}
		if (f) { setCookie(foo, "o", section); }
	};

	hide = function (foo,f, section) {
		if (jQuery.inArray(foo, jqNoAnimElements) > -1) {		// exceptions
			$jq("#" + foo).hide();
		} else if ($jq("#" + foo).hasClass("tabcontent")) {
			hideJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
		} else {
			hideJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
		}
		if (f) {
			var wasnot = getCookie(foo, section, 'x') == 'x';
			setCookie(foo, "c", section);
			if (wasnot) {
				history.go(0);	// ik!
			}
		}
	};

	// flip function... unfortunately didn't use show/hide (ay?)
	flip = function (foo,style) {
		if (style && style != 'block' || foo == 'help_sections' || foo == 'fgalexplorer') {	// TODO find a better way?
			$jq("#" + foo).toggle();	// inlines don't animate reliably (yet) (also help)
			if ($jq("#" + foo).css('display') == 'none') {
				setSessionVar('show_' + escape(foo), 'n');
			} else {
				setSessionVar('show_' + escape(foo), 'y');
			}
		} else {
			if ($jq("#" + foo).css("display") == "none") {
				setSessionVar('show_' + escape(foo), 'y');
				showJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
			}
			else {
				setSessionVar('show_' + escape(foo), 'n');
				hideJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
			}
		}
	};

	// handle JQ effects
	showJQ = function (selector, effect, speed, dir) {
		if (effect == 'none') {
			$jq(selector).show();
		} else if (effect == '' || effect == 'normal') {
			$jq(selector).show(speed);
		} else if (effect == 'slide') {
			$jq(selector).slideDown(speed);
		} else if (effect == 'fade') {
			$jq(selector).fadeIn(speed);
		} else if (effect.match(/(.*)_ui$/).length > 1) {
			$jq(selector).show(effect.match(/(.*)_ui$/)[1], {direction: dir }, speed);
		} else {
			$jq(selector).show();
		}
	};

	hideJQ = function (selector, effect, speed, dir) {
		if (effect == 'none') {
			$jq(selector).hide();
		} else if (effect == '' || effect == 'normal') {
			$jq(selector).hide(speed);
		} else if (effect == 'slide') {
			$jq(selector).slideUp(speed);
		} else if (effect == 'fade') {
			$jq(selector).fadeOut(speed);
		} else if (effect.match(/(.*)_ui$/).length > 1) {
			$jq(selector).hide(effect.match(/(.*)_ui$/)[1], {direction: dir }, speed);
		} else {
			$jq(selector).hide();
		}
	};

	// tooltip functions and setup
	if (jqueryTiki.tooltips) {	// apply "cluetips" to all .tips class anchors
		$jq('.tips').cluetip({splitTitle: '|', showTitle: false, width: '150px', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}});
		$jq('.titletips').cluetip({splitTitle: '|', cluezIndex: 400});
		$jq('.tikihelp').cluetip({splitTitle: ':', width: '150px', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}});

		// override overlib - TODO optimise JQuery calls
		convertOverlib = function (element, tip, options) {	// process overlib event fn to cluetip

			tip = tip.replace(/return overlib\((.*)\).*/gi, '$1');	// remove function wrapper
			var prefix = "";
			var strStart = 0;
			var strEnd = tip.length;

			if (tip.substring(0,1) == "'") {				// overlib is called with a string, then a few "constant" params
				strStart = 1;								// this bit extracts the first string (couldn't get a regexp to work reliably)
				strEnd = tip.lastIndexOf("'");
			} else if (tip.substring(0,1) == '"') {
				strStart = 1;
				strEnd = tip.lastIndexOf('"');
			}

			// process parameters
			params = tip.substring(strEnd-1, tip.length).toLowerCase();	// possibly: sticky,autostatus,autostatuscap,fullhtml,hauto,vauto,closeclick,wrap,followmouse,mouseoff,compatmode
			if (params.indexOf('sticky') > -1) { options.sticky = true; } else { options.sticky = false; }
			//if (params.indexOf('mouseoff') > -1) {}	// TODO?
			if (params.indexOf('fullhtml') > -1) { options.cluetipClass = 'fullhtml'; } else { options.cluetipClass = 'default'; }
			options.splitTitle = '|';
			options.showTitle = false;
			options.width = 'auto';		// this don't work :(
			options.cluezIndex = 400;
			options.dropShadow = true;
			options.fx = {open: 'fadeIn', openSpeed: 'fast'};
			options.closeText = 'x';
			options.mouseOutClose = true;

			// attach new tip
			tip = tip.substring(strStart, strEnd);		// trim quotes
			tip = tip.replace(/\\n/g, '');			// remove newlines
			tip = tip.replace(/\\/g, '');				// remove backslashes

			// hack to calculate div width
			var el = document.createElement('DIV');
			$jq(el).css('position', 'absolute').css('visibility', 'hidden');
			document.body.appendChild(el);
			$jq(el).html(tip);
			options.width = $jq(el).width();
			document.body.removeChild(el);

			prefix = "|";
			$jq(element).attr('title', prefix + tip);

			// options.sticky = true; useful for css work
			$jq(element).cluetip(options);
		}

		$jq("[onmouseover*='overlib(']").each(function() {
			tip = $jq(this)[0].getAttribute('onmouseover');			// use the html call to get the text, not the fn
			convertOverlib(this, tip, {});
		});

		$jq("[onclick*='overlib(']").each(function() {			// TODO refactor!!!!
			tip = $jq(this)[0].getAttribute('onclick');			// use the html call to get the text, not the fn
			convertOverlib(this, tip, {activation: 'click'});
		});

		// nobble overlib funcs
		overlib = function() {};
		nd = function() {};
	}

	// superfish setup (CSS menu effects)
	if (jqueryTiki.superfish) {
		$jq('ul.cssmenu_horiz').superfish({
			animation: {opacity:'show', height:'show'},	// fade-in and slide-down animation
			speed: 'fast'								// faster animation speed
		});
		$jq('ul.cssmenu_vert').superfish({
			animation: {opacity:'show', height:'show'},	// fade-in and slide-down animation
			speed: 'fast'								// faster animation speed
		});
	}

	// tablesorter setup (sortable tables?)
	if (jqueryTiki.tablesorter) {
		$jq('.sortable').tablesorter({
			widthFixed: true							// ??
//			widgets: ['zebra'],							// stripes (coming soon)
		});
	}
});		// end $jq(document).ready

/* Autocomplete assistants */

function parseAutoJSON(data) {
	var parsed = [];
	return $jq.map(data, function(row) {
		return {
			data: row,
			value: row,
			result: row
		}
	});
}

<commit_msg>[FIX] JQuery/ClueTips replacement for overlib - fix popup width (especially for trackers) Some text still not wrapping for me...<commit_after>// $Id$
// JavaScript glue for JQuery (1.3.2) in TikiWiki (3.0)

var $jq = jQuery.noConflict();

$jq(document).ready( function() { // JQuery's DOM is ready event - before onload

	var jqNoAnimElements = ['help_sections', 'ajaxLoading'];

	// override existing show/hide routines here
	show = function (foo,f,section) {
		if (jQuery.inArray(foo, jqNoAnimElements) > -1) {		// exceptions that don't animate reliably
			$jq("#" + foo).show();
		} else if ($jq("#" + foo).hasClass("tabcontent")) {		// different anim prefs for tabs
			showJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
		} else {
			showJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
		}
		if (f) { setCookie(foo, "o", section); }
	};

	hide = function (foo,f, section) {
		if (jQuery.inArray(foo, jqNoAnimElements) > -1) {		// exceptions
			$jq("#" + foo).hide();
		} else if ($jq("#" + foo).hasClass("tabcontent")) {
			hideJQ("#" + foo, jqueryTiki.effect_tabs, jqueryTiki.effect_tabs_speed, jqueryTiki.effect_tabs_direction);
		} else {
			hideJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
		}
		if (f) {
			var wasnot = getCookie(foo, section, 'x') == 'x';
			setCookie(foo, "c", section);
			if (wasnot) {
				history.go(0);	// ik!
			}
		}
	};

	// flip function... unfortunately didn't use show/hide (ay?)
	flip = function (foo,style) {
		if (style && style != 'block' || foo == 'help_sections' || foo == 'fgalexplorer') {	// TODO find a better way?
			$jq("#" + foo).toggle();	// inlines don't animate reliably (yet) (also help)
			if ($jq("#" + foo).css('display') == 'none') {
				setSessionVar('show_' + escape(foo), 'n');
			} else {
				setSessionVar('show_' + escape(foo), 'y');
			}
		} else {
			if ($jq("#" + foo).css("display") == "none") {
				setSessionVar('show_' + escape(foo), 'y');
				showJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
			}
			else {
				setSessionVar('show_' + escape(foo), 'n');
				hideJQ("#" + foo, jqueryTiki.effect, jqueryTiki.effect_speed, jqueryTiki.effect_direction);
			}
		}
	};

	// handle JQ effects
	showJQ = function (selector, effect, speed, dir) {
		if (effect == 'none') {
			$jq(selector).show();
		} else if (effect == '' || effect == 'normal') {
			$jq(selector).show(speed);
		} else if (effect == 'slide') {
			$jq(selector).slideDown(speed);
		} else if (effect == 'fade') {
			$jq(selector).fadeIn(speed);
		} else if (effect.match(/(.*)_ui$/).length > 1) {
			$jq(selector).show(effect.match(/(.*)_ui$/)[1], {direction: dir }, speed);
		} else {
			$jq(selector).show();
		}
	};

	hideJQ = function (selector, effect, speed, dir) {
		if (effect == 'none') {
			$jq(selector).hide();
		} else if (effect == '' || effect == 'normal') {
			$jq(selector).hide(speed);
		} else if (effect == 'slide') {
			$jq(selector).slideUp(speed);
		} else if (effect == 'fade') {
			$jq(selector).fadeOut(speed);
		} else if (effect.match(/(.*)_ui$/).length > 1) {
			$jq(selector).hide(effect.match(/(.*)_ui$/)[1], {direction: dir }, speed);
		} else {
			$jq(selector).hide();
		}
	};

	// tooltip functions and setup
	if (jqueryTiki.tooltips) {	// apply "cluetips" to all .tips class anchors
		$jq('.tips').cluetip({splitTitle: '|', showTitle: false, width: '150px', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}});
		$jq('.titletips').cluetip({splitTitle: '|', cluezIndex: 400});
		$jq('.tikihelp').cluetip({splitTitle: ':', width: '150px', cluezIndex: 400, fx: {open: 'fadeIn', openSpeed: 'fast'}});

		// override overlib - TODO optimise JQuery calls
		convertOverlib = function (element, tip, options) {	// process overlib event fn to cluetip

			tip = tip.replace(/return overlib\((.*)\).*/gi, '$1');	// remove function wrapper
			var prefix = "";
			var strStart = 0;
			var strEnd = tip.length;

			if (tip.substring(0,1) == "'") {				// overlib is called with a string, then a few "constant" params
				strStart = 1;								// this bit extracts the first string (couldn't get a regexp to work reliably)
				strEnd = tip.lastIndexOf("'");
			} else if (tip.substring(0,1) == '"') {
				strStart = 1;
				strEnd = tip.lastIndexOf('"');
			}

			// process parameters
			params = tip.substring(strEnd-1, tip.length).toLowerCase();	// possibly: sticky,autostatus,autostatuscap,fullhtml,hauto,vauto,closeclick,wrap,followmouse,mouseoff,compatmode
			if (params.indexOf('sticky') > -1) { options.sticky = true; } else { options.sticky = false; }
			//if (params.indexOf('mouseoff') > -1) {}	// TODO?
			if (params.indexOf('fullhtml') > -1) { options.cluetipClass = 'fullhtml'; } else { options.cluetipClass = 'default'; }
			options.splitTitle = '|';
			options.showTitle = false;
			options.width = 'auto';		// this don't work :(
			options.cluezIndex = 400;
			options.dropShadow = true;
			options.fx = {open: 'fadeIn', openSpeed: 'fast'};
			options.closeText = 'x';
			options.mouseOutClose = true;

			// attach new tip
			tip = tip.substring(strStart, strEnd);		// trim quotes
			tip = tip.replace(/\\n/g, '');			// remove newlines
			tip = tip.replace(/\\/g, '');				// remove backslashes

			// hack to calculate div width
			var el = document.createElement('DIV');
			$jq(el).css('position', 'absolute').css('visibility', 'hidden');
			document.body.appendChild(el);
			$jq(el).html(tip);
			if ($jq(el).width() > $jq(window).width()) {
				$jq(el).width($jq(window).width() * 0.8);
			}
			options.width = $jq(el).width();
			document.body.removeChild(el);

			prefix = "|";
			$jq(element).attr('title', prefix + tip);

			// options.sticky = true; useful for css work
			$jq(element).cluetip(options);
		}

		$jq("[onmouseover*='overlib(']").each(function() {
			tip = $jq(this)[0].getAttribute('onmouseover');			// use the html call to get the text, not the fn
			convertOverlib(this, tip, {});
		});

		$jq("[onclick*='overlib(']").each(function() {			// TODO refactor!!!!
			tip = $jq(this)[0].getAttribute('onclick');			// use the html call to get the text, not the fn
			convertOverlib(this, tip, {activation: 'click'});
		});

		// nobble overlib funcs
		overlib = function() {};
		nd = function() {};
	}

	// superfish setup (CSS menu effects)
	if (jqueryTiki.superfish) {
		$jq('ul.cssmenu_horiz').superfish({
			animation: {opacity:'show', height:'show'},	// fade-in and slide-down animation
			speed: 'fast'								// faster animation speed
		});
		$jq('ul.cssmenu_vert').superfish({
			animation: {opacity:'show', height:'show'},	// fade-in and slide-down animation
			speed: 'fast'								// faster animation speed
		});
	}

	// tablesorter setup (sortable tables?)
	if (jqueryTiki.tablesorter) {
		$jq('.sortable').tablesorter({
			widthFixed: true							// ??
//			widgets: ['zebra'],							// stripes (coming soon)
		});
	}
});		// end $jq(document).ready

/* Autocomplete assistants */

function parseAutoJSON(data) {
	var parsed = [];
	return $jq.map(data, function(row) {
		return {
			data: row,
			value: row,
			result: row
		}
	});
}

<|endoftext|>


<commit_before>/*
  FlagstoneJS v3.5.0
  (c) 2015-2017 Depth Development. http://depthdev.com
  License: MIT
*/
!function(e,t){"use strict";e.flagstone=function(n){function r(n){function r(){for(var e=0,t=w.length;e<t;e++)Math.random()<F&&w.splice(e,0,!1)}function a(){L.style.visibility="hidden"}function o(){var t=[x],n=0,r=C.length;for(O=[];n<r;n++){if(n<x)w[n]?(w[n].style.top=p+"px",w[n].style[A]=k*n+(n?D*n+p:p)+"px",H&&(w[n].style.height=w[n].style.width),t[n]=C[n]+p,V(w[n],n),O.push([w[n]])):x>1&&(t[n]=k+p);else{var a=Math.min.apply(null,t),o=t.indexOf(a);w[n]?(w[n].style.top=a+D+"px",w[n].style[A]=k*o+(o?D*o+p:p)+"px",H&&(w[n].style.height=w[n].style.width),t[o]+=C[n]+D,V(w[n],n),O[o].push(w[n])):x>1&&(t[o]+=k+D)}L.style.height=(Math.max.apply(null,t)||C[0]+p)+p+"px"}e.setTimeout(function(){L.style.visibility="visible"})}function s(t){if(w.length){E=L.getBoundingClientRect().width,E<y+(p?2*p:0)&&(E=y),T=Math.floor(E/y),x=T>b?b:T,k=E/x-(D*(x-1)+2*p)/x,C=[];for(var n=0,r=w.length;n<r;n++)w[n]&&(w[n].style.width=k+"px",w[n].style.marginTop="0px"),C.push(H||!w[n]?k:w[n].offsetHeight);E===L.getBoundingClientRect().width||t?o():s(!0),t||e.setTimeout(function(){s(!0)},R)}}function i(){var t=Date.now(),n=L.getElementsByTagName("img");n.length&&!function(){var r=e.setInterval(function(){for(var a=[],o=0,i=n.length;o<i;o++)a[o]=n[o].naturalHeight;(a.indexOf(0)===-1||t+I<Date.now())&&(e.clearInterval(r),e.setTimeout(function(){s(!0)}))},W)}()}function g(t){if("keydown"!==t.type||13===t.keyCode||32===t.keyCode){for(var n=t.target;n&&!n.classList.contains(B);)n=n.parentElement;L.removeChild(n),e.MutationObserver||ee()}}function l(t){"keydown"===t.type&&13!==t.keyCode&&32!==t.keyCode||e.setTimeout(s,Y)}function d(t){function n(){var t=r.getBoundingClientRect().height+a;for(i=0;i<l;i++)o[i].style.marginTop=t-c+"px";J=e[(K?"request":"cancel")+"AnimationFrame"](n)}for(var r=t;r&&!r.classList.contains(B);)r=r.parentElement;for(var a=e.parseFloat(r.style.top),o=[],s=!1,i=0,g=0,l=O.length,d=0;i<l&&!s;i++)for(g=0,d=O[i].length;g<d;g++)s&&o.push(O[i][g]),O[i][g]===r&&(s=!0);if(o.length){var c=e.parseFloat(o[0].style.top)-D;l=o.length,K=!1,e.cancelAnimationFrame(J),e.clearTimeout(U),K=!0,J=e.requestAnimationFrame(n),U=e.setTimeout(function(){K=!1,e.cancelAnimationFrame(J)},G)}}function c(e){"keydown"===e.type&&13!==e.keyCode&&32!==e.keyCode||d(e.target)}function f(){e.clearTimeout(Z),Z=e.setTimeout(s,q)}function v(){a(),e.clearTimeout($),$=e.setTimeout(ee)}function m(){e.removeEventListener("resize",f),t.head.removeChild(t.getElementById("flagstone-"+S+"-styles"))}function u(e){e.margin||0===e.margin?(p=e.margin,D=e.margin):(p=e.bedPadding||p,D=e.stonesMargin||D),y=e.minWidth||y,b=e.maxColumns||b,X=e.dragAndDrop===!0||e.dragAndDrop===!1?e.dragAndDrop:X,j=e.dropCallback||j,V=e.callback||V,ee()}var S=e.flagstone.index,h=n?n.nodeName?{elem:n}:n:{elem:t.getElementsByClassName("flagstone")[0]},L=h.elem,p=h.margin||0===h.margin?h.margin:h.bedPadding||0===h.bedPadding?h.bedPadding:10,E=0,y=h.minWidth||280,b=h.maxColumns||5,T=0,x=0,w=[],D=h.margin||0===h.margin?h.margin:h.stonesMargin||0===h.stonesMargin?h.stonesMargin:10,k=E/x-D*(x+1)/x,C=[],O=[],B="flagstone-"+S+"-bed__stone",M=h.flow,A=h.direction?h.direction.toLowerCase():"left",z=h.random,F=h.spaceFrequency||.4,P=h.space,R=h.animationDuration||0,N=h.animationDuration?h.animationDuration/1e3:0,_=h.animationTimingFunction||"linear",q=h.resizeDelay||0===h.resizeDelay?h.resizeDelay:250,H=h.square,I=h.imagesLoadedQueryDuration||2500,W=h.imagesLoadedQueryFrequency||100,X=h.dragAndDrop,Q=h.dragAndDropAutoDelay,j=h.dropCallback||function(){return!0},Y=h.eventResetDelay||0,G=h.eventResizeHeightDuration||0,J=null,K=!1,U=null,V=h.callback||function(){},Z=null,$=null,ee=null,te={targetElem:null,dragStone:null,targetStone:null,targetStoneOverLeft:0,autoDropTimer:null,autoDrop:function(){te.targetStone.classList.contains(B)&&(te.targetStoneOverLeft?te.dragStone!==te.targetStone.previousElementSibling&&(te.targetStone.parentElement.insertBefore(te.dragStone,te.targetStone),te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.remove("flagstone-dragover")):te.dragStone!==te.targetStone.nextElementSibling&&(te.targetStone.parentElement.insertBefore(te.dragStone,te.targetStone.nextElementSibling),te.targetStone.classList.remove("flagstone-right"),te.targetStone.classList.remove("flagstone-dragover")),e.clearTimeout(te.autoDropTimer),te.autoDropTimer=e.setTimeout(te.autoDrop,Q))},clear:function(){te.dragStone&&(te.dragStone.classList.remove("flagstone-drag"),te.dragStone=null),te.targetStone&&(te.targetStoneOverLeft=0,te.targetStone.classList.remove("flagstone-dragover"),te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.remove("flagstone-right"),te.targetStone=null),L.classList.remove("flagstone-dragover")},getTargetElem:function(e){for(te.targetElem=e.target instanceof HTMLElement?e.target:e.target.parentElement;te.targetElem&&!te.targetElem.classList.contains("flagstone-drag-handle");)te.targetElem=te.targetElem.parentElement;if(te.targetElem)for(te.dragStone=te.targetElem;te.dragStone&&!te.dragStone.classList.contains(B);)te.dragStone=te.dragStone.parentElement},mousedown:function(e){te.getTargetElem(e)},dragStart:function(e){return!!te.targetElem&&(te.dragStone.classList.add("flagstone-drag"),void(e.dataTransfer&&e.dataTransfer.setData("text",this.id)))},touchStart:function(e){te.getTargetElem(e),te.dragStart(e)},dragEnter:function(t){t.preventDefault(),t.stopPropagation(),this!==te.dragStone&&this!==te.targetStone&&this!==L&&(e.clearTimeout(te.autoDropTimer),te.autoDropTimer=e.setTimeout(te.autoDrop,Q))},touchMove:function(e){if(!te.dragStone)return!1;e.preventDefault(),e.stopPropagation();for(var n=t.elementFromPoint(e.touches[0].clientX,e.touches[0].clientY),r=n;r&&!r.classList.contains(B);)r=r.parentElement;r?(L.classList.remove("flagstone-dragover"),te.targetStoneOverLeft=r.getBoundingClientRect().left+r.offsetWidth/2>e.touches[0].clientX,te.targetStone&&te.targetStone!==r&&(te.targetStone.classList.remove("flagstone-dragover"),te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.remove("flagstone-right")),te.targetStone=r,te.targetStone.classList.contains("flagstone-lock")||(te.targetStone.classList.add("flagstone-dragover"),te.targetStoneOverLeft?(te.targetStone.classList.remove("flagstone-right"),te.targetStone.classList.add("flagstone-left")):(te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.add("flagstone-right")))):n===L&&(te.targetStone.classList.remove("flagstone-dragover"),te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.remove("flagstone-right"),L.classList.add("flagstone-dragover"),te.targetStone=L)},dragOver:function(e){return!!te.dragStone&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",void(this!==te.dragStone&&this.classList.contains(B)?(te.targetStone=this,te.targetStone.classList.add("flagstone-dragover"),te.targetStoneOverLeft=this.getBoundingClientRect().left+this.offsetWidth/2>e.clientX,te.targetStoneOverLeft?(te.targetStone.classList.remove("flagstone-right"),te.targetStone.classList.add("flagstone-left")):(te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.add("flagstone-right")),this.classList.remove("flagstone-dragover"),te.targetStone!==L&&L.classList.remove("flagstone-dragover")):this===L&&this.classList.add("flagstone-dragover")))},dragEnd:function(){te.clear()},touchEnd:function(){te.dragStone&&te.targetStone&&!te.targetStone.classList.contains("flagstone-lock")&&j(te.dropStone,te.targetStone)&&(te.targetStone===L?L.appendChild(te.dragStone):te.targetStoneOverLeft?L.insertBefore(te.dragStone,te.targetStone):L.insertBefore(te.dragStone,te.targetStone.nextElementSibling)),te.clear()},dragLeave:function(){te.targetStone&&(te.targetStone.classList.remove("flagstone-dragover"),te.targetStone.classList.remove("flagstone-left"),te.targetStone.classList.remove("flagstone-right"),L.classList.remove("flagstone-dragover"))},drop:function(t){if(!te.dragStone)return!1;if(t.stopPropagation(),e.clearTimeout(te.autoDropTimer),te.dragStone!==this&&(this.classList.contains(B)||this===L)){if(te.targetStone=this,te.targetStone===L){if(!j(te.dragStone,te.targetStone))return te.clear(),!1;te.targetStone.appendChild(te.dragStone)}else if(te.targetStoneOverLeft){if(!j(te.dragStone,te.targetStone))return te.clear(),!1;te.targetStone.parentElement.insertBefore(te.dragStone,te.targetStone)}else{if(!j(te.dragStone,te.targetStone.nextElementSibling))return te.clear(),!1;te.targetStone.parentElement.insertBefore(te.dragStone,te.targetStone.nextElementSibling)}te.clear(),e.MutationObserver||ee()}return!1}};return ee=function(){w=Array.prototype.slice.call(L.children);for(var t=0,n=w.length;t<n;t++)w[t].classList.add(B);for(t=0;t<n;t++)w[t].setAttribute("draggable","false"),w[t].removeEventListener("mousedown",te.mousedown),w[t].removeEventListener("dragstart",te.dragStart),w[t].removeEventListener("touchstart",te.touchStart),w[t].removeEventListener("touchmove",te.touchMove),w[t].removeEventListener("dragover",te.dragOver),w[t].removeEventListener("dragleave",te.dragLeave),w[t].removeEventListener("dragend",te.dragEnd),w[t].removeEventListener("touchend",te.touchEnd),w[t].removeEventListener("drop",te.drop),w[t].removeEventListener("touchend",te.drop),w[t].removeEventListener("dragenter",te.dragEnter),L.removeEventListener("dragover",te.dragOver),L.removeEventListener("drop",te.drop);if(X)for(t=0;t<n;t++)w[t].classList.contains("flagstone-lock")||(w[t].setAttribute("draggable","true"),w[t].addEventListener("mousedown",te.mousedown),w[t].addEventListener("dragstart",te.dragStart),w[t].addEventListener("touchstart",te.touchStart),w[t].addEventListener("touchmove",te.touchMove),w[t].addEventListener("dragover",te.dragOver),w[t].addEventListener("dragleave",te.dragLeave),w[t].addEventListener("dragend",te.dragEnd),w[t].addEventListener("touchend",te.touchEnd),w[t].addEventListener("drop",te.drop),w[t].addEventListener("touchend",te.drop),Q&&w[t].addEventListener("dragenter",te.dragEnter),L.addEventListener("dragover",te.dragOver),L.addEventListener("drop",te.drop));(z||P)&&(z&&w.sort(function(){return.5-Math.random()}),P&&r());var a=L.getElementsByClassName("flagstone-remove");for(t=0,n=a.length;t<n;t++)a[t].removeEventListener("click",g),a[t].addEventListener("click",g),a[t].removeEventListener("keydown",g),a[t].addEventListener("keydown",g);for(a=L.getElementsByClassName("flagstone-reset"),t=0,n=a.length;t<n;t++)a[t].removeEventListener("click",l),a[t].addEventListener("click",l),a[t].removeEventListener("keydown",l),a[t].addEventListener("keydown",l);for(a=L.getElementsByClassName("flagstone-resize-height"),t=0,n=a.length;t<n;t++)a[t].removeEventListener("click",c),a[t].addEventListener("click",c),a[t].removeEventListener("keydown",c),a[t].addEventListener("keydown",c);s(),R&&e.setTimeout(i,R),e.setTimeout(function(){s(!0)},R)},function(){if(L.classList.add("flagstone-"+S+"-bed"),!t.getElementById("flagstone-"+S+"-styles")){var n=".flagstone-"+S+"-bed{box-sizing:border-box;list-style-type:none;overflow:hidden;position:relative;min-width:"+(y+2*p)+"px;}",r=".flagstone-"+S+"-bed__stone{box-sizing:border-box;position:absolute;top:0px;"+A+":0px;margin:0;}",a=".flagstone-"+S+"-bed__stone{transition:top "+N+"s "+_+","+A+" "+N+"s "+_+(M?",width "+N+"s "+_:"")+";}",o=n+r+a,s=t.createElement("style");s.type="text/css",s.id="flagstone-"+S+"-styles",s.appendChild(t.createTextNode(o)),t.head.appendChild(s)}if(ee(),e.removeEventListener("resize",f),e.addEventListener("resize",f),e.MutationObserver){var i=new MutationObserver(v);i.observe(L,{childList:!0})}}(),{adjust:u,destroy:m,resizeHeight:d,hide:a,reset:f,hardReset:ee}}return e.flagstone.index++,new r(n)},e.flagstone.index=-1}(window,document);<commit_msg>Delete flagstone-3.5.0.min.js<commit_after><|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2012 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0
 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
 * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
 *
 * Contributors: IBM Corporation - initial API and implementation
 ******************************************************************************/
/*global exports module define setTimeout*/

(function(root, factory) { // UMD
    if (typeof define === "function" && define.amd) { //$NON-NLS-0$
        define(factory);
    } else if (typeof exports === "object") { //$NON-NLS-0$
        module.exports = factory();
    } else {
        root.orion = root.orion || {};
        root.orion.Deferred = factory();
    }
}(this, function() {
    var queue = [],
        running = false;

    function run() {
        var fn;
        while ((fn = queue.shift())) {
            fn();
        }
        running = false;
    }

    function enqueue(fn) {
        queue.push(fn);
        if (!running) {
            running = true;
            setTimeout(run, 0);
        }
    }

    function noReturn(fn) {
        return function() {
            fn.apply(undefined, arguments);
        };
    }

    /**
     * @name orion.Promise
     * @class Interface representing an eventual value.
     * @description Promise is an interface that represents an eventual value returned from the single completion of an operation.
     *
     *
For a concrete class that implements Promise and provides additional API, see {@link orion.Deferred}.

     * @see orion.Deferred
     * @see orion.Deferred#promise
     */
    /**
     * @name then
     * @function
     * @memberOf orion.Promise.prototype
     * @description Adds handlers to be called on fulfillment or progress of this promise.
     * @param {Function} [onResolve] Called when this promise is resolved.
     * @param {Function} [onReject] Called when this promise is rejected.
     * @param {Function} [onProgress] May be called to report progress events on this promise.
     * @returns {orion.Promise} A new promise that is fulfilled when the given onResolve or onReject
     * callback is finished. The callback's return value gives the fulfillment value of the returned promise.
     */
    /**
     * Cancels this promise.
     * @name cancel
     * @function
     * @memberOf orion.Promise.prototype
     * @param {Object} reason The reason for canceling this promise.
     * @param {Boolean} [strict]
     */

    /**
     * @name orion.Deferred
     * @borrows orion.Promise#then as #then
     * @borrows orion.Promise#cancel as #cancel
     * @class Provides abstraction over asynchronous operations.
     * @description Deferred provides abstraction over asynchronous operations.
     *
     *
Because Deferred implements the {@link orion.Promise} interface, a Deferred may be used anywhere a Promise is called for.
     * However, in most such cases it is recommended to use the Deferred's {@link #promise} field instead, which exposes a
     * simplified, minimally Promises/A+-compliant interface to callers.

     */
    function Deferred() {
        var result, state, listeners = [],
            _this = this,
            _protected = {};

        Object.defineProperty(this, "_protected", {
            value: function(secret) {
                if (secret !== queue) {
                    throw new Error("protected");
                }
                return _protected;
            }
        });

        function notify() {
            var listener;
            while ((listener = listeners.shift())) {
                var deferred = listener.deferred;
                var methodName = state === "fulfilled" ? "resolve" : "reject"; //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$
                if (typeof listener[methodName] === "function") { //$NON-NLS-0$
                    try {
                        var fn = listener[methodName];
                        var listenerResult = fn(result);
                        var listenerThen = listenerResult && (typeof listenerResult === "object" || typeof listenerResult === "function") && listenerResult.then;
                        if (typeof listenerThen === "function") {
                            if (listenerResult === deferred.promise) {
                                deferred.reject(new TypeError());
                            } else {
                                var listenerResultCancel = listenerResult.cancel;
                                if (typeof listenerResultCancel === "function") {
                                    deferred._protected(queue).parentCancel = listenerResultCancel.bind(listenerResult);
                                } else {
                                    delete deferred._protected(queue).parentCancel;
                                }
                                listenerThen.call(listenerResult, noReturn(deferred.resolve), noReturn(deferred.reject), noReturn(deferred.progress));
                            }
                        } else {
                            deferred.resolve(listenerResult);
                        }
                    } catch (e) {
                        deferred.reject(e);
                    }
                } else {
                    deferred[methodName](result);
                }
            }
        }

        function _reject(error) {
            delete _protected.parentCancel;
            state = "rejected";
            result = error;
            if (listeners.length) {
                enqueue(notify);
            }
        }

        function _resolve(value) {
            var called = false;

            function once(fn) {
                return function(value) {
                    if (!called) {
                        called = true;
                        fn(value);
                    }
                };
            }
            delete _protected.parentCancel;
            try {
                var valueThen = value && (typeof value === "object" || typeof value === "function") && value.then;
                if (typeof valueThen === "function") {
                    if (value === _this) {
                        _reject(new TypeError());
                    } else {
                        state = "assumed";
                        var valueCancel = value && value.cancel;
                        if (typeof valueCancel !== "function") {
                            var deferred = new Deferred();
                            value = deferred.promise;
                            try {
                                valueThen(deferred.resolve, deferred.reject, deferred.progress);
                            } catch (thenError) {
                                deferred.reject(thenError);
                            }
                            valueCancel = value.cancel;
                            valueThen = value.then;
                        }
                        result = value;
                        valueThen.call(value, once(_resolve), once(_reject));
                        _protected.parentCancel = valueCancel.bind(value);
                    }
                } else {
                    state = "fulfilled";
                    result = value;
                    if (listeners.length) {
                        enqueue(notify);
                    }
                }
            } catch (error) {
                once(_reject)(error);
            }
        }

        function cancel() {
            var parentCancel = _protected.parentCancel;
            if (parentCancel) {
                delete _protected.parentCancel;
                parentCancel();
            } else if (!state) {
                var cancelError = new Error("Cancel");
                cancelError.name = "Cancel";
                _reject(cancelError);
            }
        }

        /**
         * Resolves this Deferred.
         * @name resolve
         * @function
         * @memberOf orion.Deferred.prototype
         * @param {Object} value
         * @returns {orion.Promise}
         */
        this.resolve = function(value) {
            if (!state) {
                _resolve(value);
            }
            return _this;
        };

        /**
         * Rejects this Deferred.
         * @name reject
         * @function
         * @memberOf orion.Deferred.prototype
         * @param {Object} error
         * @param {Boolean} [strict]
         * @returns {orion.Promise}
         */
        this.reject = function(error) {
            if (!state) {
                _reject(error);
            }
            return _this;
        };

        /**
         * Notifies listeners of progress on this Deferred.
         * @name progress
         * @function
         * @memberOf orion.Deferred.prototype
         * @param {Object} update The progress update.
         * @returns {orion.Promise}
         */
        this.progress = function(update) {
            if (!state) {
                listeners.forEach(function(listener) {
                    if (listener.progress) {
                        try {
                            listener.progress(update);
                        } catch (ignore) {
                            // ignore
                        }
                    }
                });
            }
            return _this.promise;
        };

        this.cancel = function() {
            if (_protected.parentCancel) {
                setTimeout(cancel, 0);
            } else {
                cancel();
            }

            return _this;
        };

        // Note: "then" ALWAYS returns before having onResolve or onReject called as per http://promises-aplus.github.com/promises-spec/
        this.then = function(onFulfill, onReject, onProgress) {
            var listener = {
                resolve: onFulfill,
                reject: onReject,
                progress: onProgress,
                deferred: new Deferred()
            };
            listeners.push(listener);
            listener.deferred._protected(queue).parentCancel = _this.promise.cancel.bind(_this);
            if (state === "fulfilled" || state === "rejected") {
                enqueue(notify);
            }
            return listener.deferred.promise;
        };

        /**
         * The promise exposed by this Deferred.
         * @name promise
         * @field
         * @memberOf orion.Deferred.prototype
         * @type orion.Promise
         */
        this.promise = {
            then: _this.then,
            cancel: _this.cancel
        };
    }

    /**
     * Returns a promise that represents the outcome of all the input promises.
     *
When all is called with a single parameter, the returned promise has <dfn>eager</dfn> semantics,
     * meaning that if any input promise rejects, the returned promise immediately rejects, without waiting for the rest of the
     * input promises to fulfill.

     *
     * To obtain <dfn>lazy</dfn> semantics (meaning the returned promise waits for every input promise to fulfill), pass the
     * optional parameter optOnError.
     * @name all
     * @function
     * @memberOf orion.Deferred
     * @static
     * @param {orion.Promise[]} promises The input promises.
     * @param {Function} [optOnError] Handles a rejected input promise. optOnError is invoked for every rejected
     * input promise, and is passed the reason the input promise was rejected.
optOnError can return a value, which
     * allows it to act as a transformer: the return value serves as the final fulfillment value of the rejected promise in the
     * results array generated by all.
     * @returns {orion.Promise} A new promise. The returned promise is generally fulfilled to an Array whose elements
     * give the fulfillment values of the input promises.
However, if an input promise rejects and eager semantics is used, the
     * returned promise will instead be fulfilled to a single error value.

     */
    Deferred.all = function(promises, optOnError) {
        var count = promises.length,
            result = [],
            rejected = false,
            deferred = new Deferred();

        deferred.then(undefined, function() {
            rejected = true;
            promises.forEach(function(promise) {
                if (promise.cancel) {
                    promise.cancel();
                }
            });
        });

        function onResolve(i, value) {
            if (!rejected) {
                result[i] = value;
                if (--count === 0) {
                    deferred.resolve(result);
                }
            }
        }

        function onReject(i, error) {
            if (!rejected) {
                if (optOnError) {
                    try {
                        onResolve(i, optOnError(error));
                        return;
                    } catch (e) {
                        error = e;
                    }
                }
                deferred.reject(error);
            }
        }

        if (count === 0) {
            deferred.resolve(result);
        } else {
            promises.forEach(function(promise, i) {
                promise.then(onResolve.bind(undefined, i), onReject.bind(undefined, i));
            });
        }
        return deferred.promise;
    };

    /**
     * Applies callbacks to a promise or to a regular object.
     * @name when
     * @function
     * @memberOf orion.Deferred
     * @static
     * @param {Object|orion.Promise} value Either a {@link orion.Promise}, or a normal value.
     * @param {Function} onResolve Called when the value promise is resolved. If value is not a promise,
     * this function is called immediately.
     * @param {Function} onReject Called when the value promise is rejected. If value is not a promise,
     * this function is never called.
     * @param {Function} onProgress Called when the value promise provides a progress update. If value is
     * not a promise, this function is never called.
     * @returns {orion.Promise} A new promise.
     */
    Deferred.when = function(value, onResolve, onReject, onProgress) {
        var promise, deferred;
        if (value && typeof value.then === "function") { //$NON-NLS-0$
            promise = value;
        } else {
            deferred = new Deferred();
            deferred.resolve(value);
            promise = deferred.promise;
        }
        return promise.then(onResolve, onReject, onProgress);
    };

    return Deferred;
}));<commit_msg>Update Deferred from upstream to pick up nextTick fix https://bugs.eclipse.org/bugs/show_bug.cgi?id=429270<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2012 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License v1.0
 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
 * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
 *
 * Contributors: IBM Corporation - initial API and implementation
 ******************************************************************************/
/*global exports module define setTimeout process document MutationObserver*/

(function(root, factory) { // UMD
    if (typeof define === "function" && define.amd) { //$NON-NLS-0$
        define(factory);
    } else if (typeof exports === "object") { //$NON-NLS-0$
        module.exports = factory();
    } else {
        root.orion = root.orion || {};
        root.orion.Deferred = factory();
    }
}(this, function() {
    var queue = [],
        running = false;

    function run() {
        var fn;
        while ((fn = queue.shift())) {
            fn();
        }
        running = false;
    }

	var runAsync = (function() {
		if (typeof process !== "undefined" && typeof process.nextTick === "function") {
			var nextTick = process.nextTick;
    		return function() {
    			nextTick(run);
    		};
		} else if (typeof MutationObserver === "function") {
			var div = document.createElement("div");
			var observer = new MutationObserver(run);
			observer.observe(div, {
            	attributes: true
        	});
        	return function() {
        		div.setAttribute("class", "_tick");
        	};
		}
		return function() {
			setTimeout(run, 0);
		};
	})();

    function enqueue(fn) {
        queue.push(fn);
        if (!running) {
            running = true;
            runAsync();
        }
    }

    function noReturn(fn) {
        return function() {
            fn.apply(undefined, arguments);
        };
    }

    /**
     * @name orion.Promise
     * @class Interface representing an eventual value.
     * @description Promise is an interface that represents an eventual value returned from the single completion of an operation.
     *
     *
For a concrete class that implements Promise and provides additional API, see {@link orion.Deferred}.

     * @see orion.Deferred
     * @see orion.Deferred#promise
     */
    /**
     * @name then
     * @function
     * @memberOf orion.Promise.prototype
     * @description Adds handlers to be called on fulfillment or progress of this promise.
     * @param {Function} [onResolve] Called when this promise is resolved.
     * @param {Function} [onReject] Called when this promise is rejected.
     * @param {Function} [onProgress] May be called to report progress events on this promise.
     * @returns {orion.Promise} A new promise that is fulfilled when the given onResolve or onReject
     * callback is finished. The callback's return value gives the fulfillment value of the returned promise.
     */
    /**
     * Cancels this promise.
     * @name cancel
     * @function
     * @memberOf orion.Promise.prototype
     * @param {Object} reason The reason for canceling this promise.
     * @param {Boolean} [strict]
     */

    /**
     * @name orion.Deferred
     * @borrows orion.Promise#then as #then
     * @borrows orion.Promise#cancel as #cancel
     * @class Provides abstraction over asynchronous operations.
     * @description Deferred provides abstraction over asynchronous operations.
     *
     *
Because Deferred implements the {@link orion.Promise} interface, a Deferred may be used anywhere a Promise is called for.
     * However, in most such cases it is recommended to use the Deferred's {@link #promise} field instead, which exposes a
     * simplified, minimally Promises/A+-compliant interface to callers.

     */
    function Deferred() {
        var result, state, listeners = [],
            _this = this,
            _protected = {};

        Object.defineProperty(this, "_protected", {
            value: function(secret) {
                if (secret !== queue) {
                    throw new Error("protected");
                }
                return _protected;
            }
        });

        function notify() {
            var listener;
            while ((listener = listeners.shift())) {
                var deferred = listener.deferred;
                var methodName = state === "fulfilled" ? "resolve" : "reject"; //$NON-NLS-0$ //$NON-NLS-1$ //$NON-NLS-2$
                if (typeof listener[methodName] === "function") { //$NON-NLS-0$
                    try {
                        var fn = listener[methodName];
                        var listenerResult = fn(result);
                        var listenerThen = listenerResult && (typeof listenerResult === "object" || typeof listenerResult === "function") && listenerResult.then;
                        if (typeof listenerThen === "function") {
                            if (listenerResult === deferred.promise) {
                                deferred.reject(new TypeError());
                            } else {
                                var listenerResultCancel = listenerResult.cancel;
                                if (typeof listenerResultCancel === "function") {
                                    deferred._protected(queue).parentCancel = listenerResultCancel.bind(listenerResult);
                                } else {
                                    delete deferred._protected(queue).parentCancel;
                                }
                                listenerThen.call(listenerResult, noReturn(deferred.resolve), noReturn(deferred.reject), noReturn(deferred.progress));
                            }
                        } else {
                            deferred.resolve(listenerResult);
                        }
                    } catch (e) {
                        deferred.reject(e);
                    }
                } else {
                    deferred[methodName](result);
                }
            }
        }

        function _reject(error) {
            delete _protected.parentCancel;
            state = "rejected";
            result = error;
            if (listeners.length) {
                enqueue(notify);
            }
        }

        function _resolve(value) {
            var called = false;

            function once(fn) {
                return function(value) {
                    if (!called) {
                        called = true;
                        fn(value);
                    }
                };
            }
            delete _protected.parentCancel;
            try {
                var valueThen = value && (typeof value === "object" || typeof value === "function") && value.then;
                if (typeof valueThen === "function") {
                    if (value === _this) {
                        _reject(new TypeError());
                    } else {
                        state = "assumed";
                        var valueCancel = value && value.cancel;
                        if (typeof valueCancel !== "function") {
                            var deferred = new Deferred();
                            value = deferred.promise;
                            try {
                                valueThen(deferred.resolve, deferred.reject, deferred.progress);
                            } catch (thenError) {
                                deferred.reject(thenError);
                            }
                            valueCancel = value.cancel;
                            valueThen = value.then;
                        }
                        result = value;
                        valueThen.call(value, once(_resolve), once(_reject));
                        _protected.parentCancel = valueCancel.bind(value);
                    }
                } else {
                    state = "fulfilled";
                    result = value;
                    if (listeners.length) {
                        enqueue(notify);
                    }
                }
            } catch (error) {
                once(_reject)(error);
            }
        }

        function cancel() {
            var parentCancel = _protected.parentCancel;
            if (parentCancel) {
                delete _protected.parentCancel;
                parentCancel();
            } else if (!state) {
                var cancelError = new Error("Cancel");
                cancelError.name = "Cancel";
                _reject(cancelError);
            }
        }

        /**
         * Resolves this Deferred.
         * @name resolve
         * @function
         * @memberOf orion.Deferred.prototype
         * @param {Object} value
         * @returns {orion.Promise}
         */
        this.resolve = function(value) {
            if (!state) {
                _resolve(value);
            }
            return _this;
        };

        /**
         * Rejects this Deferred.
         * @name reject
         * @function
         * @memberOf orion.Deferred.prototype
         * @param {Object} error
         * @param {Boolean} [strict]
         * @returns {orion.Promise}
         */
        this.reject = function(error) {
            if (!state) {
                _reject(error);
            }
            return _this;
        };

        /**
         * Notifies listeners of progress on this Deferred.
         * @name progress
         * @function
         * @memberOf orion.Deferred.prototype
         * @param {Object} update The progress update.
         * @returns {orion.Promise}
         */
        this.progress = function(update) {
            if (!state) {
                listeners.forEach(function(listener) {
                    if (listener.progress) {
                        try {
                            listener.progress(update);
                        } catch (ignore) {
                            // ignore
                        }
                    }
                });
            }
            return _this.promise;
        };

        this.cancel = function() {
            if (_protected.parentCancel) {
                setTimeout(cancel, 0);
            } else {
                cancel();
            }

            return _this;
        };

        // Note: "then" ALWAYS returns before having onResolve or onReject called as per http://promises-aplus.github.com/promises-spec/
        this.then = function(onFulfill, onReject, onProgress) {
            var listener = {
                resolve: onFulfill,
                reject: onReject,
                progress: onProgress,
                deferred: new Deferred()
            };
            listeners.push(listener);
            listener.deferred._protected(queue).parentCancel = _this.promise.cancel.bind(_this);
            if (state === "fulfilled" || state === "rejected") {
                enqueue(notify);
            }
            return listener.deferred.promise;
        };

        /**
         * The promise exposed by this Deferred.
         * @name promise
         * @field
         * @memberOf orion.Deferred.prototype
         * @type orion.Promise
         */
        this.promise = {
            then: _this.then,
            cancel: _this.cancel
        };
    }

    /**
     * Returns a promise that represents the outcome of all the input promises.
     *
When all is called with a single parameter, the returned promise has <dfn>eager</dfn> semantics,
     * meaning that if any input promise rejects, the returned promise immediately rejects, without waiting for the rest of the
     * input promises to fulfill.

     *
     * To obtain <dfn>lazy</dfn> semantics (meaning the returned promise waits for every input promise to fulfill), pass the
     * optional parameter optOnError.
     * @name all
     * @function
     * @memberOf orion.Deferred
     * @static
     * @param {orion.Promise[]} promises The input promises.
     * @param {Function} [optOnError] Handles a rejected input promise. optOnError is invoked for every rejected
     * input promise, and is passed the reason the input promise was rejected.
optOnError can return a value, which
     * allows it to act as a transformer: the return value serves as the final fulfillment value of the rejected promise in the
     * results array generated by all.
     * @returns {orion.Promise} A new promise. The returned promise is generally fulfilled to an Array whose elements
     * give the fulfillment values of the input promises.
However, if an input promise rejects and eager semantics is used, the
     * returned promise will instead be fulfilled to a single error value.

     */
    Deferred.all = function(promises, optOnError) {
        var count = promises.length,
            result = [],
            rejected = false,
            deferred = new Deferred();

        deferred.then(undefined, function() {
            rejected = true;
            promises.forEach(function(promise) {
                if (promise.cancel) {
                    promise.cancel();
                }
            });
        });

        function onResolve(i, value) {
            if (!rejected) {
                result[i] = value;
                if (--count === 0) {
                    deferred.resolve(result);
                }
            }
        }

        function onReject(i, error) {
            if (!rejected) {
                if (optOnError) {
                    try {
                        onResolve(i, optOnError(error));
                        return;
                    } catch (e) {
                        error = e;
                    }
                }
                deferred.reject(error);
            }
        }

        if (count === 0) {
            deferred.resolve(result);
        } else {
            promises.forEach(function(promise, i) {
                promise.then(onResolve.bind(undefined, i), onReject.bind(undefined, i));
            });
        }
        return deferred.promise;
    };

    /**
     * Applies callbacks to a promise or to a regular object.
     * @name when
     * @function
     * @memberOf orion.Deferred
     * @static
     * @param {Object|orion.Promise} value Either a {@link orion.Promise}, or a normal value.
     * @param {Function} onResolve Called when the value promise is resolved. If value is not a promise,
     * this function is called immediately.
     * @param {Function} onReject Called when the value promise is rejected. If value is not a promise,
     * this function is never called.
     * @param {Function} onProgress Called when the value promise provides a progress update. If value is
     * not a promise, this function is never called.
     * @returns {orion.Promise} A new promise.
     */
    Deferred.when = function(value, onResolve, onReject, onProgress) {
        var promise, deferred;
        if (value && typeof value.then === "function") { //$NON-NLS-0$
            promise = value;
        } else {
            deferred = new Deferred();
            deferred.resolve(value);
            promise = deferred.promise;
        }
        return promise.then(onResolve, onReject, onProgress);
    };

    return Deferred;
}));<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var util = require('util')
, OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

/**
 * `Strategy` constructor.
 *
 * The Slack authentication strategy authenticates requests by delegating
 * to Slack using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `clientID`      your Slack application's client id
 *   - `clientSecret`  your Slack application's client secret
 *   - `callbackURL`   URL to which Slack will redirect the user after granting authorization
 *   - `scope`         array of permission scopes to request.  valid scopes include:
 *                     'identify', 'read', 'post', 'client', or 'admin'.
 *
 * Examples:
 *
 *     passport.use(new SlackStrategy({
 *         clientID: '123-456-789',
 *         clientSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/slack/callback',
 *         scope: 'identify,read,post,client,admin'
 *       },
 *       function(accessToken, refreshToken, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://slack.com/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://slack.com/api/oauth.access';
  options.scopeSeparator = options.scopeSeparator || ',';
  this.profileUrl = options.profileUrl || "https://slack.com/api/auth.test?token=";
  this._team = options.team;

  OAuth2Strategy.call(this, options, verify);
  this.name = 'slack';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Retrieve user profile from Slack.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `slack`
 *   - `id`               the user's ID
 *   - `displayName`      the user's username
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(accessToken, done) {
  //this._oauth2.useAuthorizationHeaderforGET(true);
  this.get(this.profileUrl, accessToken, function (err, body, res) {
    if (err) {
      return done(err);
    } else {
      try {
        var json = JSON.parse(body);

        if (!json.ok) {
          done(json.error ? json.error : body);
        } else {
          var profile = {
            provider: 'Slack'
          };
          profile.id = json.user_id;
          profile.displayName = json.user;

          profile._raw = body;
          profile._json = json;

          done(null, profile);
        }
      } catch(e) {
        done(e);
      }
    }
  });
}

/** The default oauth2 strategy puts the access_token into Authorization: header AND query string
  * which is a violation of the RFC so lets override and not add the header and supply only the token for qs.
  */
Strategy.prototype.get = function(url, access_token, callback) {
  this._oauth2._request("GET", url + access_token, {}, "", "", callback );
};

/**
 * Return extra Slack parameters to be included in the authorization
 * request.
 *
 * @param {Object} options
 * @return {Object}
 */
Strategy.prototype.authorizationParams = function (options) {
  var params = {};
  var team = options.team || this._team;
   if(team){
     params.team = team;
   }
  return params;
};

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<commit_msg>Added user info to authenticated profile<commit_after>/**
 * Module dependencies.
 */
var util = require('util')
, OAuth2Strategy = require('passport-oauth').OAuth2Strategy;

/**
 * `Strategy` constructor.
 *
 * The Slack authentication strategy authenticates requests by delegating
 * to Slack using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occured, `err` should be set.
 *
 * Options:
 *   - `clientID`      your Slack application's client id
 *   - `clientSecret`  your Slack application's client secret
 *   - `callbackURL`   URL to which Slack will redirect the user after granting authorization
 *   - `scope`         array of permission scopes to request.  valid scopes include:
 *                     'identify', 'read', 'post', 'client', or 'admin'.
 *
 * Examples:
 *
 *     passport.use(new SlackStrategy({
 *         clientID: '123-456-789',
 *         clientSecret: 'shhh-its-a-secret'
 *         callbackURL: 'https://www.example.net/auth/slack/callback',
 *         scope: 'identify,read,post,client,admin'
 *       },
 *       function(accessToken, refreshToken, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://slack.com/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://slack.com/api/oauth.access';
  options.scopeSeparator = options.scopeSeparator || ',';
  this.profileUrl = options.profileUrl || "https://slack.com/api/auth.test?token=";
  this.userInfoUrl = options.userInfoUrl || "https://slack.com/api/users.info?user=";
  this._team = options.team;

  OAuth2Strategy.call(this, options, verify);
  this.name = 'slack';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Retrieve user profile from Slack.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `slack`
 *   - `id`               the user's ID
 *   - `displayName`      the user's username
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(accessToken, done) {
  //this._oauth2.useAuthorizationHeaderforGET(true);
  var self = this;
  this.get(this.profileUrl, accessToken, function (err, body, res) {
    if (err) {
      return done(err);
    } else {
      try {
        var json = JSON.parse(body);

        if (!json.ok) {
          done(json.error ? json.error : body);
        } else {
          var profile = {
            provider: 'Slack'
          };
          profile.id = json.user_id;
          profile.displayName = json.user;

          profile._raw = body;
          profile._json = json;

          self.get(self.userInfoUrl + profile.id + "&token=", accessToken, function (err, body, res) {
            if (err) {
              return done(err);
            }
            var infoJson = JSON.parse(body);
            if (!infoJson.ok) {
              done(infoJson.error ? infoJson.error : body);
            }else{
              profile._json.info = infoJson;
              done(null, profile);
            }
          });
        }
      } catch(e) {
        done(e);
      }
    }
  });
}

/** The default oauth2 strategy puts the access_token into Authorization: header AND query string
  * which is a violation of the RFC so lets override and not add the header and supply only the token for qs.
  */
Strategy.prototype.get = function(url, access_token, callback) {
  this._oauth2._request("GET", url + access_token, {}, "", "", callback );
};

/**
 * Return extra Slack parameters to be included in the authorization
 * request.
 *
 * @param {Object} options
 * @return {Object}
 */
Strategy.prototype.authorizationParams = function (options) {
  var params = {};
  var team = options.team || this._team;
   if(team){
     params.team = team;
   }
  return params;
};

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<|endoftext|>