<commit_before>var addresses = [];
var INVITER_FILTER_BLANK = INVITER_FILTER_BLANK || 'start typing a name';

// Array indexOf compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

// Array filter compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

var inviter = inviter || function() {};
inviter.prototype.onDomReady = function(callback){ // callback should be a function
    if (document.addEventListener) {
        // If the browser supports the DOMContentLoaded event,
        // assign the callback function to execute when that event fires
        document.addEventListener("DOMContentLoaded", callback, false);
    } else {
        if(document.body && document.body.lastChild){
            // If the DOM is available for access, execute the callback function
            callback();
        } else {
            // Reexecute the current function, denoted by arguments.callee,
            // after waiting a brief nanosecond so as not to lock up the browser
            return setTimeout(arguments.callee, 0);
        }
    }
};

inviter.prototype.isNullSafe = function(variable) {
    return (typeof(variable) != 'undefined' && variable != null);
};

inviter.prototype.getAllFriends = function() {
    var friends = [];
    var friendsNode = document.getElementById('inviter-friends');
    var els = friendsNode.getElementsByTagName('div');
    var elsLen = els.length;
    for(var i=0; i<elsLen; i++) {
        //console.log('el '+i);
        friends.push(els[i]);
    }
    return friends;
}

// adds or removes elements from the list of addresses
function toggleAddress(address) {
    console.log('toggle address '+address);
	//if ($.inArray(address, addresses) >= 0) {
    var addressIdx = addresses.indexOf(address);
    if (addressIdx >= 0) {
        console.log('toggle addresses 0 '+addresses);
        addresses.splice(addressIdx, 1);
        /*
		addresses = $.grep(addresses, function(val) {
            console.log('toggle address / grep val '+val);
			return val != address
		});
        */
        console.log('toggle addresses 1 '+addresses);

        var els = getByEmail(address);
        var elsLen = els.length;
        for(var i=0; i<elsLen; i++) {
            els[i].className = 'friend';
        }
        /*
		getByEmail(address).each(function() {
			$(this).removeClass('selected')
		});
        */
	} else {
		addresses.push(address);
        var els = getByEmail(address);
        var elsLen = els.length;
        for(var i=0; i<elsLen; i++) {
            els[i].className = 'friend selected';
        }
        /*
		getByEmail(address).each(function() {
			$(this).addClass('selected')
		});
        */
	}
	//$('#addresses').val(addresses.join(','))
    var addressesNode = document.getElementById('addresses');
    if (inviter.isNullSafe(addressesNode)) {
        addressesNode.value = addresses.join(',');
    }

}

function getByEmail(address) {
    var friends = inviter.getAllFriends();
    //console.log('friends = '+friends);
    // $('.friends div')
    //if (Array.isArray(friends) {
    if (inviter.isNullSafe(friends)) {
        return friends.filter(function(node) {
            //console.log('friends filter '+node.getAttribute('data-email') + '/'+address);
            //return $(this).attr('data-email') == address
            return node.getAttribute('data-email') == address;
        });
    }
    return [];
}

var typewatch = function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    }
}();

inviter.prototype.bindEvent = function(element, eventType, handler) {
    console.log('binding '+element+' - '+eventType);
    if (inviter.isNullSafe(element)) {
        if (typeof element.addEventListener != "undefined") {
            element.addEventListener(eventType, handler, false);
        //if addEventListener is not present, see if this is an IE browser
        } else if (typeof element.attachEvent != "undefined") {
            //element.attachEvent('on'+eventType, handler);
            element.attachEvent('on' + eventType, function(){
                /* use call to simulate addEventListener
                 * This will make sure the callback gets the element for "this"
                 * and will ensure the function's first argument is the event object
                 */
                 handler.call(event.srcElement,event);
            });
        }
    }
}

inviter = new inviter();

//$(document).ready(function() {
inviter.onDomReady(function() {
    /*
	$('.friends div').click(function() {
		toggleAddress($(this).attr('data-email'));
	});
    */
    var friends = inviter.getAllFriends();
    if (inviter.isNullSafe(friends)) {
        var elsLen = friends.length;
        for(var i=0; i<elsLen; i++) {
            var friend = friends[i];
            inviter.bindEvent(friend, 'click', function(e) {
                toggleAddress(this.getAttribute('data-email'));
            });
        }
    }

    var filterField = document.getElementById('clearSelection');
    inviter.bindEvent(filterField, 'focus', function() {
        //$('#filterField').focus(function() {
		if ($('#filterField').val() == INVITER_FILTER_BLANK) {
			$('#filterField').val('')
		}
	});
    inviter.bindEvent(filterField, 'focusout', function() {
	//$('#filterField').focusout(function() {
		if ($('#filterField').val() == '') {
			$('#filterField').val(INVITER_FILTER_BLANK)
		}
	});

	//$('#filterField').bindWithDelay( 'keyup', function() {
    inviter.bindEvent(document.getElementById('filterField'), 'keyup', function () {
        typewatch(function() {
            var filterVal = $('#filterField').val()
            if (filterVal == '') {
                $('.friends div').show()
            } else if (filterVal.length > 0) {
                var rgx = new RegExp(filterVal, "i");
                $('.friends div').each(function() {
                    ($(this).text().search(rgx) < 0 && $(this).attr('data-email').search(rgx) < 0) ? $(this).hide() : $(this).show();
                });
            }
        }, 500 );
    });

	$('#filterField').val(INVITER_FILTER_BLANK)
	//$('#clearSelection').click(clearSelection);
    inviter.bindEvent(document.getElementById('clearSelection'), 'click', clearSelection);
    inviter.bindEvent(document.getElementById('selectAll'), 'click', selectAll);
	//$('#selectAll').click(selectAll);
});

/*
bindWithDelay jQuery plugin
Author: Brian Grinstead
MIT license: http://www.opensource.org/licenses/mit-license.php
http://github.com/bgrins/bindWithDelay
http://briangrinstead.com/files/bindWithDelay
*/

/*
(function($) {
$.fn.bindWithDelay = function( type, data, fn, timeout, throttle ) {
	var wait = null;
	var that = this;

	if ( $.isFunction( data ) ) {
		throttle = timeout;
		timeout = fn;
		fn = data;
		data = undefined;
	}

	function cb() {
		var e = $.extend(true, { }, arguments[0]);
		var throttler = function() {
			wait = null;
			fn.apply(that, [e]);
		};

		if (!throttle) { clearTimeout(wait); }
		if (!throttle || !wait) { wait = setTimeout(throttler, timeout); }
	}

	return this.bind(type, data, cb);
}
})(jQuery);
*/

function clearSelection() {
    addresses = [];
    $('.friends div').each(function() {
        $(this).removeClass('selected');
    });
    $('#addresses').val('')
}

function selectAll() {
    addresses = [];
    $('.friends div').each(function() {
        addresses.push($(this).attr('data-email'));
        $(this).addClass('selected');
    });
    console.log('select all addresses='+addresses);
    $('#addresses').val(addresses.join(','))
}<commit_msg>removed jQuery<commit_after>var addresses = [];
var INVITER_FILTER_BLANK = INVITER_FILTER_BLANK || 'start typing a name';

// Array indexOf compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

// Array filter compatibility
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

var inviter = inviter || function() {};

inviter.prototype.onDomReady = function(callback){
    if (document.addEventListener) {
        document.addEventListener('DOMContentLoaded', callback, false);
    } else {
        if(document.body && document.body.lastChild){
            callback();
        } else {
            return setTimeout(arguments.callee, 0);
        }
    }
};

// isNullSafe
inviter.prototype.isUsable = function(variable) {
    return (typeof(variable) != 'undefined' && variable != null);
};

// show friend div. display: inline-block;
inviter.prototype.show = function(element) {
    element.style.display = 'inline-block';
}

inviter.prototype.hide = function(element) {
    element.style.display = 'none';
}

inviter.prototype.text = function(element) {
    var text = document.body.textContent ? 'textContent' : 'innerText';
    return element[text];
}

inviter.prototype.getAllFriends = function() {
    var friends = [];
    var friendsNode = document.getElementById('inviter-friends');
    if (!inviter.isUsable(friendsNode)) { return friends; }
    var els = friendsNode.getElementsByTagName('div');
    var elsLen = els.length;
    for(var i=0; i<elsLen; i++) {
        friends.push(els[i]);
    }
    return friends;
}

// adds or removes elements from the list of addresses
inviter.prototype.toggleAddress = function(address) {
    var addressIdx = addresses.indexOf(address);
    if (addressIdx >= 0) {
        addresses.splice(addressIdx, 1);
        var els = inviter.getByEmail(address);
        var elsLen = els.length;
        for(var i=0; i<elsLen; i++) {
            els[i].className = 'friend';
        }
	} else {
		addresses.push(address);
        var els = inviter.getByEmail(address);
        var elsLen = els.length;
        for(var i=0; i<elsLen; i++) {
            els[i].className = 'friend selected';
        }
	}
    var addressesNode = document.getElementById('addresses');
    if (inviter.isUsable(addressesNode)) {
        addressesNode.value = addresses.join(',');
    }

}

inviter.prototype.getByEmail = function(address) {
    var friends = inviter.getAllFriends();
    return friends.filter(function(node) {
        return node.getAttribute('data-email') == address;
    });
    return [];
}

// function used to add delay to binding search field.
var typewatch = function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    }
}();

inviter.prototype.bindEvent = function(element, eventType, handler) {
    if (inviter.isUsable(element)) {
        if (typeof element.addEventListener != "undefined") {
            element.addEventListener(eventType, handler, false);
        } else if (typeof element.attachEvent != "undefined") {
            element.attachEvent('on' + eventType, function(){
                 handler.call(event.srcElement,event);
            });
        }
    }
}

inviter.prototype.clearSelection = function() {
    addresses = [];
    var friends = inviter.getAllFriends();
    var elsLen = friends.length;
    for(var i=0; i<elsLen; i++) {
        friends[i].className = 'friend';
    }
    var addressesNode = document.getElementById('addresses');
    if (inviter.isUsable(addressesNode)) {
        addressesNode.value = '';
    }
}

inviter.prototype.selectAll = function() {
    addresses = [];
    var friends = inviter.getAllFriends();
    var elsLen = friends.length;
    for(var i=0; i<elsLen; i++) {
        var friend = friends[i];
        addresses.push(friend.getAttribute('data-email'));
        friend.className = 'friend selected';
    }
    var addressesNode = document.getElementById('addresses');
    if (inviter.isUsable(addressesNode)) {
        addressesNode.value = addresses.join(',');
    }
}

