<commit_before>/**
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var truncate = function(str, width, left) {
  if (!str) return "";

	if (str.length > width) {
    if (left) {
  		return str.slice(0, width) + "...";
    } else {
  		return "..." + str.slice(str.length - width, str.length);
    }
	}
	return str;
}
function extractVersion(image){
	var temp = image.split(":");
	if(temp.length > 1){
		return temp[1];
	}
	return "latest"

}

var pods = [];
var services = [];
var controllers = [];
var uses = {};

var groups = {};

var insertByName = function(index, value) {
  if (!value || !value.metadata.labels || !value.metadata.name) {
    return;
  }
  var key = value.metadata.labels.run;
	var list = groups[key];
	if (!list) {
		list = [];
		groups[key] = list;
	}
	list.push(value);
};

var groupByName = function() {
	$.each(pods.items, insertByName);
	$.each(controllers.items, insertByName);
	$.each(services.items, insertByName);
};

var matchesLabelQuery = function(labels, selector) {
	var match = true;
	$.each(selector, function(key, value) {
		if (labels[key] != value) {
			match = false;
		}
	});
	return match;
}

var connectControllers = function() {
    connectUses();
	for (var i = 0; i < controllers.items.length; i++) {
		var controller = controllers.items[i];
		for (var j = 0; j < pods.items.length; j++) {
			var pod = pods.items[j];
			if (pod.metadata.labels.run == controller.metadata.labels.run) {
        if (controller.metadata.labels.version && pod.metadata.labels.version && (controller.metadata.labels.version != pod.metadata.labels.version)) {
          continue;
        }
				jsPlumb.connect({
					source: 'controller-' + controller.metadata.name,
					target: 'pod-' + pod.metadata.name,
					anchors:["Bottom", "Bottom"],
					paintStyle:{lineWidth:5,strokeStyle:'rgb(51,105,232)'},
					joinStyle:"round",
					endpointStyle:{ fillStyle: 'rgb(51,105,232)', radius: 7 },
					connector: ["Flowchart", { cornerRadius:5 }]});
			}
		}
	}
	for (var i = 0; i < services.items.length; i++) {
		var service = services.items[i];
    //            if (service.metadata.name == 'kubernetes' || service.metadata.name == 'skydns' || service.metadata.name == 'kubernetes-ro') { continue; }
		for (var j = 0; j < pods.items.length; j++) {
			var pod = pods.items[j];
      //console.log('connect service: ' + 'service-' + service.metadata.name + ' to pod-' + pod.metadata.name);
			if (matchesLabelQuery(pod.metadata.labels, service.spec.selector)) {
				jsPlumb.connect(
					{
						source: 'service-' + service.metadata.name,
						target: 'pod-' + pod.metadata.name,
						anchors:["Bottom", "Top"],
						paintStyle:{lineWidth:5,strokeStyle:'rgb(0,153,57)'},
						endpointStyle:{ fillStyle: 'rgb(0,153,57)', radius: 7 },
						connector:["Flowchart", { cornerRadius:5 }]});
			}
		}
	}
};

var colors = [
	'rgb(213,15,37)',
	'rgb(238,178,17)',
	'rgb(17,178,238)'
]

var connectUses = function() {
	var colorIx = 0;
	var keys = [];
	$.each(uses, function(key) {
		keys.push(key);
	});
	keys.sort(function(a, b) { return a > b; });
	$.each(keys, function(idx) {
		var key = keys[idx];
		var list = uses[key];
		var color = colors[colorIx];
		colorIx++;
		if (colorIx >= colors.length) { colorIx = 0;};
		$.each(pods.items, function(i, pod) {
        var podKey = pod.metadata.labels.run;
         //console.log('connect uses key: ' +key + ', ' + podKey);
			if (podKey == key) {
				$.each(list, function(j, serviceId) {
          //console.log('connect: ' + 'pod-' + pod.metadata.name + ' to service-' + serviceId);
					jsPlumb.connect(
					{
						source: 'pod-' + pod.metadata.name,
						target: 'service-' + serviceId,
						endpoint: "Blank",
						//anchors:["Bottom", "Top"],
            anchors:[[ 0.5, 1, 0, 1, -30, 0 ], "Top"],
						//connector: "Straight",
            connector: ["Bezier", { curviness:75 }],
						paintStyle:{lineWidth:2,strokeStyle:color},
						overlays:[
    						[ "Arrow", { width:15, length:30, location: 0.3}],
    						[ "Arrow", { width:15, length:30, location: 0.6}],
    						[ "Arrow", { width:15, length:30, location: 1}],
    					],
					});
				});
			}
		});
	});
};

var makeGroupOrder = function() {
  var groupScores = {};
  $.each(groups, function(key, val) {
    //console.log("group key: " + key);
		if (!groupScores[key]) {
		  groupScores[key] = 0;
		}
		if (uses[key]) {
			value = uses[key];
		  $.each(value, function(ix, uses_label) {
				if (!groupScores[uses_label]) {
				    groupScores[uses_label] = 1;
				} else {
				    groupScores[uses_label]++;
				}
			});
		} else {
			if (!groupScores["no-service"]) {
				groupScores["no-service"] = 1;
			} else {
				groupScores["no-service"]++;
			}
		}
	});
  var groupOrder = [];
  $.each(groupScores, function(key, value) {
    groupOrder.push(key);
	});
  groupOrder.sort(function(a, b) { return groupScores[a] - groupScores[b]; });

	//console.log(groupOrder);
  return groupOrder;
};

var renderNodes = function() {
	var y = 25;
	var x = 100;
  $.each(nodes.items, function(index, value) {
    console.log(value);
		var div = $('
');
    var ready = false;
    $.each(value.status.conditions, function(index, condition) {
      if (condition.type === 'Ready') {
        ready = (condition.status === 'True' ? 'ready' : 'not_ready' )
      }
    });

 		var eltDiv = $('
');
	  eltDiv.html('Node

' +
          truncate(value.metadata.name, 12) +
          '');
    div.append(eltDiv);

	  var elt = $('.nodesbar');
		elt.append(div);

    x += 120;
 });
}

var renderGroups = function() {
	var elt = $('#sheet');
	var y = 10;
	var serviceLeft = 0;
	var groupOrder = makeGroupOrder();
  var counts = {}
	$.each(groupOrder, function(ix, key) {
		list = groups[key];
		// list = value;
    if (!list) {
    	return;
    }
		var div = $('
');
		var x = 100;
		$.each(list, function(index, value) {
      //console.log("render groups: " + value.type + ", " + value.metadata.name + ", " + index)
			var eltDiv = null;
      console.log(value);
      var phase = value.status.phase ? value.status.phase.toLowerCase() : '';
			if (value.type == "pod") {
				eltDiv = $('
');
				eltDiv.html('' +
          "v."+ extractVersion(value.spec.containers[0].image) +
          (value.metadata.labels.version ? "
" + value.metadata.labels.version : "") + "

" +
          (value.spec.nodeName ? truncate(value.spec.nodeName, 12) : "None") + "

" +
          (value.status.podIP? "" + value.status.podIP + "" : "" + phase + "") +
          '');
			} else if (value.type == "service") {
				eltDiv = $('
');
				eltDiv.html('' +
          value.metadata.name +
          (value.metadata.labels.version ? "

" + value.metadata.labels.version : "") +
          (value.spec.externalIPs[0] ? "

" + value.spec.externalIPs[0] + ":" +value.spec.ports[0].port : "") +
          (value.spec.clusterIP ? "

" + value.spec.clusterIP : "") +
          (value.status.loadBalancer && value.status.loadBalancer.ingress ? "
" + value.status.loadBalancer.ingress[0].ip + "" : "") +
          '');
			} else {
        var key = 'controller-' + value.metadata.labels.name;
        counts[key] = key in counts ? counts[key] + 1 : 0;
				//eltDiv = $('
');
        var minLeft = 900;
        var calcLeft = 400 + (value.status.replicas * 130);
        var left = minLeft > calcLeft ? minLeft : calcLeft;
				eltDiv = $('
');
				eltDiv.html('' +
          value.metadata.name +
          (value.metadata.labels.version ? "

" + value.metadata.labels.version : "") +
          '');
			}
			div.append(eltDiv);
			x += 130;
		});
		y += 400;
		serviceLeft += 200;
		elt.append(div);
	});
};

var insertUse = function(name, use) {
  for (var i = 0; i < uses[name].length; i++) {
    if (uses[name][i] == use) {
      return;
    }
  }
  uses[name].push(use);
};

var loadData = function() {
	var deferred = new $.Deferred();
	var req1 = $.getJSON("/api/v1/pods?labelSelector=visualize%3Dtrue", function( data ) {
		pods = data;
		console.log(pods);
		$.each(data.items, function(key, val) {
    	val.type = 'pod';
      if (val.metadata.labels && val.metadata.labels.uses) {
      	var key = val.metadata.labels.run;
		    if (!uses[key]) {
			  	uses[key] = val.metadata.labels.uses.split("_");
		    } else {
			  	$.each(val.metadata.labels.uses.split("_"), function(ix, use) { insertUse(key, use); });
		    }
		  }
    });
	});

	var req2 = $.getJSON("/api/v1/replicationcontrollers?labelSelector=visualize%3Dtrue", function( data ) {
		controllers = data;
		$.each(data.items, function(key, val) {
      val.type = 'replicationController';
      //console.log("Controller ID = " + val.metadata.name)
    });
	});

	var req3 = $.getJSON("/api/v1/services?labelSelector=visualize%3Dtrue", function( data ) {
		services = data;
		//console.log("loadData(): Services");
		//console.log(services);
		$.each(data.items, function(key, val) {
      val.type = 'service';
      //console.log("service ID = " + val.metadata.name)
    });
	});

	var req4 = $.getJSON("/api/v1/nodes", function( data ) {
		nodes = data;
		//console.log("loadData(): Services");
		//console.log(nodes);
		$.each(data.items, function(key, val) {
      val.type = 'node';
      //console.log("service ID = " + val.metadata.name)
    });
	});

	$.when(req1, req2, req3, req4).then(function() {
		deferred.resolve();
	});

	return deferred;
}

function refresh(instance) {
	pods = [];
	services = [];
	controllers = [];
  nodes = [];
	uses = {};
	groups = {};

	$.when(loadData()).then(function() {
		groupByName();
		$('#sheet').empty();
    renderNodes();
		renderGroups();
		connectControllers();

		setTimeout(function() {
			refresh(instance);
		}, 2000);
  });
}

jsPlumb.bind("ready", function() {
	var instance = jsPlumb.getInstance({
		// default drag options
		DragOptions : { cursor: 'pointer', zIndex:2000 },
		// the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
		// case it returns the 'labelText' member that we set on each connection in the 'init' method below.
		ConnectionOverlays : [
			[ "Arrow", { location:1 } ],
			//[ "Label", {
			//	location:0.1,
			//	id:"label",
			//	cssClass:"aLabel"
			//}]
		],
		Container:"flowchart-demo"
	});

	refresh(instance);
	jsPlumb.fire("jsPlumbDemoLoaded", instance);
  });
<commit_msg>OnClick on nodes opens cAdvisor on node(port 4193)<commit_after>/**
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var truncate = function(str, width, left) {
  if (!str) return "";

	if (str.length > width) {
    if (left) {
  		return str.slice(0, width) + "...";
    } else {
  		return "..." + str.slice(str.length - width, str.length);
    }
	}
	return str;
}
function extractVersion(image){
	var temp = image.split(":");
	if(temp.length > 1){
		return temp[1];
	}
	return "latest"

}

var pods = [];
var services = [];
var controllers = [];
var uses = {};

var groups = {};

var insertByName = function(index, value) {
  if (!value || !value.metadata.labels || !value.metadata.name) {
    return;
  }
  var key = value.metadata.labels.run;
	var list = groups[key];
	if (!list) {
		list = [];
		groups[key] = list;
	}
	list.push(value);
};

var groupByName = function() {
	$.each(pods.items, insertByName);
	$.each(controllers.items, insertByName);
	$.each(services.items, insertByName);
};

var matchesLabelQuery = function(labels, selector) {
	var match = true;
	$.each(selector, function(key, value) {
		if (labels[key] != value) {
			match = false;
		}
	});
	return match;
}

var connectControllers = function() {
    connectUses();
	for (var i = 0; i < controllers.items.length; i++) {
		var controller = controllers.items[i];
		for (var j = 0; j < pods.items.length; j++) {
			var pod = pods.items[j];
			if (pod.metadata.labels.run == controller.metadata.labels.run) {
        if (controller.metadata.labels.version && pod.metadata.labels.version && (controller.metadata.labels.version != pod.metadata.labels.version)) {
          continue;
        }
				jsPlumb.connect({
					source: 'controller-' + controller.metadata.name,
					target: 'pod-' + pod.metadata.name,
					anchors:["Bottom", "Bottom"],
					paintStyle:{lineWidth:5,strokeStyle:'rgb(51,105,232)'},
					joinStyle:"round",
					endpointStyle:{ fillStyle: 'rgb(51,105,232)', radius: 7 },
					connector: ["Flowchart", { cornerRadius:5 }]});
			}
		}
	}
	for (var i = 0; i < services.items.length; i++) {
		var service = services.items[i];
    //            if (service.metadata.name == 'kubernetes' || service.metadata.name == 'skydns' || service.metadata.name == 'kubernetes-ro') { continue; }
		for (var j = 0; j < pods.items.length; j++) {
			var pod = pods.items[j];
      //console.log('connect service: ' + 'service-' + service.metadata.name + ' to pod-' + pod.metadata.name);
			if (matchesLabelQuery(pod.metadata.labels, service.spec.selector)) {
				jsPlumb.connect(
					{
						source: 'service-' + service.metadata.name,
						target: 'pod-' + pod.metadata.name,
						anchors:["Bottom", "Top"],
						paintStyle:{lineWidth:5,strokeStyle:'rgb(0,153,57)'},
						endpointStyle:{ fillStyle: 'rgb(0,153,57)', radius: 7 },
						connector:["Flowchart", { cornerRadius:5 }]});
			}
		}
	}
};

var colors = [
	'rgb(213,15,37)',
	'rgb(238,178,17)',
	'rgb(17,178,238)'
]

var connectUses = function() {
	var colorIx = 0;
	var keys = [];
	$.each(uses, function(key) {
		keys.push(key);
	});
	keys.sort(function(a, b) { return a > b; });
	$.each(keys, function(idx) {
		var key = keys[idx];
		var list = uses[key];
		var color = colors[colorIx];
		colorIx++;
		if (colorIx >= colors.length) { colorIx = 0;};
		$.each(pods.items, function(i, pod) {
        var podKey = pod.metadata.labels.run;
         //console.log('connect uses key: ' +key + ', ' + podKey);
			if (podKey == key) {
				$.each(list, function(j, serviceId) {
          //console.log('connect: ' + 'pod-' + pod.metadata.name + ' to service-' + serviceId);
					jsPlumb.connect(
					{
						source: 'pod-' + pod.metadata.name,
						target: 'service-' + serviceId,
						endpoint: "Blank",
						//anchors:["Bottom", "Top"],
            anchors:[[ 0.5, 1, 0, 1, -30, 0 ], "Top"],
						//connector: "Straight",
            connector: ["Bezier", { curviness:75 }],
						paintStyle:{lineWidth:2,strokeStyle:color},
						overlays:[
    						[ "Arrow", { width:15, length:30, location: 0.3}],
    						[ "Arrow", { width:15, length:30, location: 0.6}],
    						[ "Arrow", { width:15, length:30, location: 1}],
    					],
					});
				});
			}
		});
	});
};

var makeGroupOrder = function() {
  var groupScores = {};
  $.each(groups, function(key, val) {
    //console.log("group key: " + key);
		if (!groupScores[key]) {
		  groupScores[key] = 0;
		}
		if (uses[key]) {
			value = uses[key];
		  $.each(value, function(ix, uses_label) {
				if (!groupScores[uses_label]) {
				    groupScores[uses_label] = 1;
				} else {
				    groupScores[uses_label]++;
				}
			});
		} else {
			if (!groupScores["no-service"]) {
				groupScores["no-service"] = 1;
			} else {
				groupScores["no-service"]++;
			}
		}
	});
  var groupOrder = [];
  $.each(groupScores, function(key, value) {
    groupOrder.push(key);
	});
  groupOrder.sort(function(a, b) { return groupScores[a] - groupScores[b]; });

	//console.log(groupOrder);
  return groupOrder;
};

var renderNodes = function() {
	var y = 25;
	var x = 100;
  $.each(nodes.items, function(index, value) {
    console.log(value);
		var div = $('
');
    var ready = false;
    $.each(value.status.conditions, function(index, condition) {
      if (condition.type === 'Ready') {
        ready = (condition.status === 'True' ? 'ready' : 'not_ready' )
      }
    });

 		var eltDiv = $('
');
	  eltDiv.html('Node

' +
          truncate(value.metadata.name, 12) +
          '');
	  eltDiv.on("click", function() {
	  	window.location.href = "http://" + value.metadata.name +":4194/"
	  });
    div.append(eltDiv);

	  var elt = $('.nodesbar');
		elt.append(div);

    x += 120;
 });
}

var renderGroups = function() {
	var elt = $('#sheet');
	var y = 10;
	var serviceLeft = 0;
	var groupOrder = makeGroupOrder();
  var counts = {}
	$.each(groupOrder, function(ix, key) {
		list = groups[key];
		// list = value;
    if (!list) {
    	return;
    }
		var div = $('
');
		var x = 100;
		$.each(list, function(index, value) {
      //console.log("render groups: " + value.type + ", " + value.metadata.name + ", " + index)
			var eltDiv = null;
      console.log(value);
      var phase = value.status.phase ? value.status.phase.toLowerCase() : '';
			if (value.type == "pod") {
				eltDiv = $('
');
				eltDiv.html('' +
          "v."+ extractVersion(value.spec.containers[0].image) +
          (value.metadata.labels.version ? "
" + value.metadata.labels.version : "") + "

" +
          (value.spec.nodeName ? truncate(value.spec.nodeName, 12) : "None") + "

" +
          (value.status.podIP? "" + value.status.podIP + "" : "" + phase + "") +
          '');
			} else if (value.type == "service") {
				eltDiv = $('
');
				eltDiv.html('' +
          value.metadata.name +
          (value.metadata.labels.version ? "

" + value.metadata.labels.version : "") +
          (value.spec.externalIPs[0] ? "

" + value.spec.externalIPs[0] + ":" +value.spec.ports[0].port : "") +
          (value.spec.clusterIP ? "

" + value.spec.clusterIP : "") +
          (value.status.loadBalancer && value.status.loadBalancer.ingress ? "
" + value.status.loadBalancer.ingress[0].ip + "" : "") +
          '');
			} else {
        var key = 'controller-' + value.metadata.labels.name;
        counts[key] = key in counts ? counts[key] + 1 : 0;
				//eltDiv = $('
');
        var minLeft = 900;
        var calcLeft = 400 + (value.status.replicas * 130);
        var left = minLeft > calcLeft ? minLeft : calcLeft;
				eltDiv = $('
');
				eltDiv.html('' +
          value.metadata.name +
          (value.metadata.labels.version ? "

" + value.metadata.labels.version : "") +
          '');
			}
			div.append(eltDiv);
			x += 130;
		});
		y += 400;
		serviceLeft += 200;
		elt.append(div);
	});
};

var insertUse = function(name, use) {
  for (var i = 0; i < uses[name].length; i++) {
    if (uses[name][i] == use) {
      return;
    }
  }
  uses[name].push(use);
};

var loadData = function() {
	var deferred = new $.Deferred();
	var req1 = $.getJSON("/api/v1/pods?labelSelector=visualize%3Dtrue", function( data ) {
		pods = data;
		console.log(pods);
		$.each(data.items, function(key, val) {
    	val.type = 'pod';
      if (val.metadata.labels && val.metadata.labels.uses) {
      	var key = val.metadata.labels.run;
		    if (!uses[key]) {
			  	uses[key] = val.metadata.labels.uses.split("_");
		    } else {
			  	$.each(val.metadata.labels.uses.split("_"), function(ix, use) { insertUse(key, use); });
		    }
		  }
    });
	});

	var req2 = $.getJSON("/api/v1/replicationcontrollers?labelSelector=visualize%3Dtrue", function( data ) {
		controllers = data;
		$.each(data.items, function(key, val) {
      val.type = 'replicationController';
      //console.log("Controller ID = " + val.metadata.name)
    });
	});

	var req3 = $.getJSON("/api/v1/services?labelSelector=visualize%3Dtrue", function( data ) {
		services = data;
		//console.log("loadData(): Services");
		//console.log(services);
		$.each(data.items, function(key, val) {
      val.type = 'service';
      //console.log("service ID = " + val.metadata.name)
    });
	});

	var req4 = $.getJSON("/api/v1/nodes", function( data ) {
		nodes = data;
		//console.log("loadData(): Services");
		//console.log(nodes);
		$.each(data.items, function(key, val) {
      val.type = 'node';
      //console.log("service ID = " + val.metadata.name)
    });
	});

	$.when(req1, req2, req3, req4).then(function() {
		deferred.resolve();
	});

	return deferred;
}

function refresh(instance) {
	pods = [];
	services = [];
	controllers = [];
  nodes = [];
	uses = {};
	groups = {};

	$.when(loadData()).then(function() {
		groupByName();
		$('#sheet').empty();
    renderNodes();
		renderGroups();
		connectControllers();

		setTimeout(function() {
			refresh(instance);
		}, 2000);
  });
}

jsPlumb.bind("ready", function() {
	var instance = jsPlumb.getInstance({
		// default drag options
		DragOptions : { cursor: 'pointer', zIndex:2000 },
		// the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
		// case it returns the 'labelText' member that we set on each connection in the 'init' method below.
		ConnectionOverlays : [
			[ "Arrow", { location:1 } ],
			//[ "Label", {
			//	location:0.1,
			//	id:"label",
			//	cssClass:"aLabel"
			//}]
		],
		Container:"flowchart-demo"
	});

	refresh(instance);
	jsPlumb.fire("jsPlumbDemoLoaded", instance);
  });
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Employee Portal Enhancements
// @namespace    http://kunalshetye.github.io/
// @version      0.2
// @description  improve employee-portal one javascript at a time
// @author       Kunal Shetye
// @match        https://employeeportal.sdl.com/Timesheet.aspx
// @grant        none
// @noframes     1
// ==/UserScript==

$(function(){
    var originalFunction = SaveNewImageButton_Click;
    var originalFunctionString = SaveNewImageButton_Click.toString();
    var patchedFunctionString = originalFunctionString.replace("if (workEnd > new Date())", "if (workEnd != workEnd)").replace("function SaveNewImageButton_Click()", "function()");
    SaveNewImageButton_Click = eval("(" + patchedFunctionString + ")");
    var saveNewTSRecordOriginalFunction = saveNewTSRecord;
    var saveNewTSRecordFunctionString = saveNewTSRecord.toString();
    var patchedSaveNewTSRecordFunctionString = saveNewTSRecordFunctionString.replace("var sComment = tbComment.text();", "var sComment = tbComment.val();");
    saveNewTSRecord = eval("(" + patchedSaveNewTSRecordFunctionString + ")");
    var CreatePendingRecordOriginalFunction = CreatePendingRecord;
    var CreatePendingRecordFunctionString = CreatePendingRecord.toString();
    var patchedCreatePendingRecordFunctionString = CreatePendingRecordFunctionString.replace("$('#MasterPage_ContentPlaceHolder1_CommentTextBoxNew').text();", "$('#MasterPage_ContentPlaceHolder1_CommentTextBoxNew').val();");
    CreatePendingRecord = eval("(" + patchedCreatePendingRecordFunctionString + ")");
    //showThickbox("ThickBox1", "You can now log work against time in the future, with descriptions on Chrome! ;)");
    $("div#HomeContent span#MasterPage_PageTitleSuffix").html($("div#HomeContent span#MasterPage_PageTitleSuffix").text() + " (God Mode)");
});<commit_msg>Converted into a TamperMonkey stub file<commit_after>// ==UserScript==
// @name         Employee Portal Enhancements
// @namespace    http://kunalshetye.github.io/
// @version      0.3
// @description  improve employee-portal one javascript at a time
// @author       Kunal Shetye
// @match        https://employeeportal.sdl.com/Timesheet.aspx
// @require      https://kunalshetye.github.io/tm/Employee.Portal.Enhancements/script.js
// @noframes     1
// @resource     CSS https://kunalshetye.github.io/tm/Employee.Portal.Enhancements/style.css
// @grant        GM_addStyle
// @grant        GM_getResourceText

// ==/UserScript==

var newCSS = GM_getResourceText ("CSS");
GM_addStyle (newCSS);<|endoftext|>


<commit_before>var _ = require('underscore');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var PanelWithOptionsView = require('../../components/view-options/panel-with-options-view');
var StyleContentView = require('./style-content-view');
var StyleCartoCSSView = require('./style-cartocss-view');
var ScrollView = require('../../components/scroll/scroll-view');
var TabPaneView = require('../../components/tab-pane/tab-pane-view');
var TabPaneCollection = require('../../components/tab-pane/tab-pane-collection');
var Toggler = require('../../components/toggler/toggler-view');
var UndoButtons = require('../../components/undo-redo/undo-redo-view');
var ParserCSS = require('../../helpers/parser-css');
var Infobox = require('../../components/infobox/infobox-factory');
var InfoboxModel = require('../../components/infobox/infobox-model');
var InfoboxCollection = require('../../components/infobox/infobox-collection');
var Notifier = require('../../components/notifier/notifier');
var CartoCSSNotifications = require('../../cartocss-notifications');

module.exports = CoreView.extend({

  initialize: function (opts) {
    if (!opts.layerDefinitionsCollection) throw new Error('layersDefinitionCollection is required');
    if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
    if (!opts.userActions) throw new Error('userActions is required');
    if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
    if (!opts.modals) throw new Error('modals is required');
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.configModel) throw new Error('configModel is required');

    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._layerDefinitionModel = opts.layerDefinitionModel;
    this._userActions = opts.userActions;
    this._styleModel = this._layerDefinitionModel.styleModel;
    this._configModel = opts.configModel;
    this._modals = opts.modals;
    this._querySchemaModel = opts.querySchemaModel;
    this._editorModel = opts.editorModel;
    this._cartocssModel = this._layerDefinitionModel.cartocssModel;
    this._codemirrorModel = new Backbone.Model({
      content: this._layerDefinitionModel.get('cartocss')
    });

    // Set edition attribute in case custom cartocss is applied
    this._editorModel.set({
      edition: !!this._layerDefinitionModel.get('cartocss_custom'),
      disabled: false
    });

    this._infoboxModel = new InfoboxModel({
      state: this._isLayerHidden() ? 'layer-hidden' : ''
    });

    this._overlayModel = new Backbone.Model({
      visible: this._isLayerHidden()
    });

    this.listenTo(this._editorModel, 'change:edition', this._onChangeEdition);
    this.add_related_model(this._editorModel);

    this._appendMapsAPIError();
    this.listenTo(this._layerDefinitionModel, 'change:error', this._appendMapsAPIError);

    CartoCSSNotifications.track(this);

    this._configPanes();
    this._initBinds();
  },

  _appendMapsAPIError: function () {
    var error = this._layerDefinitionModel.get('error');
    if (error) {
      if (error.type === 'turbo-carto') {
        var newErrors = _.clone(this._codemirrorModel.get('errors')) || [];
        newErrors.push({ line: error.line, message: error.message });
        this._codemirrorModel.set('errors', newErrors);
      }
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initBinds: function () {
    this._querySchemaModel.on('change:query_errors', this._updateEditor, this);
    this.add_related_model(this._querySchemaModel);

    this._styleModel.bind('change', function () {
      this._codemirrorModel.set('content', this._layerDefinitionModel.get('cartocss'));
    }, this);
    this.add_related_model(this._styleModel);

    this._cartocssModel.bind('undo redo', function () {
      this._codemirrorModel.set('content', this._cartocssModel.get('content'));
    }, this);
    this.add_related_model(this._cartocssModel);
  },

  _updateEditor: function (model) {
    var errors = this._querySchemaModel.get('query_errors');
    var hasErrors = errors && errors.length > 0;
    this._editorModel.set('disabled', hasErrors);
  },

  _saveCartoCSS: function () {
    var content = this._codemirrorModel.get('content');
    var parser = new ParserCSS(content);
    var errors = parser.errors();

    if (!content) {
      return false;
    }

    this._codemirrorModel.set('errors', parser.parseError(errors));

    if (errors.length === 0) {
      this._cartocssModel.set('content', content);
      this._layerDefinitionModel.set({
        cartocss_custom: true,
        cartocss: content
      });

      this._userActions.saveLayer(this._layerDefinitionModel);

      CartoCSSNotifications.showSuccessNotification();
    } else {
      CartoCSSNotifications.showErrorNotification(parser.parseError(errors));
    }
  },

  _confirmApplyStyles: function () {
    this._infoboxModel.set({state: ''});
    this._overlayModel.set({visible: false});

    this._editorModel.set({
      edition: true
    });
  },

  _cancelApplyStyles: function () {
    this._styleModel.applyLastState();
    this._infoboxModel.set({state: ''});
    this._overlayModel.set({visible: false});
    this.render();
  },

  _cancelTorqueAggregation: function () {
    this._styleModel.applyLastState();
    this._infoboxModel.set({state: ''});
    this._overlayModel.set({visible: false});
    this.render();
  },

  _applyTorqueAggregation: function () {
    if (this._layerDefinitionsCollection.isThereAnyTorqueLayer()) {
      var torqueLayer = this._layerDefinitionsCollection.findWhere({ type: 'torque' });
      torqueLayer.styleModel.setDefaultPropertiesByType('simple', 'point');
    }

    this._infoboxModel.set({state: 'unfreeze'});
  },

  _onChangeEdition: function () {
    this._infoboxState();

    var edition = this._editorModel.get('edition');
    var index = edition ? 1 : 0;
    this._collectionPane.at(index).set({ selected: true });
  },

  _freezeTorgeAggregation: function (styleType, currentGeometryType) {
    this._infoboxModel.set({state: 'torque-exists'});
    this._overlayModel.set({visible: true});

    // Apply the previously selected style
    this._infoboxModel.once('change:state', function (mdl, state) {
      if (state === 'unfreeze') {
        this._moveTorqueLayerToTop(function () {
          this._overlayModel.set({visible: false});
          this._styleModel.setDefaultPropertiesByType(styleType, currentGeometryType);
        }.bind(this));
        this._infoboxModel.set({state: ''});
      }
    }, this);
  },

  _moveTorqueLayerToTop: function (callback) {
    var notification = Notifier.addNotification({
      status: 'loading',
      info: _t('editor.layers.moveTorqueLayer.loading'),
      closable: true
    });

    this._layerDefinitionsCollection.once('layerMoved', function () {
      callback && callback();
      notification.set({
        status: 'success',
        info: _t('editor.layers.moveTorqueLayer.success'),
        delay: Notifier.DEFAULT_DELAY
      });
    }, this);

    this._userActions.moveLayer({
      from: this._layerDefinitionModel.get('order'),
      to: this._layerDefinitionsCollection.getTopDataLayerIndex()
    });
  },

  _configPanes: function () {
    var self = this;
    var tabPaneTabs = [{
      selected: !this._layerDefinitionModel.get('cartocss_custom'),
      createContentView: function () {
        return new ScrollView({
          createContentView: function () {
            return new StyleContentView({
              className: 'Editor-content',
              userActions: self._userActions,
              layerDefinitionsCollection: self._layerDefinitionsCollection,
              layerDefinitionModel: self._layerDefinitionModel,
              styleModel: self._styleModel,
              modals: self._modals,
              configModel: self._configModel,
              querySchemaModel: self._querySchemaModel,
              editorModel: self._editorModel,
              overlayModel: self._overlayModel,
              freezeTorgeAggregation: self._freezeTorgeAggregation.bind(self)
            });
          }
        });
      },
      createActionView: function () {
        return new UndoButtons({
          trackModel: self._styleModel,
          editorModel: self._editorModel,
          applyButton: false
        });
      }
    }, {
      selected: this._layerDefinitionModel.get('cartocss_custom'),
      createContentView: function () {
        return new StyleCartoCSSView({
          layerDefinitionModel: self._layerDefinitionModel,
          styleModel: self._styleModel,
          editorModel: self._editorModel,
          codemirrorModel: self._codemirrorModel,
          onApplyEvent: self._saveCartoCSS.bind(self)
        });
      },
      createActionView: function () {
        return new UndoButtons({
          trackModel: self._cartocssModel,
          editorModel: self._editorModel,
          applyButton: true,
          onApplyClick: self._saveCartoCSS.bind(self)
        });
      }
    }];

    this._collectionPane = new TabPaneCollection(tabPaneTabs);
  },

  _isLayerHidden: function () {
    return this._layerDefinitionModel.get('visible') === false;
  },

  _infoboxState: function () {
    var edition = this._editorModel.get('edition');
    var cartocss_custom = this._layerDefinitionModel.get('cartocss_custom');

    if (!edition && cartocss_custom) {
      this._infoboxModel.set({state: 'confirm'});
      this._overlayModel.set({visible: true});
    } else if (!edition && this._isLayerHidden()) {
      this._infoboxModel.set({state: 'layer-hidden'});
      this._overlayModel.set({visible: true});
    } else {
      this._infoboxModel.set({state: ''});
      this._overlayModel.set({visible: false});
    }
  },

  _showHiddenLayer: function () {
    this._layerDefinitionModel.toggleVisible();
    this._userActions.saveLayer(this._layerDefinitionModel);

    this._infoboxState();
  },

  _initViews: function () {
    var self = this;

    var infoboxSstates = [
      {
        state: 'confirm',
        createContentView: function () {
          return Infobox.createConfirmAndCancel({
            type: 'alert',
            title: _t('editor.style.messages.cartocss-applied.title'),
            body: _t('editor.style.messages.cartocss-applied.body'),
            cancelLabel: _t('editor.style.messages.cartocss-applied.cancel'),
            confirmLabel: _t('editor.style.messages.cartocss-applied.accept')
          });
        },
        mainAction: self._cancelApplyStyles.bind(self),
        secondAction: self._confirmApplyStyles.bind(self)
      }, {
        state: 'layer-hidden',
        createContentView: function () {
          return Infobox.createConfirm({
            type: 'alert',
            title: _t('editor.style.messages.layer-hidden.title'),
            body: _t('editor.style.messages.layer-hidden.body'),
            confirmLabel: _t('editor.style.messages.layer-hidden.show'),
            confirmType: 'button'
          });
        },
        mainAction: self._showHiddenLayer.bind(self)
      }, {
        state: 'torque-exists',
        createContentView: function () {
          return Infobox.createConfirmAndCancel({
            type: 'alert',
            title: _t('editor.style.messages.torque-exists.title'),
            body: _t('editor.style.messages.torque-exists.body'),
            cancelLabel: _t('editor.style.messages.torque-exists.cancel'),
            confirmLabel: _t('editor.style.messages.torque-exists.accept')
          });
        },
        mainAction: self._cancelTorqueAggregation.bind(self),
        secondAction: self._applyTorqueAggregation.bind(self)
      }
    ];

    var infoboxCollection = new InfoboxCollection(infoboxSstates);

    var panelWithOptionsView = new PanelWithOptionsView({
      className: 'Editor-content',
      editorModel: self._editorModel,
      infoboxModel: self._infoboxModel,
      infoboxCollection: infoboxCollection,
      createContentView: function () {
        return new TabPaneView({
          collection: self._collectionPane
        });
      },
      createControlView: function () {
        return new Toggler({
          editorModel: self._editorModel,
          labels: [_t('editor.style.style-toggle.values'), _t('editor.style.style-toggle.cartocss')],
          isDisableable: true
        });
      },
      createActionView: function () {
        return new TabPaneView({
          collection: self._collectionPane,
          createContentKey: 'createActionView'
        });
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  }

});
<commit_msg>Metrics tracker for applied Cartocss added<commit_after>var _ = require('underscore');
var Backbone = require('backbone');
var CoreView = require('backbone/core-view');
var PanelWithOptionsView = require('../../components/view-options/panel-with-options-view');
var StyleContentView = require('./style-content-view');
var StyleCartoCSSView = require('./style-cartocss-view');
var ScrollView = require('../../components/scroll/scroll-view');
var TabPaneView = require('../../components/tab-pane/tab-pane-view');
var TabPaneCollection = require('../../components/tab-pane/tab-pane-collection');
var Toggler = require('../../components/toggler/toggler-view');
var UndoButtons = require('../../components/undo-redo/undo-redo-view');
var ParserCSS = require('../../helpers/parser-css');
var Infobox = require('../../components/infobox/infobox-factory');
var InfoboxModel = require('../../components/infobox/infobox-model');
var InfoboxCollection = require('../../components/infobox/infobox-collection');
var Notifier = require('../../components/notifier/notifier');
var CartoCSSNotifications = require('../../cartocss-notifications');
var MetricsTracker = require('../../components/metrics/metrics-tracker');

module.exports = CoreView.extend({

  initialize: function (opts) {
    if (!opts.layerDefinitionsCollection) throw new Error('layersDefinitionCollection is required');
    if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
    if (!opts.userActions) throw new Error('userActions is required');
    if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
    if (!opts.modals) throw new Error('modals is required');
    if (!opts.editorModel) throw new Error('editorModel is required');
    if (!opts.configModel) throw new Error('configModel is required');

    this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
    this._layerDefinitionModel = opts.layerDefinitionModel;
    this._userActions = opts.userActions;
    this._styleModel = this._layerDefinitionModel.styleModel;
    this._configModel = opts.configModel;
    this._modals = opts.modals;
    this._querySchemaModel = opts.querySchemaModel;
    this._editorModel = opts.editorModel;
    this._cartocssModel = this._layerDefinitionModel.cartocssModel;
    this._codemirrorModel = new Backbone.Model({
      content: this._layerDefinitionModel.get('cartocss')
    });

    // Set edition attribute in case custom cartocss is applied
    this._editorModel.set({
      edition: !!this._layerDefinitionModel.get('cartocss_custom'),
      disabled: false
    });

    this._infoboxModel = new InfoboxModel({
      state: this._isLayerHidden() ? 'layer-hidden' : ''
    });

    this._overlayModel = new Backbone.Model({
      visible: this._isLayerHidden()
    });

    this.listenTo(this._editorModel, 'change:edition', this._onChangeEdition);
    this.add_related_model(this._editorModel);

    this._appendMapsAPIError();
    this.listenTo(this._layerDefinitionModel, 'change:error', this._appendMapsAPIError);

    CartoCSSNotifications.track(this);

    this._configPanes();
    this._initBinds();
  },

  _appendMapsAPIError: function () {
    var error = this._layerDefinitionModel.get('error');
    if (error) {
      if (error.type === 'turbo-carto') {
        var newErrors = _.clone(this._codemirrorModel.get('errors')) || [];
        newErrors.push({ line: error.line, message: error.message });
        this._codemirrorModel.set('errors', newErrors);
      }
    }
  },

  render: function () {
    this.clearSubViews();
    this.$el.empty();
    this._initViews();
    return this;
  },

  _initBinds: function () {
    this._querySchemaModel.on('change:query_errors', this._updateEditor, this);
    this.add_related_model(this._querySchemaModel);

    this._styleModel.bind('change', function () {
      this._codemirrorModel.set('content', this._layerDefinitionModel.get('cartocss'));
    }, this);
    this.add_related_model(this._styleModel);

    this._cartocssModel.bind('undo redo', function () {
      this._codemirrorModel.set('content', this._cartocssModel.get('content'));
    }, this);
    this.add_related_model(this._cartocssModel);
  },

  _updateEditor: function (model) {
    var errors = this._querySchemaModel.get('query_errors');
    var hasErrors = errors && errors.length > 0;
    this._editorModel.set('disabled', hasErrors);
  },

  _saveCartoCSS: function () {
    var content = this._codemirrorModel.get('content');
    var parser = new ParserCSS(content);
    var errors = parser.errors();

    if (!content) {
      return false;
    }

    this._codemirrorModel.set('errors', parser.parseError(errors));

    if (errors.length === 0) {
      this._cartocssModel.set('content', content);
      this._layerDefinitionModel.set({
        cartocss_custom: true,
        cartocss: content
      });

      this._userActions.saveLayer(this._layerDefinitionModel);

      CartoCSSNotifications.showSuccessNotification();

      MetricsTracker.track('Applied CartoCSS', this._layerDefinitionModel.attributes);
    } else {
      CartoCSSNotifications.showErrorNotification(parser.parseError(errors));
    }
  },

  _confirmApplyStyles: function () {
    this._infoboxModel.set({state: ''});
    this._overlayModel.set({visible: false});

    this._editorModel.set({
      edition: true
    });
  },

  _cancelApplyStyles: function () {
    this._styleModel.applyLastState();
    this._infoboxModel.set({state: ''});
    this._overlayModel.set({visible: false});
    this.render();
  },

  _cancelTorqueAggregation: function () {
    this._styleModel.applyLastState();
    this._infoboxModel.set({state: ''});
    this._overlayModel.set({visible: false});
    this.render();
  },

  _applyTorqueAggregation: function () {
    if (this._layerDefinitionsCollection.isThereAnyTorqueLayer()) {
      var torqueLayer = this._layerDefinitionsCollection.findWhere({ type: 'torque' });
      torqueLayer.styleModel.setDefaultPropertiesByType('simple', 'point');
    }

    this._infoboxModel.set({state: 'unfreeze'});
  },

  _onChangeEdition: function () {
    this._infoboxState();

    var edition = this._editorModel.get('edition');
    var index = edition ? 1 : 0;
    this._collectionPane.at(index).set({ selected: true });
  },

  _freezeTorgeAggregation: function (styleType, currentGeometryType) {
    this._infoboxModel.set({state: 'torque-exists'});
    this._overlayModel.set({visible: true});

    // Apply the previously selected style
    this._infoboxModel.once('change:state', function (mdl, state) {
      if (state === 'unfreeze') {
        this._moveTorqueLayerToTop(function () {
          this._overlayModel.set({visible: false});
          this._styleModel.setDefaultPropertiesByType(styleType, currentGeometryType);
        }.bind(this));
        this._infoboxModel.set({state: ''});
      }
    }, this);
  },

  _moveTorqueLayerToTop: function (callback) {
    var notification = Notifier.addNotification({
      status: 'loading',
      info: _t('editor.layers.moveTorqueLayer.loading'),
      closable: true
    });

    this._layerDefinitionsCollection.once('layerMoved', function () {
      callback && callback();
      notification.set({
        status: 'success',
        info: _t('editor.layers.moveTorqueLayer.success'),
        delay: Notifier.DEFAULT_DELAY
      });
    }, this);

    this._userActions.moveLayer({
      from: this._layerDefinitionModel.get('order'),
      to: this._layerDefinitionsCollection.getTopDataLayerIndex()
    });
  },

  _configPanes: function () {
    var self = this;
    var tabPaneTabs = [{
      selected: !this._layerDefinitionModel.get('cartocss_custom'),
      createContentView: function () {
        return new ScrollView({
          createContentView: function () {
            return new StyleContentView({
              className: 'Editor-content',
              userActions: self._userActions,
              layerDefinitionsCollection: self._layerDefinitionsCollection,
              layerDefinitionModel: self._layerDefinitionModel,
              styleModel: self._styleModel,
              modals: self._modals,
              configModel: self._configModel,
              querySchemaModel: self._querySchemaModel,
              editorModel: self._editorModel,
              overlayModel: self._overlayModel,
              freezeTorgeAggregation: self._freezeTorgeAggregation.bind(self)
            });
          }
        });
      },
      createActionView: function () {
        return new UndoButtons({
          trackModel: self._styleModel,
          editorModel: self._editorModel,
          applyButton: false
        });
      }
    }, {
      selected: this._layerDefinitionModel.get('cartocss_custom'),
      createContentView: function () {
        return new StyleCartoCSSView({
          layerDefinitionModel: self._layerDefinitionModel,
          styleModel: self._styleModel,
          editorModel: self._editorModel,
          codemirrorModel: self._codemirrorModel,
          onApplyEvent: self._saveCartoCSS.bind(self)
        });
      },
      createActionView: function () {
        return new UndoButtons({
          trackModel: self._cartocssModel,
          editorModel: self._editorModel,
          applyButton: true,
          onApplyClick: self._saveCartoCSS.bind(self)
        });
      }
    }];

    this._collectionPane = new TabPaneCollection(tabPaneTabs);
  },

  _isLayerHidden: function () {
    return this._layerDefinitionModel.get('visible') === false;
  },

  _infoboxState: function () {
    var edition = this._editorModel.get('edition');
    var cartocss_custom = this._layerDefinitionModel.get('cartocss_custom');

    if (!edition && cartocss_custom) {
      this._infoboxModel.set({state: 'confirm'});
      this._overlayModel.set({visible: true});
    } else if (!edition && this._isLayerHidden()) {
      this._infoboxModel.set({state: 'layer-hidden'});
      this._overlayModel.set({visible: true});
    } else {
      this._infoboxModel.set({state: ''});
      this._overlayModel.set({visible: false});
    }
  },

  _showHiddenLayer: function () {
    this._layerDefinitionModel.toggleVisible();
    this._userActions.saveLayer(this._layerDefinitionModel);

    this._infoboxState();
  },

  _initViews: function () {
    var self = this;

    var infoboxSstates = [
      {
        state: 'confirm',
        createContentView: function () {
          return Infobox.createConfirmAndCancel({
            type: 'alert',
            title: _t('editor.style.messages.cartocss-applied.title'),
            body: _t('editor.style.messages.cartocss-applied.body'),
            cancelLabel: _t('editor.style.messages.cartocss-applied.cancel'),
            confirmLabel: _t('editor.style.messages.cartocss-applied.accept')
          });
        },
        mainAction: self._cancelApplyStyles.bind(self),
        secondAction: self._confirmApplyStyles.bind(self)
      }, {
        state: 'layer-hidden',
        createContentView: function () {
          return Infobox.createConfirm({
            type: 'alert',
            title: _t('editor.style.messages.layer-hidden.title'),
            body: _t('editor.style.messages.layer-hidden.body'),
            confirmLabel: _t('editor.style.messages.layer-hidden.show'),
            confirmType: 'button'
          });
        },
        mainAction: self._showHiddenLayer.bind(self)
      }, {
        state: 'torque-exists',
        createContentView: function () {
          return Infobox.createConfirmAndCancel({
            type: 'alert',
            title: _t('editor.style.messages.torque-exists.title'),
            body: _t('editor.style.messages.torque-exists.body'),
            cancelLabel: _t('editor.style.messages.torque-exists.cancel'),
            confirmLabel: _t('editor.style.messages.torque-exists.accept')
          });
        },
        mainAction: self._cancelTorqueAggregation.bind(self),
        secondAction: self._applyTorqueAggregation.bind(self)
      }
    ];

    var infoboxCollection = new InfoboxCollection(infoboxSstates);

    var panelWithOptionsView = new PanelWithOptionsView({
      className: 'Editor-content',
      editorModel: self._editorModel,
      infoboxModel: self._infoboxModel,
      infoboxCollection: infoboxCollection,
      createContentView: function () {
        return new TabPaneView({
          collection: self._collectionPane
        });
      },
      createControlView: function () {
        return new Toggler({
          editorModel: self._editorModel,
          labels: [_t('editor.style.style-toggle.values'), _t('editor.style.style-toggle.cartocss')],
          isDisableable: true
        });
      },
      createActionView: function () {
        return new TabPaneView({
          collection: self._collectionPane,
          createContentKey: 'createActionView'
        });
      }
    });

    this.$el.append(panelWithOptionsView.render().el);
    this.addView(panelWithOptionsView);
  }

});
<|endoftext|>


<commit_before><commit_msg>Add gulpfile tasks<commit_after>var browserify = require('browserify');
var del = require('del');
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var reactify = require('reactify');
var sass = require('gulp-sass');
var source = require('vinyl-source-stream');
// var uglify = require('gulp-uglify');
var watchify = require('watchify');

var production = process.env.NODE_ENV === 'production';

var build = function(watch) {
  var bundler;

  bundler = browserify('./app.js', {
    basedir: __dirname,
    debug: !production,
    cache: {}, // required for watchify
    packageCache: {}, // required for watchify
    fullPaths: watch // required to be true only for watchify
  });

  if(watch) {
    bundler = watchify(bundler);
  }

  bundler.transform(reactify);

  var rebundle = function() {
    var stream = bundler.bundle();
    stream.on('error', function (err) {
      console.log('Error with Browserify:', err);
    });
    stream = stream.pipe(source('bundle.js'));
    return stream.pipe(gulp.dest('./public/js'));
  };

  bundler.on('update', rebundle);
  return rebundle();
};

gulp.task('clean:js', function() {
  del(['./public/js/*']);
});

gulp.task('clean:css', function() {
  del(['./public/css/*']);
});

gulp.task('clean:fonts', function() {
  del(['./public/fonts/*']);
});

gulp.task('font-awesome:fonts', ['clean:fonts'], function() {
  gulp.src('node_modules/font-awesome/fonts/*')
    .pipe(gulp.dest('./public/fonts'));
});

gulp.task('css', ['clean:css'], function() {
  gulp.src('sass/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./public/css'));

  gulp.src('node_modules/font-awesome/css/font-awesome.min.css')
    .pipe(gulp.dest('./public/css'));
});

gulp.task('build:js', ['clean:js'], function() {
  return build(false);
});

gulp.task('watch:js', ['clean:js'], function() {
  return build(true);
});

gulp.task('serve', ['watch:js', 'css', 'font-awesome:fonts'], function() {
  gulp.watch('sass/*.scss', ['css']);
  return nodemon({script: 'server.js'});
});

gulp.task('build', ['build:js', 'css', 'font-awesome:fonts'], function() {
  return;
});
<|endoftext|>


<commit_before>// Initialize teams DataTable
function initTeamsTable() {
  teamsDatatable = $('#teams-table').DataTable({
    order: [[0, 'asc']],
    dom: 'RBltpi',
    stateSave: true,
    buttons: [],
    processing: true,
    serverSide: true,
    ajax: {
      url: $('#teams-table').data('source'),
      type: 'POST'
    },
    colReorder: {
      fixedColumnsLeft: 1000000 // Disable reordering
    },
    columnDefs: [{
      targets: [0, 1],
      orderable: true,
      searchable: false
    }, {
      targets: [2],
      searchable: false,
      orderable: true
    }, {
      targets: [3],
      searchable: false,
      orderable: false,
      sWidth: '1%'
    }]
  });
}

initTeamsTable();
<commit_msg>Fix code style issues [SCI-936]<commit_after>// Initialize teams DataTable
function initTeamsTable() {
  teamsDatatable = $('#teams-table').DataTable({
    order: [[0, 'asc']],
    dom: 'RBltpi',
    stateSave: true,
    buttons: [],
    processing: true,
    serverSide: true,
    ajax: {
      url: $('#teams-table').data('source'),
      type: 'POST'
    },
    colReorder: {
      fixedColumnsLeft: 1000000 // Disable reordering
    },
    columnDefs: [{
      targets: [0, 1],
      orderable: true,
      searchable: false
    }, {
      targets: 2,
      searchable: false,
      orderable: true
    }, {
      targets: 3,
      searchable: false,
      orderable: false,
      sWidth: '1%'
    }]
  });
}

initTeamsTable();
<|endoftext|>


<commit_before>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

"use strict";

/* global window, chrome, browser */

let hasBrowserAPIs = (typeof browser != "undefined");

// Debugging - Edge won't let us see errors during startup, log them.
window.loggedErrors = [];
window.onerror = function(...args)
{
  window.loggedErrors.push(args);
};

// TextEncoder and TextDecoder are unsupported in Edge
if (typeof window.TextEncoder == "undefined")
{
  window.TextEncoder = function(encoding)
  {
    if (encoding != "utf-8")
      throw new Error("Unsupported encoding");
  };
  window.TextEncoder.prototype = {
    encode: function(str)
    {
      let bytes = [];
      let encoded = window.encodeURIComponent(str);
      for (let i = 0; i < encoded.length; i++)
      {
        if (encoded[i] == "%")
        {
          bytes.push(parseInt(encoded.substr(i + 1, 2), 16));
          i += 2;
        }
        else
          bytes.push(encoded.charCodeAt(i));
      }
      return Uint8Array.from(bytes);
    }
  };
}

if (typeof window.TextDecoder == "undefined")
{
  window.TextDecoder = function(encoding)
  {
    if (encoding != "utf-8")
      throw new Error("Unsupported encoding");
  };
  window.TextDecoder.prototype = {
    decode: function(buffer)
    {
      let bytes = [];
      for (let i = 0; i < buffer.length; i++)
        bytes.push((buffer[i] < 16 ? "%0" : "%") + buffer[i].toString(16));
      return window.decodeURIComponent(bytes.join(""));
    }
  };
}