inviter = new inviter();

inviter.onDomReady(function() {
    var friends = inviter.getAllFriends();
    var filterField = document.getElementById('filterField');
    if (!inviter.isUsable(friends) || !inviter.isUsable(filterField)) { return; }
    var friendsSize = friends.length;
    for(var i=0; i<friendsSize; i++) {
        var friend = friends[i];
        inviter.bindEvent(friend, 'click', function(e) {
            inviter.toggleAddress(this.getAttribute('data-email'));
        });
    }
    inviter.bindEvent(filterField, 'focus', function() {
        if (filterField.value == INVITER_FILTER_BLANK) {
            filterField.value = '';
        }
	});
    inviter.bindEvent(filterField, 'focusout', function() {
        if (filterField.value == '') {
            filterField.value = INVITER_FILTER_BLANK;
        }
	});
    inviter.bindEvent(document.getElementById('filterField'), 'keyup', function () {
        typewatch(function() {
            var filterVal = filterField.value;
            if (filterVal == '') {
                for(var i=0; i<friendsSize; i++) {
                    inviter.show(friends[i]);
                }
            } else if (filterVal.length > 0) {
                var rgx = new RegExp(filterVal, "i");
                for(var i=0; i<friendsSize; i++) {
                    var friend = friends[i];
                    (inviter.text(friend).search(rgx) < 0 && friend.getAttribute('data-email').search(rgx) < 0) ? inviter.hide(friend) : inviter.show(friend);
                }
            }
        }, 500 );
    });
    filterField.value = INVITER_FILTER_BLANK;
    inviter.bindEvent(document.getElementById('clearSelection'), 'click', inviter.clearSelection);
    inviter.bindEvent(document.getElementById('selectAll'), 'click', inviter.selectAll);
});
<|endoftext|>


<commit_before>scc.defaults.resources = {"layout":{
                            "cResourceViews":"show"},
                          "section": "overview"
                         }

scc.modules.resources = function() {
  this.requires = ["resources"]

  /* panel */
  $(".sectionLink").click(function() {
    section = $(this).attr("id").split("_")[1];
    show_section(section)
  });
  function show_section(s) {
    if (s == "") { return; }
    // hide all sections
    $("#resources .structured > div").hide();
    // show the appropriate section
    $("#crs_" + s).show();
    // show change in the panel
    $(".sectionLink").removeClass("active");
    $("#rs_" + s).addClass("active");
    // set section to the hash tag
    var mod = {"resources": {"section": s }}
    scc.settings.set(mod);
  }
  show_section(scc.settings.get().resources.section);

  var interval = 1000;
  /*
   * TODO
   * - fix animation
   * - Drag timeline
   * - add hover effects
   */

  /**
   * Object that encapsulates a complete graph.
   *
   * This object includes all data that needs to be stored about a graph, as well as the data
   * that is visualized in the graph. This object also offers methods to set up and update a
   * graph.
   */
  var GraphClass = function()
  {
    var data = [];

    // all graphs
    var margin, width, height, x, y, xAxis, yAxis, area, graph, circle;

    // stacked graphs
    var z, stack, nest, layers;

    // number of values to show in the chart
    var numOfValues = 100;

    this.conf = Object.create({
      graphName : "",
      friendlyName : "",
      dataCallback : null,
      stacked : false,
//      size : {
//        width  : 0,
//        height : 0
//      },
    });

    this.setup = function() {

      margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = 500 - margin.left - margin.right,
      height = 300 - margin.top - margin.bottom;

      // configure x axis
      var tickFormatX = d3.time.format("%M:%S"); // show minutes:seconds
      x = d3.time.scale().range([0, width]);
      xAxis = d3.svg.axis().scale(x).orient("bottom")
                    // add ticks (axis and vertical line)
                    .tickSize(-height).tickFormat(tickFormatX).tickPadding(6).ticks(5)
                    ;

      // configure y axis
      var tickFormatY = d3.format("s"); // add SI-postfix (like 2k instead of 2000)
      y = d3.scale.linear().range([height, 0]);
      yAxis = d3.svg.axis().scale(y).orient("left")
                    // add ticks (axis and horizontal line)
                    .tickSize(-width).tickFormat(tickFormatY).tickPadding(6)
                    ;

      area = d3.svg.area()
          .x(function(d,i) { return x(d[1]); })
          .y0(height)
          .y1(function(d) { return y(d[0]); })
//          .y(function(d) { return y(d); })
          .interpolate("linear") // basis or linear
          ;

      graph = d3.select("div#" + this.conf.graphName).append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom)
                    // shifting the graph to the right to make space for the y axis
                    .append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    ;

      graph.append("path").attr("d", area(data)).attr("class", "area");

      if (this.conf.stacked) {
        z = d3.scale.category20c();

        stack = d3.layout.stack()
                  .offset("zero")
                  .values(function(d) { return d.values; })
                  .x(function(d) { return d.date; })
                  .y(function(d) { return d.value; });

        nest = d3.nest().key(function(d) { return d.key; });

//        layers = stack(nest.entries(data));
      }

      // draw x axis
      graph.append("g")
           .attr("class", "x axis")
           .attr("transform", "translate(0," + height + ")")
           .call(xAxis)
           .append("text")
           .attr("y", -10)
           .attr("x", width-6)
           .attr("dy", ".31em")
           .style("text-anchor", "end")
           .text(this.conf.friendlyName)
           .style("font-size", "14px");

      // draw y axis
      graph.append("g")
           .attr("class", "y axis")
           .call(yAxis);

      // add circle for more information
      circle = graph.append("circle").attr("r", 5).attr("display", "none");
      graph.on("mouseover", function() { circle.attr("display", "block"); })
           .on("mousemove", updateCircle)
           .on("mouseout", function() { circle.attr("display", "none"); });
    };

    function updateCircle() {
      console.log("updating");

      var xMouse = d3.mouse(this)[0];
      console.log("MouseX=" + xMouse);
      if (xMouse < 0) {
        return;
      }

//      var x = Math.min(Math.round(xMouse / (numOfValues-1))-1, numOfValues-1);
      // Normalize: NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
      var x = Math.round((((xMouse - 0) * (numOfValues-1 - 0)) / (width - 0)) + 0);
      var y;
      var SPACING = 5;

      if ( data[x] === undefined ) {
          var lower = x - (x % SPACING);
          var upper = lower + SPACING;
          var between = d3.interpolateNumber(data[lower], data[upper]);
          y = between( (x+0.001 % SPACING) / SPACING );
      } else {
          y = data[x][0];
      }

      var yMax = Math.max(d3.max(data, function(d) { return d[0]; }), 1)
//      console.log("yMax = " + yMax);
      var yVal = ((height / 1.1) / yMax) * y; // distance from top

      console.log("x=" + x);
      console.log("y=" + y);

      circle
      // De-Normalize: NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
           .attr("cx", (x*width) / (numOfValues-1))
           .attr("cy", height-yVal);
    }

    this.update = function(newData, timestamp) {

      // pre-populate data array with 0s so that the graph starts on the right side
      if (data.length < numOfValues) {
        var minus = numOfValues-1; // -1 to not start with zero in the chart
        for (; data.length<numOfValues; minus--) {
          data.push([0, timestamp - (minus*1000)]);
        }
      }

      // delete first element and add a new one at the end
      data.shift();
      var newDataLength = data.push([
          this.conf.dataCallback(newData) - Math.floor(Math.random()*(this.conf.dataCallback(newData)/15)),
          timestamp / 1000 * 1000 // round to whole seconds
          ]);

      // update domains
      x.domain(d3.extent(data/*.slice(-numOfValues)*/, function(d) { return d[1]; }));
//      x.domain(d3.extent(data, function(d) { return 20; }));
      y.domain([0, Math.max(d3.max(data, function(d) { return d[0]; })*1.1, 1) ]); // 1 is the minimum

      // redraw axis
      d3.select("#" + this.conf.graphName + " g.y.axis").call(yAxis);
      d3.select("#" + this.conf.graphName + " g.x.axis").call(xAxis).transition().ease("linear").duration(500);

      // add new data
//      graph.selectAll("path").data([data.slice((newDataLength > 20 ? -20 : -newDataLength))]).attr("d", area);
      graph.selectAll("#" + this.conf.graphName + " path").data([data]).attr("d", area);

      // update with animation
//      graph.selectAll("#" + this.conf.graphName + " path")
//        .data([data]) // set the new data
//        .attr("transform", "translate(" + x(1) + ")") // set the transform to the right by x(1) pixels (6 for the scale we've set) to hide the new value
//        .attr("d", area) // apply the new data values ... but the new value is hidden at this point off the right of the canvas
//        .transition() // start a transition to bring the new value into view
//        .ease("linear")
//        .duration(interval) // for this demo we want a continual slide so set this to the same as the setInterval amount below
//        .attr("transform", "translate(" + x(0) + ")"); // animate a slide to the left back to x(0) pixels to reveal the new value

      $(graph).mousemove();

//      try {
//        updateCircle();
//      } catch(e) {
//        // propably no mouseover
//        console.log(e);
//      }
    };

  }

  // helper function to create a new graph
  function createGraph(graphName, friendlyName, dataCallback, stacked) {
    var graph = new GraphClass();
    graph.conf.graphName = graphName;
    graph.conf.friendlyName = friendlyName;
    graph.conf.dataCallback = dataCallback;
    graph.conf.stacked = stacked;
    return graph;
  }

  // stores all graph objects
  var allGraphs = [];

  // add some graphs and set them up
  allGraphs.push(createGraph("graphMessagesSent",
                             "Messages Sent (#)",
                             function(newData) { return newData.workerStatistics["messagesSent"][0]; },
                             false));
  allGraphs.push(createGraph("graphMessagesReceived",
                             "Messages Received (#)",
                             function(newData) { return newData.workerStatistics["messagesReceived"][0]; },
                             false));
  allGraphs.push(createGraph("graphOutgoingEdges",
                             "Outgoing Edges (#)",
                             function(newData) { return newData.workerStatistics["numberOfOutgoingEdges"][0]; },
                             false));
  allGraphs.push(createGraph("graphToSignalSize",
                             "To Signal Size (#)",
                             function(newData) { return newData.workerStatistics["toSignalSize"][0]; },
                             false));
  allGraphs.push(createGraph("graphRequestMessagesReceived",
                             "Request Messages Received (#)",
                             function(newData) { return newData.workerStatistics["requestMessagesReceived"][0]; },
                             false));
  allGraphs.push(createGraph("graphSignalOperationsExecuted",
                             "signalOperationsExecuted (#)",
                             function(newData) { return newData.workerStatistics["signalOperationsExecuted"][0]; },
                             false));
  allGraphs.push(createGraph("graphRamStacked",
                             "RAM (B)",
                             function(newData) { return newData.systemStatistics[0]["jmx_mem_free"]; },
                             true));
  allGraphs.forEach(function(g) { g.setup(); });

  this.onopen = function () {
    scc.order({"provider": "resources"})
  }

  this.onerror = function(e) { }

  this.onmessage = function(j) {

    // update all graphs
    allGraphs.forEach(function(g) { g.update(j, j.timestamp); });

    scc.order({"provider": "resources"}, interval)
  }

  this.onclose = function() { }

}