function promisify(method, numArgs, ...args)
{
  return new Promise((resolve, reject) =>
  {
    if (args.length != numArgs)
    {
      throw new Error("Unexpected number of arguments: got " + args.length +
                      ", expected " + numArgs);
    }

    this[method](...args, result =>
    {
      if (exports.runtime.lastError)
        reject(exports.runtime.lastError.message);
      else
        resolve(result);
    });
  });
}

if (hasBrowserAPIs && typeof browser.storage != "undefined")
{
  try
  {
    browser.storage.local.get("dummy");

    // The above didn't throw, meaning we can use browser.storage directly.
    exports.storage = browser.storage;
  }
  catch (e)
  {
    // browser.storage API expects callbacks on Edge, see
    // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9420301/
    let storage = browser.storage.local;
    exports.storage = {
      local: {
        get: promisify.bind(storage, "get", 1),
        getBytesInUse: promisify.bind(storage, "getBytesInUse", 1),
        set: promisify.bind(storage, "set", 1),
        remove: promisify.bind(storage, "remove", 1),
        clear: promisify.bind(storage, "clear", 0)
      }
    };
  }
}
else
{
  exports.storage = {
    local: {
      get: promisify.bind(chrome.storage.local, "get", 1),
      getBytesInUse: promisify.bind(chrome.storage.local, "getBytesInUse", 1),
      set: promisify.bind(chrome.storage.local, "set", 1),
      remove: promisify.bind(chrome.storage.local, "remove", 1),
      clear: promisify.bind(chrome.storage.local, "clear", 0)
    }
  };
}

if (hasBrowserAPIs && typeof browser.tabs != "undefined")
{
  try
  {
    browser.tabs.query({});

    // The above didn't throw, meaning we can use browser.tabs directly.
    exports.tabs = browser.tabs;
  }
  catch (e)
  {
    // browser.tabs API expects callbacks on Edge, see
    // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9421085/
    let tabs = browser.tabs;
    exports.tabs = {
      query: promisify.bind(tabs, "query", 1),
      create: promisify.bind(tabs, "create", 1),
      remove: promisify.bind(tabs, "remove", 1),
      update: promisify.bind(tabs, "update", 2),
      executeScript: promisify.bind(tabs, "executeScript", 2),
      sendMessage: promisify.bind(tabs, "sendMessage", 2),
      onUpdated: tabs.onUpdated,
      onRemoved: tabs.onRemoved
    };
  }
}
else
{
  exports.tabs = {
    query: promisify.bind(chrome.tabs, "query", 1),
    create: promisify.bind(chrome.tabs, "create", 1),
    remove: promisify.bind(chrome.tabs, "remove", 1),
    update: promisify.bind(chrome.tabs, "update", 2),
    executeScript: promisify.bind(chrome.tabs, "executeScript", 2),
    sendMessage: promisify.bind(chrome.tabs, "sendMessage", 2),
    onUpdated: chrome.tabs.onUpdated,
    onRemoved: chrome.tabs.onRemoved
  };
}