<commit_msg>fix errors from the charts, comment charts which have to be updated to the new data format<commit_after>scc.defaults.resources = {"layout":{
                            "cResourceViews":"show"},
                          "section": "overview"
                         }

scc.modules.resources = function() {
  this.requires = ["resources"]

  /* panel */
  $(".sectionLink").click(function() {
    section = $(this).attr("id").split("_")[1];
    show_section(section)
  });
  function show_section(s) {
    if (s == "") { return; }
    // hide all sections
    $("#resources .structured > div").hide();
    // show the appropriate section
    $("#crs_" + s).show();
    // show change in the panel
    $(".sectionLink").removeClass("active");
    $("#rs_" + s).addClass("active");
    // set section to the hash tag
    var mod = {"resources": {"section": s }}
    scc.settings.set(mod);
  }
  show_section(scc.settings.get().resources.section);

  var interval = 1000;
  /*
   * TODO
   * - fix animation
   * - Drag timeline
   * - add hover effects
   */

  /**
   * Object that encapsulates a complete graph.
   *
   * This object includes all data that needs to be stored about a graph, as well as the data
   * that is visualized in the graph. This object also offers methods to set up and update a
   * graph.
   */
  var GraphClass = function()
  {
    var data = [];

    // all graphs
    var margin, width, height, x, y, xAxis, yAxis, area, graph, circle;

    // stacked graphs
    var z, stack, nest, layers;

    // number of values to show in the chart
    var numOfValues = 100;

    this.conf = Object.create({
      graphName : "",
      friendlyName : "",
      dataCallback : null,
      stacked : false,
//      size : {
//        width  : 0,
//        height : 0
//      },
    });

    this.setup = function() {

      margin = {top: 20, right: 20, bottom: 30, left: 50},
      width = 500 - margin.left - margin.right,
      height = 300 - margin.top - margin.bottom;

      // configure x axis
      var tickFormatX = d3.time.format("%M:%S"); // show minutes:seconds
      x = d3.time.scale().range([0, width]);
      xAxis = d3.svg.axis().scale(x).orient("bottom")
                    // add ticks (axis and vertical line)
                    .tickSize(-height).tickFormat(tickFormatX).tickPadding(6).ticks(5)
                    ;

      // configure y axis
      var tickFormatY = d3.format("s"); // add SI-postfix (like 2k instead of 2000)
      y = d3.scale.linear().range([height, 0]);
      yAxis = d3.svg.axis().scale(y).orient("left")
                    // add ticks (axis and horizontal line)
                    .tickSize(-width).tickFormat(tickFormatY).tickPadding(6)
                    ;

      area = d3.svg.area()
          .x(function(d,i) { return x(d[1]); })
          .y0(height)
          .y1(function(d) { return y(d[0]); })
//          .y(function(d) { return y(d); })
          .interpolate("linear") // basis or linear
          ;

      graph = d3.select("div#" + this.conf.graphName).append("svg")
                    .attr("width", width + margin.left + margin.right)
                    .attr("height", height + margin.top + margin.bottom)
                    // shifting the graph to the right to make space for the y axis
                    .append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")")
                    ;

      graph.append("path").attr("d", area(data)).attr("class", "area");

      if (this.conf.stacked) {
        z = d3.scale.category20c();

        stack = d3.layout.stack()
                  .offset("zero")
                  .values(function(d) { return d.values; })
                  .x(function(d) { return d.date; })
                  .y(function(d) { return d.value; });

        nest = d3.nest().key(function(d) { return d.key; });

//        layers = stack(nest.entries(data));
      }

      // draw x axis
      graph.append("g")
           .attr("class", "x axis")
           .attr("transform", "translate(0," + height + ")")
           .call(xAxis)
           .append("text")
           .attr("y", -10)
           .attr("x", width-6)
           .attr("dy", ".31em")
           .style("text-anchor", "end")
           .text(this.conf.friendlyName)
           .style("font-size", "14px");

      // draw y axis
      graph.append("g")
           .attr("class", "y axis")
           .call(yAxis);

      // add circle for more information
      circle = graph.append("circle").attr("r", 5).attr("display", "none");
      graph.on("mouseover", function() { circle.attr("display", "block"); })
           .on("mousemove", updateCircle)
           .on("mouseout", function() { circle.attr("display", "none"); });
    };

    function updateCircle() {
      console.log("updating");

      var xMouse = d3.mouse(this)[0];
      console.log("MouseX=" + xMouse);
      if (xMouse < 0) {
        return;
      }

//      var x = Math.min(Math.round(xMouse / (numOfValues-1))-1, numOfValues-1);
      // Normalize: NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
      var x = Math.round((((xMouse - 0) * (numOfValues-1 - 0)) / (width - 0)) + 0);
      var y;
      var SPACING = 5;

      if ( data[x] === undefined ) {
          var lower = x - (x % SPACING);
          var upper = lower + SPACING;
          var between = d3.interpolateNumber(data[lower], data[upper]);
          y = between( (x+0.001 % SPACING) / SPACING );
      } else {
          y = data[x][0];
      }

      var yMax = Math.max(d3.max(data, function(d) { return d[0]; }), 1)
//      console.log("yMax = " + yMax);
      var yVal = ((height / 1.1) / yMax) * y; // distance from top

      console.log("x=" + x);
      console.log("y=" + y);

      circle
      // De-Normalize: NewValue = (((OldValue - OldMin) * (NewMax - NewMin)) / (OldMax - OldMin)) + NewMin
           .attr("cx", (x*width) / (numOfValues-1))
           .attr("cy", height-yVal);
    }

    this.update = function(newData, timestamp) {

      // pre-populate data array with 0s so that the graph starts on the right side
      if (data.length < numOfValues) {
        var minus = numOfValues-1; // -1 to not start with zero in the chart
        for (; data.length<numOfValues; minus--) {
          data.push([0, timestamp - (minus*1000)]);
        }
      }

      // delete first element and add a new one at the end
      data.shift();
      var newDataLength = data.push([
          this.conf.dataCallback(newData) - Math.floor(Math.random()*(this.conf.dataCallback(newData)/15)),
          timestamp / 1000 * 1000 // round to whole seconds
          ]);

      // update domains
      x.domain(d3.extent(data/*.slice(-numOfValues)*/, function(d) { return d[1]; }));
//      x.domain(d3.extent(data, function(d) { return 20; }));
      y.domain([0, Math.max(d3.max(data, function(d) { return d[0]; })*1.1, 1) ]); // 1 is the minimum

      // redraw axis
      d3.select("#" + this.conf.graphName + " g.y.axis").call(yAxis);
      d3.select("#" + this.conf.graphName + " g.x.axis").call(xAxis).transition().ease("linear").duration(500);

      // add new data
//      graph.selectAll("path").data([data.slice((newDataLength > 20 ? -20 : -newDataLength))]).attr("d", area);
      graph.selectAll("#" + this.conf.graphName + " path").data([data]).attr("d", area);

      // update with animation
//      graph.selectAll("#" + this.conf.graphName + " path")
//        .data([data]) // set the new data
//        .attr("transform", "translate(" + x(1) + ")") // set the transform to the right by x(1) pixels (6 for the scale we've set) to hide the new value
//        .attr("d", area) // apply the new data values ... but the new value is hidden at this point off the right of the canvas
//        .transition() // start a transition to bring the new value into view
//        .ease("linear")
//        .duration(interval) // for this demo we want a continual slide so set this to the same as the setInterval amount below
//        .attr("transform", "translate(" + x(0) + ")"); // animate a slide to the left back to x(0) pixels to reveal the new value

      $(graph).mousemove();

//      try {
//        updateCircle();
//      } catch(e) {
//        // propably no mouseover
//        console.log(e);
//      }
    };

  }

  // helper function to create a new graph
  function createGraph(graphName, friendlyName, dataCallback, stacked) {
    var graph = new GraphClass();
    graph.conf.graphName = graphName;
    graph.conf.friendlyName = friendlyName;
    graph.conf.dataCallback = dataCallback;
    graph.conf.stacked = stacked;
    return graph;
  }

  // stores all graph objects
  var allGraphs = [];

  // add some graphs and set them up
//  allGraphs.push(createGraph("graphMessagesSent",
//                             "Messages Sent (#)",
//                             function(newData) { return newData.workerStatistics["messagesSent"][0]; },
//                             false));
  allGraphs.push(createGraph("graphMessagesReceived",
                             "Messages Received (#)",
                             function(newData) { return newData.workerStatistics["messagesReceived"][0]; },
                             false));
  allGraphs.push(createGraph("graphOutgoingEdges",
                             "Outgoing Edges (#)",
                             function(newData) { return newData.workerStatistics["numberOfOutgoingEdges"][0]; },
                             false));
  allGraphs.push(createGraph("graphToSignalSize",
                             "To Signal Size (#)",
                             function(newData) { return newData.workerStatistics["toSignalSize"][0]; },
                             false));
  allGraphs.push(createGraph("graphRequestMessagesReceived",
                             "Request Messages Received (#)",
                             function(newData) { return newData.workerStatistics["requestMessagesReceived"][0]; },
                             false));
  allGraphs.push(createGraph("graphSignalOperationsExecuted",
                             "signalOperationsExecuted (#)",
                             function(newData) { return newData.workerStatistics["signalOperationsExecuted"][0]; },
                             false));