if (hasBrowserAPIs && typeof browser.runtime != "undefined")
  exports.runtime = browser.runtime;
else
  exports.runtime = chrome.runtime;
<commit_msg>Fixed decrypting legacy passwords in Edge<commit_after>/*
 * This Source Code is subject to the terms of the Mozilla Public License
 * version 2.0 (the "License"). You can obtain a copy of the License at
 * http://mozilla.org/MPL/2.0/.
 */

"use strict";

/* global window, chrome, browser */

let hasBrowserAPIs = (typeof browser != "undefined");

// Debugging - Edge won't let us see errors during startup, log them.
window.loggedErrors = [];
window.onerror = function(...args)
{
  window.loggedErrors.push(args);
};

// TextEncoder and TextDecoder are unsupported in Edge
if (typeof window.TextEncoder == "undefined")
{
  window.TextEncoder = function(encoding)
  {
    if (encoding != "utf-8")
      throw new Error("Unsupported encoding");
  };
  window.TextEncoder.prototype = {
    encode: function(str)
    {
      let bytes = [];
      let encoded = window.encodeURIComponent(str);
      for (let i = 0; i < encoded.length; i++)
      {
        if (encoded[i] == "%")
        {
          bytes.push(parseInt(encoded.substr(i + 1, 2), 16));
          i += 2;
        }
        else
          bytes.push(encoded.charCodeAt(i));
      }
      return Uint8Array.from(bytes);
    }
  };
}