//  allGraphs.push(createGraph("graphRamStacked",
//                             "RAM (B)",
//                             function(newData) { return newData.systemStatistics["jmx_mem_free"][0]; },
//                             true));
  allGraphs.forEach(function(g) { g.setup(); });

  this.onopen = function () {
    scc.order({"provider": "resources"})
  }

  this.onerror = function(e) { }

  this.onmessage = function(j) {

    // update all graphs
    allGraphs.forEach(function(g) { g.update(j, j.timestamp); });

    scc.order({"provider": "resources"}, interval)
  }

  this.onclose = function() { }

}

<|endoftext|>


<commit_before>/**
 * .reel Unit Tests
 */
(function($){

  module('Annotations', { teardown: function teardown(){
    $('.jquery-reel').trigger('teardown');
    // The teardown is automatic since 1.2
  }});

  test( 'No (or undefined) `annotations` option doesn\'t result in any sebsequent DOM changes', function(){
    expect(2);
    var
      selector= '#image',
      $reel= $(selector).reel() // `undefined` is default

    ok( !!$reel.parent().find('.jquery-reel-interface').length, 'Shared `.jquery-reel-interface` container present');
    ok( !$reel.parent().find('.jquery-reel-annotations').length, 'The `.jquery-reel-annotations` child not present anywhere in the instance');
  });

  test( 'Defining an annotations object results in rendering of respective DOM node container', function(){
    expect(1);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {}
      })

    ok( !!$('~ .jquery-reel-interface > .jquery-reel-annotations', $reel).length, 'The `.jquery-reel-annotations` child node of `jquery-reel-interface` node present');
  });

  test( 'One annotation DOM container (holder) is rendered per each `annotations` object key/value pair', function(){
    expect(2);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "my_annotation_name": {}
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    equal( !!$('div[id]', $annotations).length, 1, 'One annotation node with `id` attribute');
    ok( !!$('#my_annotation_name').length, 'Reachable by an `id` selector equal to annotation key');
  });

  asyncTest( '`holder` holds a collection of HTML attributes used for the handler\'s `div` tag', function(){
    expect(7);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "my_annotation": {
            holder: {
              text: 'Some text',
              'class': 'some_class_name',
              title: 'Some hint',
              // Any attribute would do as it would for jQuery's `.attr()`
              'any-attribute': 'any-value'
            },
          },
          "still_holder": {}
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    // Positioning of annotations happens at `frameChange`
    $reel.one('frameChange', function(){
      ok( !!$('div#my_annotation').length, 'Node present');
      //ok( $('#my_annotation').is(':visible'), 'Node visible');
      ok( $('#my_annotation').is(':contains(Some text)'), 'Node text content');
      equal( $('#my_annotation').text(), 'Some text', 'Node text content');
      ok( !!$('#my_annotation.some_class_name').length, 'Class name applied');
      equal( $('#my_annotation[title]').attr('title'), 'Some hint', '`title` attribute applied');
      equal( $('#my_annotation[any-attribute]').attr('any-attribute'), 'any-value', 'Any attribute would do');

      ok( !!$('div#still_holder').length, 'Holder is always present, even when not defined');
      start();
    });
  });

  asyncTest( '`image` holds a collection of HTML attributes used for an `img` tag inside the holder', function(){
    expect(5);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "my_annotation": {
            image: {
              src: 'some/my/image.jpg',
              width: 100,
              height: 50
            }
          }
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    // Positioning of annotations happens at `frameChange`
    $reel.one('frameChange', function(){
      ok( !!$('div#my_annotation').length, 'Holder node present');
      ok( !!$('div#my_annotation img').length, 'Wrapping an image node');
      equal( $('#my_annotation img').attr('src'), 'some/my/image.jpg', 'Image `src`');
      equiv( $('#my_annotation img').css('width'), 100, 'CSS width');
      equiv( $('#my_annotation img').css('height'), 50, 'CSS height');
      //equiv( $('#my_annotation img').attr('width'), 100, '`width`');
      //equiv( $('#my_annotation img').attr('height'), 50, '`height`');
      start();
    });
  });

  asyncTest( '`link` holds a collection of HTML attributes used for an `a` tag inside the holder', function(){
    expect(8);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "text_link": {
            link: {
              href: 'http://some/location',
              text: 'Click to navigate away'
            }
          },
          "image_link": {
            image: {
              src: 'some/my/image.jpg'
            },
            link: {
              href: 'http://some/location'
            }
          }
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    // Positioning of annotations happens at `frameChange`
    $reel.one('frameChange', function(){
      ok( !!$('div#text_link').length, 'Holder node present');
      ok( !!$('div#text_link a').length, 'Wrapping a link node');
      equal( $('#text_link a').attr('href'), 'http://some/location', 'Link `href`');
      equal( $('#text_link a').text(), 'Click to navigate away', '`title`');

      ok( !!$('div#image_link').length, 'Holder node present');
      ok( !!$('div#image_link > a > img').length, 'Wrapping a link node wrapping an image node');
      equal( $('#image_link a').attr('href'), 'http://some/location', 'Link `href`');
      equal( $('#image_link img').attr('src'), 'some/my/image.jpg', 'Image `src`');

      start();
    });
  });

  // TODO Add conditional visibility and positioning tests

})(jQuery);
<commit_msg>Test for frame-based visibility based on simple `start` and `end` annotation properties<commit_after>/**
 * .reel Unit Tests
 */
(function($){

  module('Annotations', { teardown: function teardown(){
    $('.jquery-reel').trigger('teardown');
    // The teardown is automatic since 1.2
  }});

  test( 'No (or undefined) `annotations` option doesn\'t result in any sebsequent DOM changes', function(){
    expect(2);
    var
      selector= '#image',
      $reel= $(selector).reel() // `undefined` is default

    ok( !!$reel.parent().find('.jquery-reel-interface').length, 'Shared `.jquery-reel-interface` container present');
    ok( !$reel.parent().find('.jquery-reel-annotations').length, 'The `.jquery-reel-annotations` child not present anywhere in the instance');
  });

  test( 'Defining an annotations object results in rendering of respective DOM node container', function(){
    expect(1);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {}
      })

    ok( !!$('~ .jquery-reel-interface > .jquery-reel-annotations', $reel).length, 'The `.jquery-reel-annotations` child node of `jquery-reel-interface` node present');
  });

  test( 'One annotation DOM container (holder) is rendered per each `annotations` object key/value pair', function(){
    expect(2);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "my_annotation_name": {}
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    equal( !!$('div[id]', $annotations).length, 1, 'One annotation node with `id` attribute');
    ok( !!$('#my_annotation_name').length, 'Reachable by an `id` selector equal to annotation key');
  });

  asyncTest( '`holder` holds a collection of HTML attributes used for the handler\'s `div` tag', function(){
    expect(7);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "my_annotation": {
            holder: {
              text: 'Some text',
              'class': 'some_class_name',
              title: 'Some hint',
              // Any attribute would do as it would for jQuery's `.attr()`
              'any-attribute': 'any-value'
            },
          },
          "still_holder": {}
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    // Positioning of annotations happens at `frameChange`
    $reel.one('frameChange', function(){
      ok( !!$('div#my_annotation').length, 'Node present');
      //ok( $('#my_annotation').is(':visible'), 'Node visible');
      ok( $('#my_annotation').is(':contains(Some text)'), 'Node text content');
      equal( $('#my_annotation').text(), 'Some text', 'Node text content');
      ok( !!$('#my_annotation.some_class_name').length, 'Class name applied');
      equal( $('#my_annotation[title]').attr('title'), 'Some hint', '`title` attribute applied');
      equal( $('#my_annotation[any-attribute]').attr('any-attribute'), 'any-value', 'Any attribute would do');

      ok( !!$('div#still_holder').length, 'Holder is always present, even when not defined');
      start();
    });
  });

  asyncTest( '`image` holds a collection of HTML attributes used for an `img` tag inside the holder', function(){
    expect(5);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "my_annotation": {
            image: {
              src: 'some/my/image.jpg',
              width: 100,
              height: 50
            }
          }
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    // Positioning of annotations happens at `frameChange`
    $reel.one('frameChange', function(){
      ok( !!$('div#my_annotation').length, 'Holder node present');
      ok( !!$('div#my_annotation img').length, 'Wrapping an image node');
      equal( $('#my_annotation img').attr('src'), 'some/my/image.jpg', 'Image `src`');
      equiv( $('#my_annotation img').css('width'), 100, 'CSS width');
      equiv( $('#my_annotation img').css('height'), 50, 'CSS height');
      //equiv( $('#my_annotation img').attr('width'), 100, '`width`');
      //equiv( $('#my_annotation img').attr('height'), 50, '`height`');
      start();
    });
  });

  asyncTest( '`link` holds a collection of HTML attributes used for an `a` tag inside the holder', function(){
    expect(8);
    var
      selector= '#image',
      $reel= $(selector).reel({
        annotations: {
          "text_link": {
            link: {
              href: 'http://some/location',
              text: 'Click to navigate away'
            }
          },
          "image_link": {
            image: {
              src: 'some/my/image.jpg'
            },
            link: {
              href: 'http://some/location'
            }
          }
        }
      }),
      $annotations= $('~ * > .jquery-reel-annotations', $reel)

    // Positioning of annotations happens at `frameChange`
    $reel.one('frameChange', function(){
      ok( !!$('div#text_link').length, 'Holder node present');
      ok( !!$('div#text_link a').length, 'Wrapping a link node');
      equal( $('#text_link a').attr('href'), 'http://some/location', 'Link `href`');
      equal( $('#text_link a').text(), 'Click to navigate away', '`title`');

      ok( !!$('div#image_link').length, 'Holder node present');
      ok( !!$('div#image_link > a > img').length, 'Wrapping a link node wrapping an image node');
      equal( $('#image_link a').attr('href'), 'http://some/location', 'Link `href`');
      equal( $('#image_link img').attr('src'), 'some/my/image.jpg', 'Image `src`');

      start();
    });
  });

  asyncTest( 'Frame-based visibility annotation control properties `start` and `end`', function(){
    expect(36);
    var
      selector= '#image',
      frames= 36, // Default value
      should_be= '----+++++++++-----------------------'.split(''),
      $reel= $(selector).reel({
        annotations: {
          "my_annotation": {
            x: 1, y: 1,
            start: 5,
            end: 13
          }
        },
        // And this will autoscroll thorugh all frames once
        entry: 1,
        opening: 1
      }),
      checked= [],
      $annotations= $('~ * > .jquery-reel-annotations', $reel),
      $annotation= $('#my_annotation')

    // Positioning of annotations happens at `frameChange`
    $reel.bind('frameChange', function(){
      var
        frame= $reel.data('frame'),
        should= should_be[frame - 1] == '+'

      equal( $annotation.is(':visible') , should, (should ? 'On' : 'Off')+' @ frame '+frame );

      checked.push(frame);
      if (checked.length == frames){
        $reel.unbind('frameChange');
        start();
      }
    });
  });

  // TODO Add conditional visibility and positioning tests

})(jQuery);
<|endoftext|>


<commit_before>
var app = require('../fixtures/bootstrap'),
    vows = require('vows'),
    assert = require('assert'),
    util = require('util');

vows.describe('lib/application.js').addBatch({

  'Application Integrity Checks': {

    'Set domain': function() {
      assert.equal(app.domain, 'localhost');
    },

    'Set application path': function() {
      assert.equal(app.path, framework.constructor.path + '/test/fixtures/test-skeleton');
    },

    'Detected library overrides': function() {
      assert.isFunction(app.lib.controller);
    },

    'Initialized models': function() {
      assert.isTrue(app.models.users instanceof framework.lib.model);
    },

    'Initialized helpers': function() {
      assert.isTrue(app.helpers.main instanceof framework.lib.helper);
    },

    'Initialized controllers': function() {
      assert.isTrue(app.controllers.main instanceof framework.lib.controller);
    },

    'Initialized framework engines': function() {
      assert.isTrue(app.engines.eco instanceof framework.lib.engine);
    },

    'Initialized application engines': function() {
      assert.isTrue(app.engines.myengine instanceof framework.lib.engine);
    }

  }

}).addBatch({

  'Application::registerEnable': {

    topic: function() {
      app.registerEnable('myFeature', function(config) {
        this.__ValidContext = true;
        this.__PassedConfig = config;
      });
      return app;
    },

    'Properly registers feature': function(topic) {
      assert.isFunction(app.__enableFeatures.myFeature);
    }

  }

}).addBatch({

  'Application::enable': {

    topic: function() {
      app.enable('myFeature', {testVar: 99});
      return app;
    },

    'Registers feature in app.supports': function() {
      assert.isTrue(app.supports.myFeature);
    },

    'Calls registered function correctly within app context': function() {
      assert.isTrue(app.__ValidContext);
    },

    'Passes config to registered function': function() {
      assert.equal(app.__PassedConfig.testVar, 99);
    }

  }

}).addBatch({

  'Application::use': {

    'Loads application addons': function() {
      app.use('application-addon', {testVal: 99});
      assert.isTrue(app.__LoadedApplicationAddon);
    },

    'Provides correct arguments to app addons': function() {
      assert.equal(app.__ApplicationAddonConfig.testVal, 99);
    },

    'Loads framework addons': function() {
      app.use('framework-addon', {testVal: 99});
      assert.isTrue(app.__LoadedFrameworkAddon);
    },

    'Provides correct arguments to framework addons': function() {
      assert.equal(app.__FrameworkAddonConfig.testVal, 99);
    },

    'Throws an error if addon not found': function() {
      try { app.use('unknown-addon'); }
      catch(e) { assert.isTrue(e instanceof Error); }
    }

  }

}).addBatch({

  'Application::url': {

    'Returns proper url when no args provided': function() {
      assert.equal(app.url(), util.format('http://%s:%s/', app.domain, framework.config.server.listenPort));
    },

    'Returns proper url when run with path argument': function() {
      var q = '/item?id=25';
      assert.equal(app.url(q), util.format('http://%s:%s%s', app.domain, framework.config.server.listenPort, q));
    }

  }

}).addBatch({

  'Application::relPath': {

    'Returns a relative application path': function() {
      var fullPath = app.path + '/views/main';
      assert.equal(app.relPath(fullPath), 'views/main');
    },

    'Works when passing offset argument': function() {
      var fullPath = app.path + '/views/main/main-index.html';
      assert.equal(app.relPath(fullPath, 'views/main'), 'main-index.html');
    },

    'Handles offset argument w/slashes correctly': function() {
      var fullPath = app.path + '/views/main/main-index.html',
          expected = 'main-index.html';
      var r1 = app.relPath(fullPath, '/views/main') == expected,
          r2 = app.relPath(fullPath, '/views/main/') == expected,
          r3 = app.relPath(fullPath, 'views/main/') == expected;
      assert.isTrue(r1 && r2 && r3);
    }

  }

}).export(module);

<commit_msg>Update<commit_after>
var app = require('../fixtures/bootstrap'),
    vows = require('vows'),
    assert = require('assert'),
    util = require('util');

app.logging = false;

vows.describe('lib/application.js').addBatch({

  'Application Integrity Checks': {

    'Set domain': function() {
      assert.equal(app.domain, 'localhost');
    },

    'Set application path': function() {
      assert.equal(app.path, framework.constructor.path + '/test/fixtures/test-skeleton');
    },

    'Detected library overrides': function() {
      assert.isFunction(app.lib.controller);
    },

    'Initialized models': function() {
      assert.isTrue(app.models.users instanceof framework.lib.model);
    },

    'Initialized helpers': function() {
      assert.isTrue(app.helpers.main instanceof framework.lib.helper);
    },

    'Initialized controllers': function() {
      assert.isTrue(app.controllers.main instanceof framework.lib.controller);
    },

    'Initialized framework engines': function() {
      assert.isTrue(app.engines.eco instanceof framework.lib.engine);
    },

    'Initialized application engines': function() {
      assert.isTrue(app.engines.myengine instanceof framework.lib.engine);
    }

  }

}).addBatch({

  'Application::registerEnable': {

    topic: function() {
      app.registerEnable('myFeature', function(config) {
        this.__ValidContext = true;
        this.__PassedConfig = config;
      });
      return app;
    },

    'Properly registers feature': function(topic) {
      assert.isFunction(app.__enableFeatures.myFeature);
    }

  }

}).addBatch({

  'Application::enable': {

    topic: function() {
      app.enable('myFeature', {testVar: 99});
      return app;
    },

    'Registers feature in app.supports': function() {
      assert.isTrue(app.supports.myFeature);
    },

    'Calls registered function correctly within app context': function() {
      assert.isTrue(app.__ValidContext);
    },

    'Passes config to registered function': function() {
      assert.equal(app.__PassedConfig.testVar, 99);
    }

  }

}).addBatch({

  'Application::use': {

    'Loads application addons': function() {
      app.use('application-addon', {testVal: 99});
      assert.isTrue(app.__LoadedApplicationAddon);
    },

    'Provides correct arguments to app addons': function() {
      assert.equal(app.__ApplicationAddonConfig.testVal, 99);
    },

    'Loads framework addons': function() {
      app.use('framework-addon', {testVal: 99});
      assert.isTrue(app.__LoadedFrameworkAddon);
    },

    'Provides correct arguments to framework addons': function() {
      assert.equal(app.__FrameworkAddonConfig.testVal, 99);
    },

    'Throws an error if addon not found': function() {
      try { app.use('unknown-addon'); }
      catch(e) { assert.isTrue(e instanceof Error); }
    }

  }

}).addBatch({

  'Application::url': {

    'Returns proper url when no args provided': function() {
      assert.equal(app.url(), util.format('http://%s:%s/', app.domain, framework.config.server.listenPort));
    },

    'Returns proper url when run with path argument': function() {
      var q = '/item?id=25';
      assert.equal(app.url(q), util.format('http://%s:%s%s', app.domain, framework.config.server.listenPort, q));
    }

  }

}).addBatch({

  'Application::relPath': {

    'Returns a relative application path': function() {
      var fullPath = app.path + '/views/main';
      assert.equal(app.relPath(fullPath), 'views/main');
    },

    'Works when passing offset argument': function() {
      var fullPath = app.path + '/views/main/main-index.html';
      assert.equal(app.relPath(fullPath, 'views/main'), 'main-index.html');
    },

    'Handles offset argument w/slashes correctly': function() {
      var fullPath = app.path + '/views/main/main-index.html',
          expected = 'main-index.html';
      var r1 = app.relPath(fullPath, '/views/main') == expected,
          r2 = app.relPath(fullPath, '/views/main/') == expected,
          r3 = app.relPath(fullPath, 'views/main/') == expected;
      assert.isTrue(r1 && r2 && r3);
    }

  }

}).addBatch({

  'Application::fullPath': {

    'Returns the full path of an application resource': function() {
      assert.equal(app.fullPath('views/main'), app.path + '/views/main');
    }

  }

}).addBatch({

  'Application::driver': {

    'Returns a driver object': function() {
      var driver = app.driver('mysql', {});
      assert.isTrue(driver instanceof framework.lib.driver);
    }

  }

}).addBatch({

  'Application::storage': {

    'Returns a storage object': function() {
      var storage = app.storage('redis', {});
      assert.isTrue(storage instanceof framework.lib.storage);
    }

  }

}).addBatch({

  'Application::getResource': {

    topic: function() {
      app.context = {
        alpha: {name: 'alpha'},
        beta: {
          gamma: {name: 'gamma'}
        }
      }
      return app;
    },

    'Gets {context}/{resource}': function() {
      var drv = app.getResource('context/alpha');
      assert.equal(drv.name, 'alpha');
    },

    'Gets {context}/{group}:{resource}': function() {
      var drv = app.getResource('context/beta:gamma');
      assert.equal(drv.name, 'gamma');
    }

  }

}).export(module);

<|endoftext|>