if (typeof window.TextDecoder == "undefined")
{
  window.TextDecoder = function(encoding)
  {
    if (encoding != "utf-8")
      throw new Error("Unsupported encoding");
  };
  window.TextDecoder.prototype = {
    decode: function(buffer)
    {
      let array = new Uint8Array(buffer);
      let bytes = [];
      for (let i = 0; i < array.length; i++)
        bytes.push((array[i] < 16 ? "%0" : "%") + array[i].toString(16));
      return window.decodeURIComponent(bytes.join(""));
    }
  };
}

function promisify(method, numArgs, ...args)
{
  return new Promise((resolve, reject) =>
  {
    if (args.length != numArgs)
    {
      throw new Error("Unexpected number of arguments: got " + args.length +
                      ", expected " + numArgs);
    }

    this[method](...args, result =>
    {
      if (exports.runtime.lastError)
        reject(exports.runtime.lastError.message);
      else
        resolve(result);
    });
  });
}

if (hasBrowserAPIs && typeof browser.storage != "undefined")
{
  try
  {
    browser.storage.local.get("dummy");

    // The above didn't throw, meaning we can use browser.storage directly.
    exports.storage = browser.storage;
  }
  catch (e)
  {
    // browser.storage API expects callbacks on Edge, see
    // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9420301/
    let storage = browser.storage.local;
    exports.storage = {
      local: {
        get: promisify.bind(storage, "get", 1),
        getBytesInUse: promisify.bind(storage, "getBytesInUse", 1),
        set: promisify.bind(storage, "set", 1),
        remove: promisify.bind(storage, "remove", 1),
        clear: promisify.bind(storage, "clear", 0)
      }
    };
  }
}
else
{
  exports.storage = {
    local: {
      get: promisify.bind(chrome.storage.local, "get", 1),
      getBytesInUse: promisify.bind(chrome.storage.local, "getBytesInUse", 1),
      set: promisify.bind(chrome.storage.local, "set", 1),
      remove: promisify.bind(chrome.storage.local, "remove", 1),
      clear: promisify.bind(chrome.storage.local, "clear", 0)
    }
  };
}

if (hasBrowserAPIs && typeof browser.tabs != "undefined")
{
  try
  {
    browser.tabs.query({});

    // The above didn't throw, meaning we can use browser.tabs directly.
    exports.tabs = browser.tabs;
  }
  catch (e)
  {
    // browser.tabs API expects callbacks on Edge, see
    // https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9421085/
    let tabs = browser.tabs;
    exports.tabs = {
      query: promisify.bind(tabs, "query", 1),
      create: promisify.bind(tabs, "create", 1),
      remove: promisify.bind(tabs, "remove", 1),
      update: promisify.bind(tabs, "update", 2),
      executeScript: promisify.bind(tabs, "executeScript", 2),
      sendMessage: promisify.bind(tabs, "sendMessage", 2),
      onUpdated: tabs.onUpdated,
      onRemoved: tabs.onRemoved
    };
  }
}
else
{
  exports.tabs = {
    query: promisify.bind(chrome.tabs, "query", 1),
    create: promisify.bind(chrome.tabs, "create", 1),
    remove: promisify.bind(chrome.tabs, "remove", 1),
    update: promisify.bind(chrome.tabs, "update", 2),
    executeScript: promisify.bind(chrome.tabs, "executeScript", 2),
    sendMessage: promisify.bind(chrome.tabs, "sendMessage", 2),
    onUpdated: chrome.tabs.onUpdated,
    onRemoved: chrome.tabs.onRemoved
  };
}

if (hasBrowserAPIs && typeof browser.runtime != "undefined")
  exports.runtime = browser.runtime;
else
  exports.runtime = chrome.runtime;
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Workflowier
// @namespace    Workflowier
// @include      https://workflowy.com/*
// @author       Nick Busey
// @description  User Script for Workflowy.com that adds some extra features.
// @version      0.0.1.5
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
    var script = document.createElement("script");
    script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
    script.addEventListener('load', function() {
        var script = document.createElement("script");
        script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
        document.body.appendChild(script);
    }, false);
    document.body.appendChild(script);
}

searching = false;

// the guts of this userscript
function main() {
    // Note, jQ replaces jQ to avoid conflicts.
    // Insert recent links
    var recentLinks = "
"+
    "

This Week

"+
    "

Today

"+
    "

Last Hour

"+
    "
";
    jQ('#savedViewHUDButton').after("

Recent

"+recentLinks);

    jQ('#showRecentLinks').click(function() {jQ('#recentLinksMenu').slideToggle()});

    jQ('#recentLink_1wk').click(function(e) {
        e.preventDefault();
        if (jQ('#searchBox').val()=='last-changed:7d') {
            search.searchProjectTree('');
        } else {
            search.searchProjectTree('last-changed:7d');
        }
    });
    jQ('#recentLink_24hrs').click(function(e) {
        e.preventDefault();
        if (jQ('#searchBox').val()=='last-changed:1d') {
            search.searchProjectTree('');
        } else {
            search.searchProjectTree('last-changed:1d');
        }
    });
    jQ('#recentLink_1hr').click(function(e) {
        e.preventDefault();
        if (jQ('#searchBox').val()=='last-changed:1h') {
            search.searchProjectTree('');
        } else {
            search.searchProjectTree('last-changed:1h');
        }
    });
    var generateTagsMenu = function() {
        var currentSearch = jQ('#searchBox').val();
        search.searchProjectTree('#');
        var tags = $('.contentTagText');
        // Generate list of all hashtags
        var tagObjs = {};
        tags.each(function(ii, obj) {
            // console.log(obj);
            // console.log(jQ(obj).text());
            var tag = jQ(obj).text();

            var tagObj = tagObjs[tag];
            // console.log(tag,' - ',tagObj);
            if (!tagObj) {
                //   console.log("No tag object, make an empty one.")
                tagObj = {'count':1};
            } else {
                tagObj['count']++;
            }
            tagObjs[tag] = tagObj;
        });
        //   console.log(tagObjs);
        var tagObjsArray = [];
        for (var tag in tagObjs) {
            var tagObj = tagObjs[tag];
            tagObj['tag'] = tag;
            // console.log(tag,tagObj);
            tagObjsArray.push(tagObj);
        }
        //   console.log(tagObjsArray);
        var sortedTagObjsArray = tagObjsArray.sort(function (a, b) {
            return b.count - a.count;
        });
        globTest = sortedTagObjsArray;
        //   console.log(sortedTagObjsArray);
        var tagLinkOutput = '';
        for (var ii in sortedTagObjsArray) {
            var count = sortedTagObjsArray[ii]['count'];
            var tag = sortedTagObjsArray[ii]['tag'];
            tagLinkOutput += ""+count+" #"+tag+"";
        }
        //   console.log(tagLinkOutput);
        var menu = "
"+tagLinkOutput+"
";

        jQ('#savedViewHUDButton').after("

View Tags

"+menu);
        jQ('#openTags').click(function() {jQ('#tagsMenu').slideToggle()});
        search.searchProjectTree(currentSearch);

    };

    // search.searchProjectTree('#daily-teeth');
    // var total = $('.contentMatch').size()/2;
    // search.searchProjectTree('#daily-teeth is:complete');
    // var done = $('.contentMatch').size()/2;
    // console.log(total,done);
    // console.log(done/total);
    // var pct = done/total;

    var attemptTags = function() {
        setTimeout(function() {
            try {
                // console.log('Generate tags');
                generateTagsMenu();
            } catch(e) {
                // console.log("Got exception",e);
                attemptTags();
            }
        },500);
    };

    attemptTags();

    // Add -rand functionality
    jQ(window).on('hashchange',function(e) {
        if (searching) {
            return false;
        }

        var query = jQ('#searchBox').val();
        var needle=/(%23\w*-rand)+/;
        var match = window.location.href.match(needle);
        if (match) {
            // A tag with -rand on the end has been clicked. Locate another.
            searching = true;
            var tag = match[0]; //matches "2 chapters"
            tag = "#"+tag.slice(3);
            window.location.href='/#';
            search.searchProjectTree(tag);
            var target = null;
            var count = 0;
            var tags = $('.contentMatch');
            var random = $(tags[Math.floor(Math.random()*tags.length)])[0];
            var parent = jQ(random).parents('.name').find('a').first();
            var href = jQ(parent).attr('href');
            window.location.href = href;
            setTimeout(function() {
                searching = false;
            },100);
        }
    });

    // Add styles
    jQ('body').append("");
}

// load jQuery and execute the main function
addJQuery(main);
<commit_msg>Adding updateURL<commit_after>// ==UserScript==
// @name         Workflowier
// @namespace    Workflowier
// @include      https://workflowy.com/*
// @author       Nick Busey
// @description  User Script for Workflowy.com that adds some extra features.
// @version      0.0.1.6
// @updateURL    https://greasyfork.org/scripts/18496-workflowier/code/Workflowier.user.js
// ==/UserScript==

// a function that loads jQuery and calls a callback function when jQuery has finished loading
function addJQuery(callback) {
    var script = document.createElement("script");
    script.setAttribute("src", "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js");
    script.addEventListener('load', function() {
        var script = document.createElement("script");
        script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
        document.body.appendChild(script);
    }, false);
    document.body.appendChild(script);
}

searching = false;

// the guts of this userscript
function main() {
    // Note, jQ replaces jQ to avoid conflicts.
    // Insert recent links
    var recentLinks = "
"+
    "

This Week

"+
    "

Today

"+
    "

Last Hour

"+
    "
";
    jQ('#savedViewHUDButton').after("

Recent

"+recentLinks);

    jQ('#showRecentLinks').click(function() {jQ('#recentLinksMenu').slideToggle()});

    jQ('#recentLink_1wk').click(function(e) {
        e.preventDefault();
        if (jQ('#searchBox').val()=='last-changed:7d') {
            search.searchProjectTree('');
        } else {
            search.searchProjectTree('last-changed:7d');
        }
    });
    jQ('#recentLink_24hrs').click(function(e) {
        e.preventDefault();
        if (jQ('#searchBox').val()=='last-changed:1d') {
            search.searchProjectTree('');
        } else {
            search.searchProjectTree('last-changed:1d');
        }
    });
    jQ('#recentLink_1hr').click(function(e) {
        e.preventDefault();
        if (jQ('#searchBox').val()=='last-changed:1h') {
            search.searchProjectTree('');
        } else {
            search.searchProjectTree('last-changed:1h');
        }
    });
    var generateTagsMenu = function() {
        var currentSearch = jQ('#searchBox').val();
        search.searchProjectTree('#');
        var tags = $('.contentTagText');
        // Generate list of all hashtags
        var tagObjs = {};
        tags.each(function(ii, obj) {
            // console.log(obj);
            // console.log(jQ(obj).text());
            var tag = jQ(obj).text();

            var tagObj = tagObjs[tag];
            // console.log(tag,' - ',tagObj);
            if (!tagObj) {
                //   console.log("No tag object, make an empty one.")
                tagObj = {'count':1};
            } else {
                tagObj['count']++;
            }
            tagObjs[tag] = tagObj;
        });
        //   console.log(tagObjs);
        var tagObjsArray = [];
        for (var tag in tagObjs) {
            var tagObj = tagObjs[tag];
            tagObj['tag'] = tag;
            // console.log(tag,tagObj);
            tagObjsArray.push(tagObj);
        }
        //   console.log(tagObjsArray);
        var sortedTagObjsArray = tagObjsArray.sort(function (a, b) {
            return b.count - a.count;
        });
        globTest = sortedTagObjsArray;
        //   console.log(sortedTagObjsArray);
        var tagLinkOutput = '';
        for (var ii in sortedTagObjsArray) {
            var count = sortedTagObjsArray[ii]['count'];
            var tag = sortedTagObjsArray[ii]['tag'];
            tagLinkOutput += ""+count+" #"+tag+"";
        }
        //   console.log(tagLinkOutput);
        var menu = "
"+tagLinkOutput+"
";

        jQ('#savedViewHUDButton').after("

View Tags

"+menu);
        jQ('#openTags').click(function() {jQ('#tagsMenu').slideToggle()});
        search.searchProjectTree(currentSearch);

    };

    // search.searchProjectTree('#daily-teeth');
    // var total = $('.contentMatch').size()/2;
    // search.searchProjectTree('#daily-teeth is:complete');
    // var done = $('.contentMatch').size()/2;
    // console.log(total,done);
    // console.log(done/total);
    // var pct = done/total;

    var attemptTags = function() {
        setTimeout(function() {
            try {
                // console.log('Generate tags');
                generateTagsMenu();
            } catch(e) {
                // console.log("Got exception",e);
                attemptTags();
            }
        },500);
    };

    attemptTags();

    // Add -rand functionality
    jQ(window).on('hashchange',function(e) {
        if (searching) {
            return false;
        }

        var query = jQ('#searchBox').val();
        var needle=/(%23\w*-rand)+/;
        var match = window.location.href.match(needle);
        if (match) {
            // A tag with -rand on the end has been clicked. Locate another.
            searching = true;
            var tag = match[0]; //matches "2 chapters"
            tag = "#"+tag.slice(3);
            window.location.href='/#';
            search.searchProjectTree(tag);
            var target = null;
            var count = 0;
            var tags = $('.contentMatch');
            var random = $(tags[Math.floor(Math.random()*tags.length)])[0];
            var parent = jQ(random).parents('.name').find('a').first();
            var href = jQ(parent).attr('href');
            window.location.href = href;
            setTimeout(function() {
                searching = false;
            },100);
        }
    });

    // Add styles
    jQ('body').append("");
}

// load jQuery and execute the main function
addJQuery(main);
<|endoftext|>


<commit_before>// Navigation 1.0 ALPHA
//
// * Highlights the appropriate element in the navigation when scrolling through the page
// * Scrolls to appropriate section of the page when the navigation is clicked

var sections = [];
var articleSections = $();
var autoscrolling = false;

$(document).ready(function(){

  $("nav").on("click","a",function(){
    $(".selected").removeClass("selected");
    $(this).addClass("selected");
    var section = $(this).attr("href");

    autoscrolling = true;

    $('html, body').animate({
        scrollTop: $(section).offset().top
    }, 500, function(){
      autoscrolling = false;
      window.location.hash = section;
    });

    return false;
  });

  $("nav a").each(function(i,el){
    var sectionName = $(el).attr("href");
    if(sectionName.length > 0) {
      sectionName = sectionName.replace("#","").toLowerCase();
      sections.push(sectionName);
    }
  });

  var jam = $("article *[id]");
  $(jam).each(function(i,el){
    var id = $(el).attr("id");
    id = id.replace("#","").toLowerCase();
    if(sections.indexOf(id) > -1) {
      articleSections.push(el);
    }
  });

  $(window).on("scroll",function(){
    if(autoscrolling == false) {
      scroll();
    }
  });

  // Get the modal
//var modal = document.getElementById("myModal");
var modal = document.getElementByClassName("modal")

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementByClassName("modal-img");
var modalImg = document.getElementByClassName("modal-content");
var captionText = document.getElementByClassName"modal-caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

});

function scroll(){
  articleSections.each(function(i,el){
    var windowTop = $(window).scrollTop();
    var offset = $(el).offset();
    var fromTop = offset.top - windowTop;
    if(fromTop > 0 && fromTop < 400) {
      var id = $(el).attr('id');
      id = id.toLowerCase().replace("#","");
      $("nav .selected").removeClass("selected");
      $("nav a[href=#"+id+"]").addClass("selected");
    }
  });
}
<commit_msg>fix typo<commit_after>// Navigation 1.0 ALPHA
//
// * Highlights the appropriate element in the navigation when scrolling through the page
// * Scrolls to appropriate section of the page when the navigation is clicked

var sections = [];
var articleSections = $();
var autoscrolling = false;

$(document).ready(function(){

  $("nav").on("click","a",function(){
    $(".selected").removeClass("selected");
    $(this).addClass("selected");
    var section = $(this).attr("href");

    autoscrolling = true;

    $('html, body').animate({
        scrollTop: $(section).offset().top
    }, 500, function(){
      autoscrolling = false;
      window.location.hash = section;
    });

    return false;
  });

  $("nav a").each(function(i,el){
    var sectionName = $(el).attr("href");
    if(sectionName.length > 0) {
      sectionName = sectionName.replace("#","").toLowerCase();
      sections.push(sectionName);
    }
  });

  var jam = $("article *[id]");
  $(jam).each(function(i,el){
    var id = $(el).attr("id");
    id = id.replace("#","").toLowerCase();
    if(sections.indexOf(id) > -1) {
      articleSections.push(el);
    }
  });

  $(window).on("scroll",function(){
    if(autoscrolling == false) {
      scroll();
    }
  });

  // Get the modal
//var modal = document.getElementById("myModal");
var modal = document.getElementByClassName("modal")

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementByClassName("modal-img");
var modalImg = document.getElementByClassName("modal-content");
var captionText = document.getElementByClassName("modal-caption");
img.onclick = function(){
  modal.style.display = "block";
  modalImg.src = this.src;
  captionText.innerHTML = this.alt;
}

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
  modal.style.display = "none";
}

});

function scroll(){
  articleSections.each(function(i,el){
    var windowTop = $(window).scrollTop();
    var offset = $(el).offset();
    var fromTop = offset.top - windowTop;
    if(fromTop > 0 && fromTop < 400) {
      var id = $(el).attr('id');
      id = id.toLowerCase().replace("#","");
      $("nav .selected").removeClass("selected");
      $("nav a[href=#"+id+"]").addClass("selected");
    }
  });
}
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var DIR         = __dirname + '/',
        os          = require('os'),
        crypto      = require('crypto'),
        fs          = require('fs'),
        path        = require('path'),

        mkdirp      = require('mkdirp'),
        ischanged   = require('ischanged'),
        Util        = require('util-io'),
        type        = Util.type,
        ponse       = require('ponse'),

        log       = require('debug')('minify'),

        modules     = {},

        WIN         = process.platform === 'win32',

        ERROR_MSG   = 'File type "{{ ext }}" not supported.',

        MinFolder   = getDir() || DIR + 'min/';

        ['js', 'html', 'css', 'img'].forEach(function(name) {
            modules[name] = require(DIR + name);
        });

    module.exports  = minify;

    function optimizeData(params, callback) {
        var p   = params,
            ext = p.ext.slice(1);

        modules[ext](p.data, callback);
    }

    function minify(name, options, callback) {
        var isChanged, isExist, ret, ext, is,
            EXT         = ['js', 'html', 'css'],
            isObject    = type.object(name),
            exec        = Util.exec,
            nameMin     = getName(name);

        if (!callback)
            callback = options;

        if (!options && !callback)
            ret = middle.bind(null, name);
        else if (isObject) {
            optimizeData(name, callback);
        } else {
            ext         = path.extname(name).slice(1);
            is          = ~EXT.indexOf(ext);

            if (!is) {
                callback(Error(Util.render(ERROR_MSG, {
                    ext: ext
                })));
            } else {
                isChanged   = exec.with(ischanged, name),
                isExist     = exec.with(fs.lstat, nameMin);

                exec.parallel([isChanged, isExist], function(error, changed, exists) {
                    if (changed || !exists)
                        optimize(name, options, callback);
                    else
                        if (options.returnName)
                            callback(null, nameMin);
                        else if (options.returnStream)
                            callback(null, fs.createReadStream(nameMin));
                        else
                            fs.readFile(nameMin, 'utf8', callback);
                });
            }
        }

        return ret;
    }

    function getDir() {
        var dir;

        if (os.tmpdir) {
            dir     = os.tmpdir();
            dir     += '/minify';

            if (!WIN)
                dir += '/' + process.getuid();

            dir     += '/';
        }

        return dir;
    }

    function makeDir(callback) {
        var ANY_MASK    = 0,
            umask       = process.umask(ANY_MASK);

        mkdirp('/' + MinFolder, function(error) {
            process.umask(umask);

            if (error && error.code === 'EEXIST')
                callback();
            else
                callback(error);
        });
    }

    function middle(options, req, res, next) {
        var isMinify, dir, is, isFunction,
            name        = req.url,
            isExt       = Util.checkExt(name, ['js', 'css', 'html']);

        Util.check([options], ['options']);

        is              = options.is;
        dir             = options.dir || './';

        isFunction      = type.function(is);
        name            = path.join(dir, name);

        if (isFunction)
            isMinify    = is();
        else
            isMinify    = is || type.undefined(is);

        if (!isExt || !isMinify)
            next();
        else
            minify(name, {
                returnName  : true
            }, function(error, name) {
                if (error)
                    next();
                else
                    ponse.sendFile({
                        request: req,
                        response: res,
                        name: name,
                        gzip: true,
                        cache:true,
                    });
            });
    }

    /**
     * function minificate js,css and html files
     *
     * @param files     -   js, css or html file path
     * @param options   -   object contain main options
     */
    function optimize(file, options, callback) {
        if (!callback)
            callback = options;

        Util.check(arguments, ['file', 'callback']);

        makeDir(function(error) {
            var name,
                isObj   = type.object(file);

            if (error)
                log(error);

            if (isObj)
                name    = Object.keys(file)[0];
            else
                name    = file;

            log('reading file' + path.basename(name));

            fs.readFile(name, 'utf8', function(error, data) {
                if (error)
                    callback(error);
                else
                    onDataRead(file, data, options, callback);
            });
        });
    }

   /**
    * Processing of files
    * @param fileData {name, data}
    */
    function onDataRead(filename, data, options, callback) {
        var ext, minFileName,
            readFilesCount  = 0,
            returnName      = options.returnName;

        log('file ' + path.basename(filename) + ' read');

        ext         = path.extname(filename);
        minFileName = getName(filename, ext);

        optimizeData({
            ext : ext,
            data: data
        }, function(error, data) {
            if (error)
                callback(error);
            else
                Util.exec.if(ext !== '.css', function(error, optimizedData) {
                    var isStr   = type.string(optimizedData);

                    if (isStr)
                        data    = optimizedData;

                    ++readFilesCount;

                    writeFile(minFileName, data, function(error, dataMin) {
                        if (returnName)
                            callback(error, minFileName);
                        else
                            callback(error, dataMin);
                        });
                    }, function(callback) {
                        modules.img(filename, data, callback);
                    });
            });
    }

    /**
     * function get name of file in min folder
     *
     * @param name
     * @param ext
     */
    function getName(name, ext) {
        var ret, minFileName;

        if (type.string(name)) {
            if (!ext)
                ext         = path.extname(name);

            minFileName = crypto.createHash('sha1')
                .update(name)
                .digest('hex') + ext;

            ret = MinFolder + minFileName;
        }

        return ret;
    }

    /*
     * Функция записывает файла
     * и выводит ошибку или сообщает,
     * что файл успешно записан
     */
    function writeFile(name, data, callback) {
        fs.writeFile(name, data, function(error) {
            var msg = 'file ' + path.basename(name) + ' written';

            log(error || msg);

            callback(error, data);
        });
    }

})();
<commit_msg>chore(minify) add " "<commit_after>(function() {
    'use strict';

    var DIR         = __dirname + '/',
        os          = require('os'),
        crypto      = require('crypto'),
        fs          = require('fs'),
        path        = require('path'),

        mkdirp      = require('mkdirp'),
        ischanged   = require('ischanged'),
        Util        = require('util-io'),
        type        = Util.type,
        ponse       = require('ponse'),

        log         = require('debug')('minify'),

        modules     = {},

        WIN         = process.platform === 'win32',

        ERROR_MSG   = 'File type "{{ ext }}" not supported.',

        MinFolder   = getDir() || DIR + 'min/';

        ['js', 'html', 'css', 'img'].forEach(function(name) {
            modules[name] = require(DIR + name);
        });

    module.exports  = minify;

    function optimizeData(params, callback) {
        var p   = params,
            ext = p.ext.slice(1);

        modules[ext](p.data, callback);
    }

    function minify(name, options, callback) {
        var isChanged, isExist, ret, ext, is,
            EXT         = ['js', 'html', 'css'],
            isObject    = type.object(name),
            exec        = Util.exec,
            nameMin     = getName(name);

        if (!callback)
            callback = options;

        if (!options && !callback)
            ret = middle.bind(null, name);
        else if (isObject) {
            optimizeData(name, callback);
        } else {
            ext         = path.extname(name).slice(1);
            is          = ~EXT.indexOf(ext);

            if (!is) {
                callback(Error(Util.render(ERROR_MSG, {
                    ext: ext
                })));
            } else {
                isChanged   = exec.with(ischanged, name),
                isExist     = exec.with(fs.lstat, nameMin);

                exec.parallel([isChanged, isExist], function(error, changed, exists) {
                    if (changed || !exists)
                        optimize(name, options, callback);
                    else
                        if (options.returnName)
                            callback(null, nameMin);
                        else if (options.returnStream)
                            callback(null, fs.createReadStream(nameMin));
                        else
                            fs.readFile(nameMin, 'utf8', callback);
                });
            }
        }

        return ret;
    }

    function getDir() {
        var dir;

        if (os.tmpdir) {
            dir     = os.tmpdir();
            dir     += '/minify';

            if (!WIN)
                dir += '/' + process.getuid();

            dir     += '/';
        }

        return dir;
    }

    function makeDir(callback) {
        var ANY_MASK    = 0,
            umask       = process.umask(ANY_MASK);

        mkdirp('/' + MinFolder, function(error) {
            process.umask(umask);

            if (error && error.code === 'EEXIST')
                callback();
            else
                callback(error);
        });
    }

    function middle(options, req, res, next) {
        var isMinify, dir, is, isFunction,
            name        = req.url,
            isExt       = Util.checkExt(name, ['js', 'css', 'html']);

        Util.check([options], ['options']);

        is              = options.is;
        dir             = options.dir || './';

        isFunction      = type.function(is);
        name            = path.join(dir, name);

        if (isFunction)
            isMinify    = is();
        else
            isMinify    = is || type.undefined(is);

        if (!isExt || !isMinify)
            next();
        else
            minify(name, {
                returnName  : true
            }, function(error, name) {
                if (error)
                    next();
                else
                    ponse.sendFile({
                        request: req,
                        response: res,
                        name: name,
                        gzip: true,
                        cache:true,
                    });
            });
    }

    /**
     * function minificate js,css and html files
     *
     * @param files     -   js, css or html file path
     * @param options   -   object contain main options
     */
    function optimize(file, options, callback) {
        if (!callback)
            callback = options;

        Util.check(arguments, ['file', 'callback']);

        makeDir(function(error) {
            var name,
                isObj   = type.object(file);

            if (error)
                log(error);

            if (isObj)
                name    = Object.keys(file)[0];
            else
                name    = file;

            log('reading file' + path.basename(name));

            fs.readFile(name, 'utf8', function(error, data) {
                if (error)
                    callback(error);
                else
                    onDataRead(file, data, options, callback);
            });
        });
    }

   /**
    * Processing of files
    * @param fileData {name, data}
    */
    function onDataRead(filename, data, options, callback) {
        var ext, minFileName,
            readFilesCount  = 0,
            returnName      = options.returnName;

        log('file ' + path.basename(filename) + ' read');

        ext         = path.extname(filename);
        minFileName = getName(filename, ext);

        optimizeData({
            ext : ext,
            data: data
        }, function(error, data) {
            if (error)
                callback(error);
            else
                Util.exec.if(ext !== '.css', function(error, optimizedData) {
                    var isStr   = type.string(optimizedData);

                    if (isStr)
                        data    = optimizedData;

                    ++readFilesCount;

                    writeFile(minFileName, data, function(error, dataMin) {
                        if (returnName)
                            callback(error, minFileName);
                        else
                            callback(error, dataMin);
                        });
                    }, function(callback) {
                        modules.img(filename, data, callback);
                    });
            });
    }

    /**
     * function get name of file in min folder
     *
     * @param name
     * @param ext
     */
    function getName(name, ext) {
        var ret, minFileName;

        if (type.string(name)) {
            if (!ext)
                ext         = path.extname(name);

            minFileName = crypto.createHash('sha1')
                .update(name)
                .digest('hex') + ext;

            ret = MinFolder + minFileName;
        }

        return ret;
    }

    /*
     * Функция записывает файла
     * и выводит ошибку или сообщает,
     * что файл успешно записан
     */
    function writeFile(name, data, callback) {
        fs.writeFile(name, data, function(error) {
            var msg = 'file ' + path.basename(name) + ' written';

            log(error || msg);

            callback(error, data);
        });
    }

})();
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var metal = require('gulp-metal');

metal.registerTasks({
	bundleCssFileName: 'senna.css',
	bundleFileName: 'senna.js',
	globalName: 'senna',
	mainBuildJsTasks: ['build:globals'],
	moduleName: 'senna',
	testBrowsers: ['Chrome', 'Firefox', 'Safari', 'IE10 - Win7', 'IE11 - Win7'],
	testSaucelabsBrowsers: {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_safari_8: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '8'
		},
		sl_safari_9: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '9'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '7.1'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	}
});