<commit_before>define(['intern/dojo/text!lib/common/resolver/paths.json', 'test/mocks/lazo'], function (paths, lazo) {

    'use strict';

    paths = JSON.parse(paths);

    try {
        window.LAZO = lazo;
    } catch (err) {
        global.LAZO = lazo;
    }
    LAZO.app.isServer = false;
    LAZO.app.isClient = true;

    var needle = '/{env}/';
    var serverPaths = {};
    var env = LAZO.app.isServer ? 'server' : 'client';
    var replace = '/' + env + '/';

    for (var k in paths.common) { // update env specific implementation paths
        paths.common[k] = paths.common[k].replace(needle, replace);
    }
    for (k in paths[env]) { // merge env specific paths
        paths.common[k] = paths[env][k];
    }

    return {

        proxyPort: 9000,

        proxyUrl: 'http://localhost:9000/',

        capabilities: {
            'selenium-version': '2.40.0'
        },

        environments: [{ browserName: 'chrome', version: '34', platform: [ 'OS X 10.9', 'Windows 7', 'Linux' ] }],

        tunnel: 'SauceLabsTunnel',

        excludeInstrumentation: /^(?:test|node_modules|lib\/vendor)\//,

        useLoader: {
            'host-browser': '../../node_modules/requirejs/require.js'
        },

        loader: {
            paths: paths.common,
            map: {
                intern: {
                    dojo: 'intern/node_modules/dojo',
                    chai: 'intern/node_modules/chai/chai'
                },
                '*': {
                    // testing libs
                    sinon: '../../node_modules/sinon/lib/sinon.js',
                    'sinon-chai': '../../node_modules/sinon-chai/lib/sinon-chai.js'
                }
            }
        }

    };

});<commit_msg>added more browsers<commit_after>define(['intern/dojo/text!lib/common/resolver/paths.json', 'test/mocks/lazo'], function (paths, lazo) {

    'use strict';

    paths = JSON.parse(paths);

    try {
        window.LAZO = lazo;
    } catch (err) {
        global.LAZO = lazo;
    }
    LAZO.app.isServer = false;
    LAZO.app.isClient = true;

    var needle = '/{env}/';
    var serverPaths = {};
    var env = LAZO.app.isServer ? 'server' : 'client';
    var replace = '/' + env + '/';

    for (var k in paths.common) { // update env specific implementation paths
        paths.common[k] = paths.common[k].replace(needle, replace);
    }
    for (k in paths[env]) { // merge env specific paths
        paths.common[k] = paths[env][k];
    }

    return {

        proxyPort: 9000,

        proxyUrl: 'http://localhost:9000/',

        capabilities: {
            'selenium-version': '2.40.0'
        },

        environments: [
            { browserName: 'internet explorer', version: '11', platform: 'Windows 8.1' },
            { browserName: 'internet explorer', version: '10', platform: 'Windows 8' },
            { browserName: 'internet explorer', version: '9', platform: 'Windows 7' },
            { browserName: 'firefox', version: '28', platform: [ 'OS X 10.9', 'Windows 7', 'Linux' ] },
            { browserName: 'chrome', version: '34', platform: [ 'OS X 10.9', 'Windows 7', 'Linux' ] },
            { browserName: 'safari', version: '6', platform: 'OS X 10.8' },
            { browserName: 'safari', version: '7', platform: 'OS X 10.9' }
        ],

        tunnel: 'SauceLabsTunnel',

        excludeInstrumentation: /^(?:test|node_modules|lib\/vendor)\//,

        useLoader: {
            'host-browser': '../../node_modules/requirejs/require.js'
        },

        loader: {
            paths: paths.common,
            map: {
                intern: {
                    dojo: 'intern/node_modules/dojo',
                    chai: 'intern/node_modules/chai/chai'
                },
                '*': {
                    // testing libs
                    sinon: '../../node_modules/sinon/lib/sinon.js',
                    'sinon-chai': '../../node_modules/sinon-chai/lib/sinon-chai.js'
                }
            }
        }

    };

});<|endoftext|>


<commit_before>var menuOpenCounter = 0;
var menuCloseCounter = 0;
var itemSelectedCounter = 0;
var menuRuntime = null;