gulp.task('default', ['build:globals', 'build:amd']);<commit_msg>Updates saucelabs to test on IOS 9.2<commit_after>'use strict';

var gulp = require('gulp');
var metal = require('gulp-metal');

metal.registerTasks({
	bundleCssFileName: 'senna.css',
	bundleFileName: 'senna.js',
	globalName: 'senna',
	mainBuildJsTasks: ['build:globals'],
	moduleName: 'senna',
	testBrowsers: ['Chrome', 'Firefox', 'Safari', 'IE10 - Win7', 'IE11 - Win7'],
	testSaucelabsBrowsers: {
		sl_chrome: {
			base: 'SauceLabs',
			browserName: 'chrome'
		},
		sl_safari_8: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '8'
		},
		sl_safari_9: {
			base: 'SauceLabs',
			browserName: 'safari',
			version: '9'
		},
		sl_firefox: {
			base: 'SauceLabs',
			browserName: 'firefox'
		},
		sl_ie_10: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 7',
			version: '10'
		},
		sl_ie_11: {
			base: 'SauceLabs',
			browserName: 'internet explorer',
			platform: 'Windows 8.1',
			version: '11'
		},
		sl_iphone: {
			base: 'SauceLabs',
			browserName: 'iphone',
			platform: 'OS X 10.10',
			version: '9.2'
		},
		sl_android_4: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '4.4'
		},
		sl_android_5: {
			base: 'SauceLabs',
			browserName: 'android',
			platform: 'Linux',
			version: '5.0'
		}
	}
});

gulp.task('default', ['build:globals', 'build:amd']);<|endoftext|>


<commit_before>var Commuter = require('commuter');
var historyPolyfill = require('html5-history-api');
var onLoad = require('on-load');
var page = require('page');
var Plan = require('plan');
var utils = require('router-utils');
var session = require('session');

page('/', utils.redirect('/planner'));

page('/login', require('commuter-login'));
page('/forgot-password', require('forgot-password-page'));
page('/change-password/:key', require('change-password-page'));
page('/confirm-email/:key', Commuter.confirmEmail, utils.redirect('/login'));

page('/planner', session.commuterIsLoggedIn, Plan.load, require('planner-page'));
page('/planner/:link', session.loginWithLink, utils.redirect('/planner'));

page('/style-guide', require('style-guide'));

page('/t/:code', function(ctx, next) {
  session.loginAnonymously(function(err) {
    window.analytics.page(ctx.code, 'Entry Page');
    next(err);
  });
}, utils.redirect('/planner'))

page('/welcome', function(ctx, next) {
  session.loginAnonymously(next);
}, utils.redirect('/planner'));

page('*', utils.render);

onLoad(page);
<commit_msg>Track as Source<commit_after>var Commuter = require('commuter');
var historyPolyfill = require('html5-history-api');
var onLoad = require('on-load');
var page = require('page');
var Plan = require('plan');
var utils = require('router-utils');
var session = require('session');

page('/', utils.redirect('/planner'));

page('/login', require('commuter-login'));
page('/forgot-password', require('forgot-password-page'));
page('/change-password/:key', require('change-password-page'));
page('/confirm-email/:key', Commuter.confirmEmail, utils.redirect('/login'));

page('/planner', session.commuterIsLoggedIn, Plan.load, require('planner-page'));
page('/planner/:link', session.loginWithLink, utils.redirect('/planner'));

page('/style-guide', require('style-guide'));

page('/t/:code', function(ctx, next) {
  session.loginAnonymously(function(err) {
    window.analytics.page(ctx.code, 'Source');
    next(err);
  });
}, utils.redirect('/planner'))

page('/welcome', function(ctx, next) {
  session.loginAnonymously(next);
}, utils.redirect('/planner'));

page('*', utils.render);

onLoad(page);
<|endoftext|>