function testQUnit(name, itemClickEvent, triggerEvent) {
  QUnit.module(name);
  // before each test
  function createContextMenu(items) {
    var $fixture = $('#qunit-fixture');

    // ensure `#qunit-fixture` exists when testing with karma runner
    if ($fixture.length === 0) {
      $('
').appendTo("body");
      $fixture = $('#qunit-fixture');
    }

    $fixture.append("
right click me!
");

    if(!items){
      items = {
        copy: {name: 'Copy', icon: 'copy'},
        paste: {name: 'Paste', icon: 'paste'}
      };
    }

    $.contextMenu({
      selector: '.context-menu',
      events: {
        show: function(opt) {
          menuRuntime = opt;
          menuOpenCounter = menuOpenCounter + 1;
        },
        hide: function() {
          menuCloseCounter = menuCloseCounter + 1;
        }
      },
      callback: function(key, options) {
        itemSelectedCounter = itemSelectedCounter + 1;
      },
      items: items,
      itemClickEvent: itemClickEvent
    });
  }

  // after each test
  function destroyContextMenuAndCleanup() {
    $.contextMenu('destroy');

    // clean up `#qunit-fixture` when testing in karma runner
    var $fixture = $('#qunit-fixture');
    if ($fixture.length) {
      $fixture.html('');
    }

    // reset vars
    menuOpenCounter = 0;
    menuCloseCounter = 0;
    itemSelectedCounter = 0;
    menuRuntime = null;
  }

  QUnit.test('$.contextMenu object exists', function(assert) {
    assert.ok($.contextMenu, '$.contextMenu plugin is loaded');
    assert.notEqual($.contextMenu, undefined, '$.contextMenu is not undefined');
  });

  QUnit.test('open contextMenu', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu();
    assert.equal(menuOpenCounter, 1, 'contextMenu was opened once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('open contextMenu at 0,0', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu({x: 0, y: 0});
    assert.equal(menuOpenCounter, 1, 'contextMenu was opened once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('close contextMenu', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu();
    $(".context-menu").contextMenu('hide');
    assert.equal(menuCloseCounter, 1, 'contextMenu was closed once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('navigate contextMenu items', function(assert) {
    createContextMenu();
    var itemWasFocused = 0;
    var itemWasBlurred = 0;

    // listen to focus and blur events
    $(document.body)
      .on("contextmenu:focus", ".context-menu-item", function(e) {
        itemWasFocused = itemWasFocused + 1;
      })
      .on("contextmenu:blur", ".context-menu-item", function(e) {
        itemWasBlurred = itemWasBlurred + 1;
      });

    $(".context-menu").contextMenu();
    menuRuntime.$menu.trigger('nextcommand'); // triggers contextmenu:focus
    assert.equal(itemWasFocused, 1, 'first menu item was focused once');
    itemWasFocused = 0;

    menuRuntime.$menu.trigger('nextcommand'); // triggers contextmenu:blur & contextmenu:focus
    assert.equal(itemWasFocused, 1, 'first menu item was blurred');
    assert.equal(itemWasBlurred, 1, 'second menu item was focused');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('activate contextMenu item', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu();
    menuRuntime.$menu.trigger('nextcommand');
    menuRuntime.$selected.trigger(triggerEvent);

    assert.equal(itemSelectedCounter, 1, 'selected menu item was clicked once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('do not open context menu with no visible items', function(assert) {
    createContextMenu({
      copy: {name: 'Copy', icon: 'copy', visible: function(){return false;}},
      paste: {name: 'Paste', icon: 'paste', visible: function(){return false;}}
    });
    $(".context-menu").contextMenu();

    assert.equal(menuOpenCounter, 0, 'selected menu wat not opened');
    destroyContextMenuAndCleanup();
  });
};

testQUnit('contextMenu events', '', 'mouseup')
testQUnit('contextMenu events - click handler', 'click', 'click')<commit_msg>Test to demonstrate bug in issue #413<commit_after>var menuOpenCounter = 0;
var menuCloseCounter = 0;
var itemSelectedCounter = 0;
var menuRuntime = null;

function testQUnit(name, itemClickEvent, triggerEvent) {
  QUnit.module(name);
  // before each test
  function createContextMenu(items) {
    var $fixture = $('#qunit-fixture');

    // ensure `#qunit-fixture` exists when testing with karma runner
    if ($fixture.length === 0) {
      $('
').appendTo("body");
      $fixture = $('#qunit-fixture');
    }

    $fixture.append("
right click me!
");

    if(!items){
      items = {
        copy: {name: 'Copy', icon: 'copy'},
        paste: {name: 'Paste', icon: 'paste'}
      };
    }

    $.contextMenu({
      selector: '.context-menu',
      events: {
        show: function(opt) {
          menuRuntime = opt;
          menuOpenCounter = menuOpenCounter + 1;
        },
        hide: function() {
          menuCloseCounter = menuCloseCounter + 1;
        }
      },
      callback: function(key, options) {
        itemSelectedCounter = itemSelectedCounter + 1;
      },
      items: items,
      itemClickEvent: itemClickEvent
    });
  }

  // after each test
  function destroyContextMenuAndCleanup() {
    $.contextMenu('destroy');

    // clean up `#qunit-fixture` when testing in karma runner
    var $fixture = $('#qunit-fixture');
    if ($fixture.length) {
      $fixture.html('');
    }

    // reset vars
    menuOpenCounter = 0;
    menuCloseCounter = 0;
    itemSelectedCounter = 0;
    menuRuntime = null;
  }

  QUnit.test('$.contextMenu object exists', function(assert) {
    assert.ok($.contextMenu, '$.contextMenu plugin is loaded');
    assert.notEqual($.contextMenu, undefined, '$.contextMenu is not undefined');
  });

  QUnit.test('open contextMenu', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu();
    assert.equal(menuOpenCounter, 1, 'contextMenu was opened once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('open contextMenu at 0,0', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu({x: 0, y: 0});
    assert.equal(menuOpenCounter, 1, 'contextMenu was opened once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('close contextMenu', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu();
    $(".context-menu").contextMenu('hide');
    assert.equal(menuCloseCounter, 1, 'contextMenu was closed once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('navigate contextMenu items', function(assert) {
    createContextMenu();
    var itemWasFocused = 0;
    var itemWasBlurred = 0;

    // listen to focus and blur events
    $(document.body)
      .on("contextmenu:focus", ".context-menu-item", function(e) {
        itemWasFocused = itemWasFocused + 1;
      })
      .on("contextmenu:blur", ".context-menu-item", function(e) {
        itemWasBlurred = itemWasBlurred + 1;
      });

    $(".context-menu").contextMenu();
    menuRuntime.$menu.trigger('nextcommand'); // triggers contextmenu:focus
    assert.equal(itemWasFocused, 1, 'first menu item was focused once');
    itemWasFocused = 0;

    menuRuntime.$menu.trigger('nextcommand'); // triggers contextmenu:blur & contextmenu:focus
    assert.equal(itemWasFocused, 1, 'first menu item was blurred');
    assert.equal(itemWasBlurred, 1, 'second menu item was focused');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('activate contextMenu item', function(assert) {
    createContextMenu();
    $(".context-menu").contextMenu();
    menuRuntime.$menu.trigger('nextcommand');
    menuRuntime.$selected.trigger(triggerEvent);

    assert.equal(itemSelectedCounter, 1, 'selected menu item was clicked once');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('do not open context menu with no visible items', function(assert) {
    createContextMenu({
      copy: {name: 'Copy', icon: 'copy', visible: function(){return false;}},
      paste: {name: 'Paste', icon: 'paste', visible: function(){return false;}}
    });
    $(".context-menu").contextMenu();

    assert.equal(menuOpenCounter, 0, 'selected menu wat not opened');
    destroyContextMenuAndCleanup();
  });

  QUnit.test('items in seconds submenu to not override callbacks', function (assert) {
    var firstCallback = false, secondCallback = false;
    createContextMenu({
      firstsubmenu: {
        name: 'Copy',
        icon: 'copy',
        items: {
          firstitem : {
            name : "firstitem",
            icon : "copy",
            callback : function(){
              firstCallback = true;
            }
          }
        }
      },
      secondsubmenu: {
        name: 'Copy',
        icon: 'copy',
        items: {
          firstitem : {
            name : "firstitem",
            icon : "copy",
            callback : function(){
              secondCallback = true;
            }
          }
        }
      }
    });
    $('.context-menu-submenu .context-menu-item').first().trigger(triggerEvent);
    $('.context-menu-submenu .context-menu-item').last().trigger(triggerEvent);

    assert.equal(firstCallback, 1)
    assert.equal(secondCallback, 1)
  })
};

testQUnit('contextMenu events', '', 'mouseup')
testQUnit('contextMenu events - click handler', 'click', 'click')<|endoftext|>


<commit_before>module("Stomp Transaction");

test("Send a message in a transaction and abort", function() {

  var txid = "txid_" + Math.random();
  var body = Math.random();

  var client = Stomp.client(TEST.url);

  client.debug = TEST.debug;
  client.connect(TEST.login, TEST.password,
    function() {
      client.subscribe(TEST.destination, function(message)
      {
        start();
        // we should receive the 2nd message outside the transaction
        equals(message.body, "outside");
        client.disconnect();
      });

      client.begin(txid);
      client.send(TEST.destination, {transaction: txid}, body);
      client.abort(txid);
      client.send(TEST.destination, {}, "outside");
    });
    stop(TEST.timeout);
});

test("Send a message in a transaction and commit", function() {

  var txid = "txid_" + Math.random();
  var body = Math.random();

  var client = Stomp.client(TEST.url);

  client.debug = TEST.debug;
  client.connect(TEST.login, TEST.password,
    function() {
      client.subscribe(TEST.destination, function(message)
      {
        start();
        equals(message.body, body);
        client.disconnect();
      });
      client.begin(txid);
      client.send(TEST.destination, {transaction: txid}, body);
      client.commit(txid);
    });
    stop(TEST.timeout);
});
<commit_msg>tests<commit_after>module("Stomp Transaction");

test("Send a message in a transaction and abort", function() {

  var txid = "txid_" + Math.random();
  var body = Math.random();
  var body2 = Math.random();

  var client = Stomp.client(TEST.url);

  client.debug = TEST.debug;
  client.connect(TEST.login, TEST.password,
    function() {
      client.subscribe(TEST.destination, function(message)
      {
        start();
        // we should receive the 2nd message outside the transaction
        equals(message.body, body2);
        client.disconnect();
      });

      client.begin(txid);
      client.send(TEST.destination, {transaction: txid}, body);
      client.abort(txid);
      client.send(TEST.destination, {}, body2);
    });
    stop(TEST.timeout);
});

test("Send a message in a transaction and commit", function() {

  var txid = "txid_" + Math.random();
  var body = Math.random();

  var client = Stomp.client(TEST.url);

  client.debug = TEST.debug;
  client.connect(TEST.login, TEST.password,
    function() {
      client.subscribe(TEST.destination, function(message)
      {
        start();
        equals(message.body, body);
        client.disconnect();
      });
      client.begin(txid);
      client.send(TEST.destination, {transaction: txid}, body);
      client.commit(txid);
    });
    stop(TEST.timeout);
});
<|endoftext|>


<commit_before>/*
Notes:
- phantomjs and caspar via homebrew
- npm install phantomcss
- bower install phantomcss

[note i installed these locally via npm. @filtercake]
*/

/*
	Require and initialise PhantomCSS module
	Paths are relative to CasperJs directory
*/
var phantomcss = require('./../../phantomcss/phantomcss.js');

phantomcss.init({
	screenshotRoot: './test/visual/screenshots',
	failedComparisonsRoot: './test/visual/failures',
	/*
	casper: specific_instance_of_casper,
	*/
	// libraryRoot: './../../phantomcss'
	libraryRoot: './node_modules/phantomcss'
	/*
	fileNameGetter: function overide_file_naming(){},
	onPass: function passCallback(){},
	onFail: function failCallback(){},
	onTimeout: function timeoutCallback(){},
	onComplete: function completeCallback(){},
	hideElements: '#thing.selector',
	addLabelToFailedImage: true,
	outputSettings: {
		errorColor: {
			red: 255,
			green: 255,
			blue: 0
		},
		errorType: 'movement',
		transparency: 0.3
	}
	*/
});

/*
	The test scenario
*/
// casper.start( './demo/coffeemachine.html' );
casper.start( 'http://localhost:9000/#notes' );

casper.viewport(1024, 768);

casper.then(function(){
	phantomcss.screenshot('#header-title', '001-header-title');
});

// casper.then(function(){
// 	phantomcss.screenshot('#coffee-machine-button', '001.1 coffee machine button, button only');
// });

// casper.then(function(){
// 	casper.click('#coffee-machine-button');

// 	// wait for modal to fade-in
// 	casper.waitForSelector('#myModal:not([style*="display: none"])',
// 		function success(){
// 			phantomcss.screenshot('#myModal', '002 coffee machine dialog');
// 		},
// 		function timeout(){
// 			casper.test.fail('Should see coffee machine');
// 		}
// 	);
// });

// casper.then(function(){
// 	casper.click('#cappuccino-button');
// 	phantomcss.screenshot('#myModal', '003 cappuccino success');
// });

// casper.then(function(){
// 	casper.click('#close');

// 	// wait for modal to fade-out
// 	casper.waitForSelector('#myModal[style*="display: none"]',
// 		function success(){
// 			phantomcss.screenshot('#coffee-machine-wrapper', '004 coffee machine close success');
// 		},
// 		function timeout(){
// 			casper.test.fail('Should be able to walk away from the coffee machine');
// 		}
// 	);
// });

casper.then( function now_check_the_screenshots(){
	// compare screenshots
	phantomcss.compareAll();
});

casper.then( function end_it(){
	casper.test.done();
});

/*
Casper runs tests
*/
casper.run(function(){
	console.log('\nTHE END.');
	phantom.exit(phantomcss.getExitStatus());
});

<commit_msg>add visual test for welcome page. #1<commit_after>/*
Notes:
- phantomjs and caspar via homebrew
- npm install phantomcss
- bower install phantomcss

[note i installed these locally via npm. @filtercake]
*/

/*
	Require and initialise PhantomCSS module
	Paths are relative to CasperJs directory
*/
var phantomcss = require('./../../phantomcss/phantomcss.js');

phantomcss.init({
	screenshotRoot: './test/visual/screenshots',
	failedComparisonsRoot: './test/visual/failures',
	/*
	casper: specific_instance_of_casper,
	*/
	// libraryRoot: './../../phantomcss'
	libraryRoot: './node_modules/phantomcss'
	/*
	fileNameGetter: function overide_file_naming(){},
	onPass: function passCallback(){},
	onFail: function failCallback(){},
	onTimeout: function timeoutCallback(){},
	onComplete: function completeCallback(){},
	hideElements: '#thing.selector',
	addLabelToFailedImage: true,
	outputSettings: {
		errorColor: {
			red: 255,
			green: 255,
			blue: 0
		},
		errorType: 'movement',
		transparency: 0.3
	}
	*/
});

/*
	The test scenario
*/
// casper.start( './demo/coffeemachine.html' );
casper.start( 'http://localhost:9000/#notes' );

casper.viewport(1024, 768);

casper.then(function(){
	phantomcss.screenshot('#header-title', '001-header-title');
});

casper.thenOpen('http://localhost:9000/welcome.html', function() {
    phantomcss.screenshot('.welcome-body', '000-welcome-page');
});

// casper.then(function(){
// 	phantomcss.screenshot('#coffee-machine-button', '001.1 coffee machine button, button only');
// });

// casper.then(function(){
// 	casper.click('#coffee-machine-button');

// 	// wait for modal to fade-in
// 	casper.waitForSelector('#myModal:not([style*="display: none"])',
// 		function success(){
// 			phantomcss.screenshot('#myModal', '002 coffee machine dialog');
// 		},
// 		function timeout(){
// 			casper.test.fail('Should see coffee machine');
// 		}
// 	);
// });

// casper.then(function(){
// 	casper.click('#cappuccino-button');
// 	phantomcss.screenshot('#myModal', '003 cappuccino success');
// });

// casper.then(function(){
// 	casper.click('#close');

// 	// wait for modal to fade-out
// 	casper.waitForSelector('#myModal[style*="display: none"]',
// 		function success(){
// 			phantomcss.screenshot('#coffee-machine-wrapper', '004 coffee machine close success');
// 		},
// 		function timeout(){
// 			casper.test.fail('Should be able to walk away from the coffee machine');
// 		}
// 	);
// });

casper.then( function now_check_the_screenshots(){
	// compare screenshots
	phantomcss.compareAll();
});

casper.then( function end_it(){
	casper.test.done();
});

/*
Casper runs tests
*/
casper.run(function(){
	console.log('\nTHE END.');
	phantom.exit(phantomcss.getExitStatus());
});

<|endoftext|>


<commit_before>/**
 * @name mainApp
 * @requieres
 * @type {angular.Module}
 * @description Main module of the application
 */
var mainApp = angular.module('mainApp',[
    'ngRoute',
    'mainAppCtrls',
    'mgcrea.ngStrap',
    'ui.router',
    'angular-jwt',
    'restSvcs',
    'angular-storage',
    'pascalprecht.translate',
    'textAngular'
]);
/**
 * @name mainAppCtrls
 * @type {angular.Module}
 * @description Module containg all controller of the application
 */
var mainAppCtrls = angular.module('mainAppCtrls',["pascalprecht.translate"]);

mainApp.config(['$urlRouterProvider','$stateProvider',
    function($urlRouterProvider,$stateProvider)
    {
        var prefix = "resources/views/";

        $stateProvider
            .state('workshops',{
                url: '/workshops',
                controller: 'WorkshopListCtrl',
                templateUrl: prefix.concat('workshopList.html')
            })
            .state('workshopsdetails',{
                url: '/workshops/details/:id',
                controller: 'WorkshopDetailsCtrl',
                templateUrl: prefix.concat('workshopDetails.html')
            })
            .state('login',{
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: prefix.concat('login.html')
            })
            .state('enrollment_confirm',{
                url: '/enrollment_confirm/:id/:token',
                templateUrl: prefix.concat('enrollmentConfirm.html'),
                controller: 'EnrollmentConfirm'
            })
            .state('unsubscribe',{
                url: '/unsubscribe/:id/:workshopid/:token',
                templateUrl: prefix.concat('unsubscribemessage.html'),
                controller: 'UnsubscribeController'
            })
            .state('password_reset',{
                url: '/password_reset/:token',
                templateUrl: prefix.concat('passwordReset.html'),
                controller: 'PasswordRestCtrl'
            })
            .state('dashboard',{
                url: '/dashboard',
                controller: 'DashboardCtrl',
                templateUrl: prefix.concat('adminDashboard.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template',{
                url:'/workshop_template',
                controller:'WorkshopTemplateCtrl',
                templateUrl: prefix.concat('adminWorkshopTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template.new', {
                url: '/new',
                controller: 'NewWorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template.edit', {
                url: '/edit/:id',
                controller: 'EditWorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })

            //Müsste geschaut werden ob es passt erstellt von Ahmet
            .state('email_template', {
                url: '/email_template',
                controller: 'EmailTemplateCtrl',
                templateUrl: prefix.concat('adminEmailTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })

            .state('email_template.new', {
                url: '/new',
                controller: 'NewEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.edit', {
                url: '/edit/:id',
                controller: 'EditEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('blacklist',{
                url: '/blacklist',
                controller: 'BlacklistCtrl',
                templateUrl: prefix.concat('adminBlacklist.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('administrator_management', {
                    url: '/administrator_management',
                    controller: 'AdministratorManagementCtrl',
                    templateUrl: prefix.concat('administratorManagement.html'),
                data: {
                    //requiresLogin: true
                }
                })
            .state('settings', {
                url: '/settings',
                controller: 'SettingsCtrl',
                templateUrl: prefix.concat('adminSettings.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_managment',{
                url: '/workshop_managment',
                controller: 'WorkshopManagmentCtrl',
                templateUrl: prefix.concat('adminWorkshopManagement.html')
            })
            .state('admininvite',{
                url: '/admin/create/:token',
                controller: 'AdminCreateCtrl',
                templateUrl: prefix.concat('adminInvite.html')
            })
            .state('contact',{
                url: '/contact',
                controller: 'ContactCtrl',
                templateUrl: prefix.concat('contact.html')
            });

        $urlRouterProvider.otherwise('/workshops');

    }
]);

mainApp.config(['jwtInterceptorProvider','$httpProvider','$urlRouterProvider',function(jwtInterceptorProvider,$httpProvider,$urlRouterProvider){
    jwtInterceptorProvider.tokenGetter = function(store) {
        return store.get('jwt');
    }

    $httpProvider.interceptors.push('jwtInterceptor');
}])
    .run(['$rootScope','$state','store','jwtHelper','UIHelper',function($rootScope, $state, store, jwtHelper,UIHelper) {
        UIHelper.ToggleLogout();
        $rootScope.$on('$stateChangeStart', function(e, to) {
            if (to.data.requiresLogin) {
                if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                    e.preventDefault();
                    $state.go('login');
                }
            }

        });
    }]);

mainApp.config(['$translateProvider', function($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/local/lang-',
        suffix: '.json'
    });
    $translateProvider.preferredLanguage('en');
}]);
/**
 * @ngdoc service
 * @descrption Helper service to show or hide User UI elements
 * @name  mainApp.UIHelper
 */
mainApp.factory('UIHelper',['$rootScope','store','jwtHelper',function($rootScope,store,jwtHelper){
    return {
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#HideUserUI
         * @description hide the user UI
         * @methodOf mainApp.UIHelper
         */
        HideUserUI: function(){
            $rootScope.hide_user_ui = true;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ShowUserUI
         * @description show the user UI
         * @methodOf mainApp.UIHelper
         */
        ShowUserUI: function(){
            $rootScope.hide_user_ui = false;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleUserUI
         * @description toggle the user UI
         * @methodOf mainApp.UIHelper
         */
        ToggleUserUI: function(){
            $rootScope.hide_user_ui = ! $rootScope.hide_user_ui;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleLogout
         * @description Toggles, if the Logout or the Login Button is shown
         * @methodOf mainApp.UIHelper
         */
        ToggleLogout: function(){
            var jwt  = store.get('jwt');
            if(!jwt){
                $rootScope.logged_in = false;
                return;
            }
            $rootScope.logged_in = jwtHelper.isTokenExpired(jwt);
        }
    }
}]);
<commit_msg>Enrollment Succes Controller Updare<commit_after>/**
 * @name mainApp
 * @requieres
 * @type {angular.Module}
 * @description Main module of the application
 */
var mainApp = angular.module('mainApp',[
    'ngRoute',
    'mainAppCtrls',
    'mgcrea.ngStrap',
    'ui.router',
    'angular-jwt',
    'restSvcs',
    'angular-storage',
    'pascalprecht.translate'
]);
/**
 * @name mainAppCtrls
 * @type {angular.Module}
 * @description Module containg all controller of the application
 */
var mainAppCtrls = angular.module('mainAppCtrls',["pascalprecht.translate"]);

mainApp.config(['$urlRouterProvider','$stateProvider',
    function($urlRouterProvider,$stateProvider)
    {
        var prefix = "resources/views/";

        $stateProvider
            .state('workshops',{
                url: '/workshops',
                controller: 'WorkshopListCtrl',
                templateUrl: prefix.concat('workshopList.html')
            })
            .state('workshopsdetails',{
                url: '/workshops/details/:id',
                controller: 'WorkshopDetailsCtrl',
                templateUrl: prefix.concat('workshopDetails.html')
            })
            .state('login',{
                url: '/login',
                controller: 'LoginCtrl',
                templateUrl: prefix.concat('login.html')
            })
            .state('enrollment_confirm',{
                url: '/enrollment_confirm/:id/:token',
                templateUrl: prefix.concat('enrollmentConfirm.html'),
                controller: 'EnrollmentConfirmCrtl'
            })
            .state('unsubscribe',{
                url: '/unsubscribe/:id/:workshopid/:token',
                templateUrl: prefix.concat('unsubscribe.html'),
                controller: 'UnsubscribeController'
            })
            .state('password_reset',{
                url: '/password_reset/:token',
                templateUrl: prefix.concat('passwordReset.html'),
                controller: 'PasswordRestCtrl'
            })
            .state('dashboard',{
                url: '/dashboard',
                controller: 'DashboardCtrl',
                templateUrl: prefix.concat('adminDashboard.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template',{
                url:'/workshop_template',
                controller:'WorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplate.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template.new', {
                url: '/new',
                controller: 'NewWorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('workshop_template.edit', {
                url: '/edit/:id',
                controller: 'EditWorkshopTemplateCtrl',
                templateUrl: prefix.concat('workshopTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.new', {
                url: '/new',
                controller: 'NewEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('email_template.edit', {
                url: '/edit/:id',
                controller: 'EditEmailTemplateCtrl',
                templateUrl: prefix.concat('emailTemplateNew.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('blacklist',{
                url: '/blacklist',
                controller: 'BlacklistCtrl',
                templateUrl: prefix.concat('adminBlacklist.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('administrator_management', {
                    url: '/administrator_management',
                    controller: 'AdministratorManagementCtrl',
                    templateUrl: prefix.concat('administratorManagement.html'),
                data: {
                    //requiresLogin: true
                }
                })
            .state('settings', {
                url: '/settings',
                controller: 'SettingsCtrl',
                templateUrl: prefix.concat('adminSettings.html'),
                data: {
                    //requiresLogin: true
                }
            })
            .state('admininvite',{
                url: '/admin/create/:token',
                controller: 'AdminCreateCtrl',
                templateUrl: prefix.concat('adminInvite.html')
            })
            .state('contact',{
                url: '/contact',
                controller: 'ContactCtrl',
                templateUrl: prefix.concat('contact.html')
            });

        $urlRouterProvider.otherwise('/workshops');

    }
]);

mainApp.config(['jwtInterceptorProvider','$httpProvider','$urlRouterProvider',function(jwtInterceptorProvider,$httpProvider,$urlRouterProvider){
    jwtInterceptorProvider.tokenGetter = function(store) {
        return store.get('jwt');
    }

    $httpProvider.interceptors.push('jwtInterceptor');
}])
    .run(['$rootScope','$state','store','jwtHelper',function($rootScope, $state, store, jwtHelper) {
        $rootScope.$on('$stateChangeStart', function(e, to) {
            if (to.data && to.data.requiresLogin) {
                if (!store.get('jwt') || jwtHelper.isTokenExpired(store.get('jwt'))) {
                    e.preventDefault();
                    $state.go('login');
                }
            }
        });
    }]);

mainApp.config(['$translateProvider', function($translateProvider) {
    $translateProvider.useStaticFilesLoader({
        prefix: 'resources/local/lang-',
        suffix: '.json'
    });
    $translateProvider.preferredLanguage('en');
}]);
/**
 * @ngdoc service
 * @descrption Helper service to show or hide User UI elements
 * @name  mainApp.UIHelper
 */
mainApp.factory('UIHelper',['$rootScope',function($rootScope){
    return {
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#HideUserUI
         * @description hide the user UI
         * @methodOf mainApp.UIHelper
         */
        HideUserUI: function(){
            $rootScope.hide_user_ui = true;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ShowUserUI
         * @description show the user UI
         * @methodOf mainApp.UIHelper
         */
        ShowUserUI: function(){
            $rootScope.hide_user_ui = false;
        },
        /**
         * @ngdoc function
         * @name mainApp.UIHelper#ToggleUserUI
         * @description toggle the user UI
         * @methodOf mainApp.UIHelper
         */
        ToggleUserUI: function(){
            $rootScope.hide_user_ui = ! $rootScope.hide;
        }
    }
}]);
<|endoftext|>