<commit_before>// Global Variables Declaration -- start

var svgNS = "http://www.w3.org/2000/svg";
var pageLoaded = 0;
var displayNow = 0;
var possibleContainers, containerRotationMode;

// Some global variables are declared within the pageloading part of the code.
// Global Variables Declaration -- end

// Code used for start up -- start

function displayNone()
{
  var i;
  // looping all possible containers
  for(i = 1; i <= possibleContainers; i++)
  {
    document.getElementById("container"+i).style.display = "none";
  }
}

function visibilityHidden()
{
  var i;
  // looping all possible containers
  for(i = 1; i <= possibleContainers; i++)
  {
    document.getElementById("container"+i).style.visibility = "hidden";
  }
}

function setHenosisAt(cx, cy)
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosis").setAttribute('cx', cx);
  document.getElementById("henosis").setAttribute('cy', cy);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

  var ua = navigator.userAgent.toLowerCase();
  var isAppleWebKit = ua.indexOf("applewebkit") > -1;

  if(isAppleWebKit)
  {
    var leftPosition = cx - 20;
    var topPosition = cy - 20;
  }
  else
  {
    var leftPosition = cx-(windowWidth/2);
    var topPosition = cy-(windowHeight/2);
  }

  document.getElementById("henosis").style.left = leftPosition+"px";
  document.getElementById("henosis").style.top = topPosition+"px";
}

function setHenosisAtCentre()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosis").setAttribute('cx', windowWidth/2);
  document.getElementById("henosis").setAttribute('cy', windowHeight/2);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");
}

function henosisLayerFix()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosisLayer").style.height = windowHeight+"px";
  document.getElementById("henosisLayer").style.width = windowWidth+"px";
}

function start(cx = "NULL", cy = "NULL")
{
  var ua = navigator.userAgent.toLowerCase();
  var isAndroid = ua.indexOf("android") > -1;

  if(containerRotationMode == "display")
  {
    displayNone();
  }
  else if(containerRotationMode == "visibility")
  {
    visibilityHidden();
  }
  else
  {
    console.log("Error: Unsupported containerRotationMode!");
  }

  if(cx != "NULL" && cy != "NULL")
  {
    setHenosisAt(cx, cy);
  }
  else
  {
    setHenosisAtCentre();
  }

  if(isAndroid)
  {
    henosisLayerFix();
  }
}

// start();

// Code used for start up -- end

// Code used for dragging -- start

$( function() {
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  $('#henosis').draggable({
    containment: [ 0, 0, windowWidth-40, windowHeight-40]
  })
  // .bind('mousedown', function(event, ui){
  //   // bring target to front
  //   $(event.target.parentElement).append( event.target );
  // })
  .bind('drag', function(event, ui){
    var ua = navigator.userAgent.toLowerCase();

    var isAppleWebKit = ua.indexOf("applewebkit") > -1;
    // var isAppleWebKit = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());

    var isSafari = ua.indexOf("safari") > -1;
    // var isSafari = /safari/.test(navigator.userAgent.toLowerCase());

    if(isSafari && !isAppleWebKit)
    {
      var leftPosition = event.pageX; // event.pageX gives the  mouse position relative to the left edge of the document.
      var topPosition = event.pageY; // event.pageY gives the  mouse position relative to the right edge of the document.

      // contain the henosis within the window's dimensions
      if(leftPosition < 20)
      {
        leftPosition = 20;
      }
      if(leftPosition > windowWidth - 20)
      {
        leftPosition = windowWidth - 20;
      }

      if(topPosition < 20)
      {
        topPosition = 20;
      }
      if(topPosition > windowHeight - 20)
      {
        topPosition = windowHeight - 20;
      }
    }
    else if(isAppleWebKit)
    {
      var leftPosition = ui.position.left + 20;
      var topPosition = ui.position.top + 20;
    }
    else
    {
      var leftPosition = ui.position.left+(windowWidth/2);
      var topPosition = ui.position.top+(windowHeight/2);
    }

    // update coordinates manually, since top/left style props don't work on SVG
    event.target.setAttribute('cx', leftPosition);
    event.target.setAttribute('cy', topPosition);
    changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

  });
} );

// Code used for dragging -- end

// Code used for page refresh -- start
function resizeSetting()
{
  // Move to a better containment when possible.

  var ua = navigator.userAgent.toLowerCase();
  var isAndroid = ua.indexOf("android") > -1;

  if(isAndroid)
  {
    $(window).bind('orientationchange', function(e)
    {
      if (window.RT) clearTimeout(window.RT);
      window.RT = setTimeout(function()
      {
        this.location.reload(false); /* false to get page from cache */
      }, 200);
    });
  }
  else
  {
    // See: https://www.sitepoint.com/jquery-refresh-page-browser-resize/
    //refresh page on browser resize
    $(window).bind('resize', function(e)
    {
      if (window.RT) clearTimeout(window.RT);
      window.RT = setTimeout(function()
      {
        this.location.reload(false); /* false to get page from cache */
      }, 200);
    });
  }
}
// Code used for page refresh -- end

// Code for scaleUpAct and for switching containers -- start

function createActCircle(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircle");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","white");
  myCircle.setAttributeNS(null,"stroke","none");
  myCircle.setAttributeNS(null,"style","opacity: 1;");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function createActCircleShadow(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircleShadow");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","grey");
  myCircle.setAttributeNS(null,"stroke","none");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function displayToggle()
{
  if(containerRotationMode == "display")
  {
    if(displayNow==0)
    {
      displayNow++;
      document.getElementById("container"+displayNow).style.display = "block";
    }
    else if(displayNow == possibleContainers)
    {
      document.getElementById("container"+displayNow).style.display = "none";
      displayNow = 1;
      document.getElementById("container"+displayNow).style.display = "block";
    }
    else
    {
      document.getElementById("container"+displayNow).style.display = "none";
      displayNow++;
      document.getElementById("container"+displayNow).style.display = "block";
    }
  }
  else if(containerRotationMode == "visibility")
  {
    if(displayNow==0)
    {
      displayNow++;
      document.getElementById("container"+displayNow).style.visibility = "visible";
    }
    else if(displayNow == possibleContainers)
    {
      document.getElementById("container"+displayNow).style.visibility = "hidden";
      displayNow = 1;
      document.getElementById("container"+displayNow).style.visibility = "visible";
    }
    else
    {
      document.getElementById("container"+displayNow).style.visibility = "hidden";
      displayNow++;
      document.getElementById("container"+displayNow).style.visibility = "visible";
    }
  }
}

function reduceOpacity()
{
  setTimeout(function () {
    var opacity = document.getElementById("actCircle").style.opacity;
    if(opacity>0)
    {
      document.getElementById("actCircle").style.opacity = (parseFloat(opacity)-parseFloat(0.2));
      reduceOpacity();
    }
    else
    {
      document.getElementById("actCircle").remove();
      if (document.getElementById("henosis").addEventListener)
      {
        // all browsers except IE before version 9
        // $('#henosis').off('click');
        document.getElementById("henosis").addEventListener("click", henosisScaleUpActStart, true);
      }
      else
      {
        if (document.getElementById("henosis").attachEvent)
        {
          // IE before version 9
          document.getElementById("henosis").attachEvent("click", henosisScaleUpActStart);
        }
      }
    }
  }, 50);
}

function scaleUpActComplete()
{
  document.getElementById("actCircleShadow").remove();
  if(pageLoaded==0)
  {
    document.getElementById("henosisLayer").style.background="none";
    pageLoaded=1;
  }
  displayToggle();
  reduceOpacity();
}

function henosisActCircleScaleUpAct(maxValue)
{
  setTimeout(function () {
    var radius = document.getElementById("actCircle").getAttribute('r');
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if(radius<maxValue)
    {
      document.getElementById("actCircle").setAttribute('r', parseFloat(radius)+parseFloat(maxValue/15));
      changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
      henosisActCircleScaleUpAct(maxValue);
    }
    else
    {
      scaleUpActComplete();
    }
  }, 10);
}

function henosisScaleUpActStart()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  var diagonalLength = Math.sqrt((windowWidth*windowWidth)+(windowHeight*windowHeight));
  var cx = document.getElementById("henosis").getAttribute('cx');
  var cy = document.getElementById("henosis").getAttribute('cy');
  createActCircleShadow(cx, cy);
  createActCircle(cx, cy);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
  henosisActCircleScaleUpAct(diagonalLength);
}

// Code for scaleUpAct and for switching containers -- end

// pageloading part -- start
var colors = new Array( "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red");
var colornow=1;
var loopStop=0;
function changeBackground(color) {
  document.getElementById("henosis").setAttribute('fill', color);
}

function incrementcolor() {
  if(colornow==6) {
    colornow=0;
  }
  else {
    colornow++;
  }
}

function loopLi() {
  setTimeout(function () {
    changeBackground(colors[colornow]);
    incrementcolor();
    if(loopStop==0)
    {
      loopLi();
    }
    else
    {
      document.getElementById("henosis").setAttribute('fill', "white");
      henosisScaleUpActStart();
    }
  }, 1000);
}

// loopLi();
// pageloading part -- end

// pageloaded -- start
$(window).on('load', function()
{
  loopStop=1;
});
// pageloaded -- end

// henosis initialization function - usage help -- start
//
//  henosisInit(possibleContainersParameter, containerRotationModeParameter, cx, cy);
//
//  1) possibleContainersParameter
//      Set the number of containers you would like to have in the website.
//      Values: INTEGER.
//
//  2) containerRotationModeParameter
//      Set the mode of operation for container rotation below.
//      Values: "display", "visibility";
//
//  3) cx
//      Set the initial cx coordinate for henosis.
//      Values: Range(20, (viewportWidth-20));
//
//  4) cy
//      Set the initial cy coordinate for henosis.
//      Values: Range(20, (viewportHeight-20));
//
// henosis initialization function - usage help -- end

// Code for henosis initialization function -- start

function henosisInit(possibleContainersParameter = 2, containerRotationModeParameter = "display", cx = "NULL", cy = "NULL")
{
  possibleContainers = possibleContainersParameter;
  containerRotationMode = containerRotationModeParameter;
  start(cx, cy);
  loopLi();
  resizeSetting();
}

// Code for henosis initialization function -- end
<commit_msg>Update henosis.js<commit_after>// Global Variables Declaration -- start

var svgNS = "http://www.w3.org/2000/svg";
var pageLoaded = 0;
var displayNow = 0;
var possibleContainers, containerRotationMode;

// Some global variables are declared within the pageloading part of the code.
// Global Variables Declaration -- end

// Code used for start up -- start

function displayNone()
{
  var i;
  // looping all possible containers
  for(i = 1; i <= possibleContainers; i++)
  {
    document.getElementById("container"+i).style.display = "none";
  }
}

function visibilityHidden()
{
  var i;
  // looping all possible containers
  for(i = 1; i <= possibleContainers; i++)
  {
    document.getElementById("container"+i).style.visibility = "hidden";
  }
}

function setHenosisAt(cx, cy)
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosis").setAttribute('cx', cx);
  document.getElementById("henosis").setAttribute('cy', cy);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

  var ua = navigator.userAgent.toLowerCase();
  var isAppleWebKit = ua.indexOf("applewebkit") > -1;

  if(isAppleWebKit)
  {
    var leftPosition = cx - 20;
    var topPosition = cy - 20;
  }
  else
  {
    var leftPosition = cx-(windowWidth/2);
    var topPosition = cy-(windowHeight/2);
  }

  document.getElementById("henosis").style.left = leftPosition+"px";
  document.getElementById("henosis").style.top = topPosition+"px";
}

function setHenosisAtCentre()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosis").setAttribute('cx', windowWidth/2);
  document.getElementById("henosis").setAttribute('cy', windowHeight/2);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");
}

function henosisLayerFix()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  document.getElementById("henosisLayer").style.height = windowHeight+"px";
  document.getElementById("henosisLayer").style.width = windowWidth+"px";
}

function start(cx = "NULL", cy = "NULL")
{
  var ua = navigator.userAgent.toLowerCase();
  var isAndroid = ua.indexOf("android") > -1;

  if(containerRotationMode == "display")
  {
    displayNone();
  }
  else if(containerRotationMode == "visibility")
  {
    visibilityHidden();
  }
  else
  {
    console.log("Error: Unsupported containerRotationMode!");
  }

  if(cx != "NULL" && cy != "NULL")
  {
    setHenosisAt(cx, cy);
  }
  else
  {
    setHenosisAtCentre();
  }

  if(isAndroid)
  {
    henosisLayerFix();
  }
}

// start();

// Code used for start up -- end

// Code used for dragging -- start

$( function() {
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  $('#henosis').draggable({
    containment: [ 0, 0, windowWidth-40, windowHeight-40]
  })
  // .bind('mousedown', function(event, ui){
  //   // bring target to front
  //   $(event.target.parentElement).append( event.target );
  // })
  .bind('drag', function(event, ui){
    var ua = navigator.userAgent.toLowerCase();

    var isAppleWebKit = ua.indexOf("applewebkit") > -1;
    // var isAppleWebKit = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());

    var isSafari = ua.indexOf("safari") > -1;
    // var isSafari = /safari/.test(navigator.userAgent.toLowerCase());

    if(isSafari)
    {
      var leftPosition = event.pageX; // event.pageX gives the  mouse position relative to the left edge of the document.
      var topPosition = event.pageY; // event.pageY gives the  mouse position relative to the right edge of the document.

      // contain the henosis within the window's dimensions
      if(leftPosition < 20)
      {
        leftPosition = 20;
      }
      if(leftPosition > windowWidth - 20)
      {
        leftPosition = windowWidth - 20;
      }

      if(topPosition < 20)
      {
        topPosition = 20;
      }
      if(topPosition > windowHeight - 20)
      {
        topPosition = windowHeight - 20;
      }
    }
    else if(isAppleWebKit)
    {
      var leftPosition = ui.position.left + 20;
      var topPosition = ui.position.top + 20;
    }
    else
    {
      var leftPosition = ui.position.left+(windowWidth/2);
      var topPosition = ui.position.top+(windowHeight/2);
    }

    // update coordinates manually, since top/left style props don't work on SVG
    event.target.setAttribute('cx', leftPosition);
    event.target.setAttribute('cy', topPosition);
    changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "henosis", "shadow");

  });
} );

// Code used for dragging -- end

// Code used for page refresh -- start
function resizeSetting()
{
  // Move to a better containment when possible.

  var ua = navigator.userAgent.toLowerCase();
  var isAndroid = ua.indexOf("android") > -1;

  if(isAndroid)
  {
    $(window).bind('orientationchange', function(e)
    {
      if (window.RT) clearTimeout(window.RT);
      window.RT = setTimeout(function()
      {
        this.location.reload(false); /* false to get page from cache */
      }, 200);
    });
  }
  else
  {
    // See: https://www.sitepoint.com/jquery-refresh-page-browser-resize/
    //refresh page on browser resize
    $(window).bind('resize', function(e)
    {
      if (window.RT) clearTimeout(window.RT);
      window.RT = setTimeout(function()
      {
        this.location.reload(false); /* false to get page from cache */
      }, 200);
    });
  }
}
// Code used for page refresh -- end

// Code for scaleUpAct and for switching containers -- start

function createActCircle(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircle");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","white");
  myCircle.setAttributeNS(null,"stroke","none");
  myCircle.setAttributeNS(null,"style","opacity: 1;");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function createActCircleShadow(cx, cy)
{
  var myCircle = document.createElementNS(svgNS,"circle"); //to create a circle. for rectangle use "rectangle"
  myCircle.setAttributeNS(null,"id","actCircleShadow");
  myCircle.setAttributeNS(null,"cx",cx);
  myCircle.setAttributeNS(null,"cy",cy);
  myCircle.setAttributeNS(null,"r",20);
  myCircle.setAttributeNS(null,"fill","grey");
  myCircle.setAttributeNS(null,"stroke","none");
  document.getElementById("henosisLayer").appendChild(myCircle);
}

function displayToggle()
{
  if(containerRotationMode == "display")
  {
    if(displayNow==0)
    {
      displayNow++;
      document.getElementById("container"+displayNow).style.display = "block";
    }
    else if(displayNow == possibleContainers)
    {
      document.getElementById("container"+displayNow).style.display = "none";
      displayNow = 1;
      document.getElementById("container"+displayNow).style.display = "block";
    }
    else
    {
      document.getElementById("container"+displayNow).style.display = "none";
      displayNow++;
      document.getElementById("container"+displayNow).style.display = "block";
    }
  }
  else if(containerRotationMode == "visibility")
  {
    if(displayNow==0)
    {
      displayNow++;
      document.getElementById("container"+displayNow).style.visibility = "visible";
    }
    else if(displayNow == possibleContainers)
    {
      document.getElementById("container"+displayNow).style.visibility = "hidden";
      displayNow = 1;
      document.getElementById("container"+displayNow).style.visibility = "visible";
    }
    else
    {
      document.getElementById("container"+displayNow).style.visibility = "hidden";
      displayNow++;
      document.getElementById("container"+displayNow).style.visibility = "visible";
    }
  }
}

function reduceOpacity()
{
  setTimeout(function () {
    var opacity = document.getElementById("actCircle").style.opacity;
    if(opacity>0)
    {
      document.getElementById("actCircle").style.opacity = (parseFloat(opacity)-parseFloat(0.2));
      reduceOpacity();
    }
    else
    {
      document.getElementById("actCircle").remove();
      if (document.getElementById("henosis").addEventListener)
      {
        // all browsers except IE before version 9
        // $('#henosis').off('click');
        document.getElementById("henosis").addEventListener("click", henosisScaleUpActStart, true);
      }
      else
      {
        if (document.getElementById("henosis").attachEvent)
        {
          // IE before version 9
          document.getElementById("henosis").attachEvent("click", henosisScaleUpActStart);
        }
      }
    }
  }, 50);
}

function scaleUpActComplete()
{
  document.getElementById("actCircleShadow").remove();
  if(pageLoaded==0)
  {
    document.getElementById("henosisLayer").style.background="none";
    pageLoaded=1;
  }
  displayToggle();
  reduceOpacity();
}

function henosisActCircleScaleUpAct(maxValue)
{
  setTimeout(function () {
    var radius = document.getElementById("actCircle").getAttribute('r');
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    if(radius<maxValue)
    {
      document.getElementById("actCircle").setAttribute('r', parseFloat(radius)+parseFloat(maxValue/15));
      changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
      henosisActCircleScaleUpAct(maxValue);
    }
    else
    {
      scaleUpActComplete();
    }
  }, 10);
}

function henosisScaleUpActStart()
{
  var windowHeight = $(window).height();
  var windowWidth = $(window).width();
  var diagonalLength = Math.sqrt((windowWidth*windowWidth)+(windowHeight*windowHeight));
  var cx = document.getElementById("henosis").getAttribute('cx');
  var cy = document.getElementById("henosis").getAttribute('cy');
  createActCircleShadow(cx, cy);
  createActCircle(cx, cy);
  changeShadowOfSVGElement((windowWidth/2), (windowHeight/2), 1, 0.005, "actCircle", "actCircleShadow");
  henosisActCircleScaleUpAct(diagonalLength);
}

// Code for scaleUpAct and for switching containers -- end

// pageloading part -- start
var colors = new Array( "Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red");
var colornow=1;
var loopStop=0;
function changeBackground(color) {
  document.getElementById("henosis").setAttribute('fill', color);
}

function incrementcolor() {
  if(colornow==6) {
    colornow=0;
  }
  else {
    colornow++;
  }
}

function loopLi() {
  setTimeout(function () {
    changeBackground(colors[colornow]);
    incrementcolor();
    if(loopStop==0)
    {
      loopLi();
    }
    else
    {
      document.getElementById("henosis").setAttribute('fill', "white");
      henosisScaleUpActStart();
    }
  }, 1000);
}

// loopLi();
// pageloading part -- end

// pageloaded -- start
$(window).on('load', function()
{
  loopStop=1;
});
// pageloaded -- end

// henosis initialization function - usage help -- start
//
//  henosisInit(possibleContainersParameter, containerRotationModeParameter, cx, cy);
//
//  1) possibleContainersParameter
//      Set the number of containers you would like to have in the website.
//      Values: INTEGER.
//
//  2) containerRotationModeParameter
//      Set the mode of operation for container rotation below.
//      Values: "display", "visibility";
//
//  3) cx
//      Set the initial cx coordinate for henosis.
//      Values: Range(20, (viewportWidth-20));
//
//  4) cy
//      Set the initial cy coordinate for henosis.
//      Values: Range(20, (viewportHeight-20));
//
// henosis initialization function - usage help -- end

// Code for henosis initialization function -- start

function henosisInit(possibleContainersParameter = 2, containerRotationModeParameter = "display", cx = "NULL", cy = "NULL")
{
  possibleContainers = possibleContainersParameter;
  containerRotationMode = containerRotationModeParameter;
  start(cx, cy);
  loopLi();
  resizeSetting();
}

// Code for henosis initialization function -- end
<|endoftext|>


<commit_before>(function() {

  var view;

  module("Backbone.View", {

    setup: function() {
      view = new Backbone.View({
        id        : 'test-view',
        className : 'test-view',
        other     : 'non-special-option'
      });
    }

  });

  test("constructor", 3, function() {
    equal(view.el.id, 'test-view');
    equal(view.el.className, 'test-view');
    equal(view.el.other, void 0);
  });

  test("$", 2, function() {
    var view = new Backbone.View;
    view.setElement('
test
');
    var result = view.$('a b');

    strictEqual(result[0].innerHTML, 'test');
    ok(result.length === +result.length);
  });

  test("jQuery", function() {
    var view = new Backbone.View;
    view.setElement('
test
');

    if (Backbone.$) {
      ok(view.$el instanceof Backbone.$);
      equal(view.$el[0], view.el);
    } else {
      ok(view.el.nodeType === 1);
    }
  });

  test("initialize", 1, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.one = 1;
      }
    });

    strictEqual(new View().one, 1);
  });

  test("delegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 3);
    equal(counter2, 3);
  });

  test("delegate", 2, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    view.delegate('click', 'h1', view.increment);
    view.delegate('click', view.increment);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 1);
  });

  test("delegateEvents allows functions for callbacks", 3, function() {
    var view = new Backbone.View({el: '

'});
    view.counter = 0;

    var events = {
      click: function() {
        this.counter++;
      }
    };

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 1);

    view.$el.trigger('click');
    equal(view.counter, 2);

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 3);
  });

  test("delegateEvents ignore undefined methods", 0, function() {
    var view = new Backbone.View({el: '

'});
    view.delegateEvents({'click': 'undefinedMethod'});
    view.$el.trigger('click');
  });

  test("undelegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.undelegateEvents();
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 3);
  });

  test("undelegate", 0, function() {
    view.delegate('click', function() { ok(false); });
    view.delegate('click', 'h1', function() { ok(false); });

    view.undelegate('click');

    view.$('h1').trigger('click');
    view.$el.trigger('click');
  })

  test("undelegate with passed handler", 1, function() {
    var listener = view.delegate('click', function() { ok(false); });
    view.delegate('click', function() { ok(true); });
    view.undelegate('click', listener);
    view.$el.trigger('click');
  });

  test("undelegate with selector", 2, function() {
    var counter1 = 0, counter2 = 0;
    view.delegate('click', function() { counter1++; });
    view.delegate('click', 'h1', function() { counter2++; });

    view.undelegate('click', 'h1');

    view.$('h1').trigger('click');
    view.$el.trigger('click');

    equal(counter1, 1);
    equal(counter2, 0);
  });

  test("_ensureElement with DOM node el", 1, function() {
    var View = Backbone.View.extend({
      el: document.body
    });

    equal(new View().el, document.body);
  });

  test("_ensureElement with string el", 3, function() {
    var View = Backbone.View.extend({
      el: "body"
    });
    strictEqual(new View().el, document.body);

    View = Backbone.View.extend({
      el: "#testElement > h1"
    });
    strictEqual(new View().el, $("#testElement > h1").get(0));

    View = Backbone.View.extend({
      el: "#nonexistent"
    });
    ok(!new View().el);
  });

  test("with className and id functions", 2, function() {
    var View = Backbone.View.extend({
      className: function() {
        return 'className';
      },
      id: function() {
        return 'id';
      }
    });

    strictEqual(new View().el.className, 'className');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes", 2, function() {
    var View = Backbone.View.extend({
      attributes: {
        id: 'id',
        'class': 'class'
      }
    });

    strictEqual(new View().el.className, 'class');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes as a function", 1, function() {
    var View = Backbone.View.extend({
      attributes: function() {
        return {'class': 'dynamic'};
      }
    });

    strictEqual(new View().el.className, 'dynamic');
  });

  test("multiple views per element", 3, function() {
    var count = 0;
    var $el = $('

');

    var View = Backbone.View.extend({
      el: $el,
      events: {
        click: function() {
          count++;
        }
      }
    });

    var view1 = new View;
    $el.trigger("click");
    equal(1, count);

    var view2 = new View;
    $el.trigger("click");
    equal(3, count);

    view1.delegateEvents();
    $el.trigger("click");
    equal(5, count);
  });

  test("custom events, with namespaces", 2, function() {
    var count = 0;

    var View = Backbone.View.extend({
      el: $('body'),
      events: function() {
        return {"fake$event.namespaced": "run"};
      },
      run: function() {
        count++;
      }
    });

    var view = new View;
    $('body').trigger('fake$event').trigger('fake$event');
    equal(count, 2);

    $('body').off('.namespaced');
    $('body').trigger('fake$event');
    equal(count, 2);
  });

  test("#1048 - setElement uses provided object.", 2, function() {
    var $el = $('body');

    var view = new Backbone.View({el: $el});
    ok(view.$el === $el);

    view.setElement($el = $($el));
    ok(view.$el === $el);
  });

  test("#986 - Undelegate before changing element.", 1, function() {
    var button1 = $('<button></button>');
    var button2 = $('<button></button>');

    var View = Backbone.View.extend({
      events: {
        click: function(e) {
          ok(view.el === e.target);
        }
      }
    });

    var view = new View({el: button1});
    view.setElement(button2);

    button1.trigger('click');
    button2.trigger('click');
  });

  test("#1172 - Clone attributes object", 2, function() {
    var View = Backbone.View.extend({
      attributes: {foo: 'bar'}
    });

    var view1 = new View({id: 'foo'});
    strictEqual(view1.el.id, 'foo');

    var view2 = new View();
    ok(!view2.el.id);
  });

  test("#1228 - tagName can be provided as a function", 1, function() {
    var View = Backbone.View.extend({
      tagName: function() {
        return 'p';
      }
    });

    ok(new View().el.tagName.toLowerCase() == 'p');
  });

  test("views stopListening", 0, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.listenTo(this.model, 'all x', function(){ ok(false); });
        this.listenTo(this.collection, 'all x', function(){ ok(false); });
      }
    });

    var view = new View({
      model: new Backbone.Model,
      collection: new Backbone.Collection
    });

    view.stopListening();
    view.model.trigger('x');
    view.collection.trigger('x');
  });

  test("Provide function for el.", 2, function() {
    var View = Backbone.View.extend({
      el: function() {
        return "

";
      }
    });

    var view = new View;
    ok(view.el.tagName.toLowerCase() == 'p');
    ok(view.$('a').length != 0);
  });

  test("events passed in options", 1, function() {
    var counter = 0;

    var View = Backbone.View.extend({
      el: '#testElement',
      increment: function() {
        counter++;
      }
    });

    var view = new View({
      events: {
        'click h1': 'increment'
      }
    });

    view.$('h1').trigger('click').trigger('click');
    equal(counter, 2);
  });

  test("remove", 2, function() {
    var el = view.el;
    document.body.appendChild(view.el);

    view.delegate('click', function() { ok(false); });
    view.listenTo(view, 'all x', function() { ok(false); });

    view.remove();

    strictEqual(view.el, el);
    notEqual(view.el.parentNode, document.body);

    view.$el.trigger('click');
    view.trigger('x');
  });

})();
<commit_msg>remove namespace test from custom events test.<commit_after>(function() {

  var view;

  module("Backbone.View", {

    setup: function() {
      view = new Backbone.View({
        id        : 'test-view',
        className : 'test-view',
        other     : 'non-special-option'
      });
    }

  });

  test("constructor", 3, function() {
    equal(view.el.id, 'test-view');
    equal(view.el.className, 'test-view');
    equal(view.el.other, void 0);
  });

  test("$", 2, function() {
    var view = new Backbone.View;
    view.setElement('
test
');
    var result = view.$('a b');

    strictEqual(result[0].innerHTML, 'test');
    ok(result.length === +result.length);
  });

  test("jQuery", function() {
    var view = new Backbone.View;
    view.setElement('
test
');

    if (Backbone.$) {
      ok(view.$el instanceof Backbone.$);
      equal(view.$el[0], view.el);
    } else {
      ok(view.el.nodeType === 1);
    }
  });

  test("initialize", 1, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.one = 1;
      }
    });

    strictEqual(new View().one, 1);
  });

  test("delegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 3);
    equal(counter2, 3);
  });

  test("delegate", 2, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    view.delegate('click', 'h1', view.increment);
    view.delegate('click', view.increment);

    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 1);
  });

  test("delegateEvents allows functions for callbacks", 3, function() {
    var view = new Backbone.View({el: '

'});
    view.counter = 0;

    var events = {
      click: function() {
        this.counter++;
      }
    };

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 1);

    view.$el.trigger('click');
    equal(view.counter, 2);

    view.delegateEvents(events);
    view.$el.trigger('click');
    equal(view.counter, 3);
  });

  test("delegateEvents ignore undefined methods", 0, function() {
    var view = new Backbone.View({el: '

'});
    view.delegateEvents({'click': 'undefinedMethod'});
    view.$el.trigger('click');
  });

  test("undelegateEvents", 6, function() {
    var counter1 = 0, counter2 = 0;

    var view = new Backbone.View({el: '#testElement'});
    view.increment = function(){ counter1++; };
    view.$el.on('click', function(){ counter2++; });

    var events = {'click h1': 'increment'};

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 1);

    view.undelegateEvents();
    view.$('h1').trigger('click');
    equal(counter1, 1);
    equal(counter2, 2);

    view.delegateEvents(events);
    view.$('h1').trigger('click');
    equal(counter1, 2);
    equal(counter2, 3);
  });

  test("undelegate", 0, function() {
    view.delegate('click', function() { ok(false); });
    view.delegate('click', 'h1', function() { ok(false); });

    view.undelegate('click');

    view.$('h1').trigger('click');
    view.$el.trigger('click');
  })

  test("undelegate with passed handler", 1, function() {
    var listener = view.delegate('click', function() { ok(false); });
    view.delegate('click', function() { ok(true); });
    view.undelegate('click', listener);
    view.$el.trigger('click');
  });

  test("undelegate with selector", 2, function() {
    var counter1 = 0, counter2 = 0;
    view.delegate('click', function() { counter1++; });
    view.delegate('click', 'h1', function() { counter2++; });

    view.undelegate('click', 'h1');

    view.$('h1').trigger('click');
    view.$el.trigger('click');

    equal(counter1, 1);
    equal(counter2, 0);
  });

  test("_ensureElement with DOM node el", 1, function() {
    var View = Backbone.View.extend({
      el: document.body
    });

    equal(new View().el, document.body);
  });

  test("_ensureElement with string el", 3, function() {
    var View = Backbone.View.extend({
      el: "body"
    });
    strictEqual(new View().el, document.body);

    View = Backbone.View.extend({
      el: "#testElement > h1"
    });
    strictEqual(new View().el, $("#testElement > h1").get(0));

    View = Backbone.View.extend({
      el: "#nonexistent"
    });
    ok(!new View().el);
  });

  test("with className and id functions", 2, function() {
    var View = Backbone.View.extend({
      className: function() {
        return 'className';
      },
      id: function() {
        return 'id';
      }
    });

    strictEqual(new View().el.className, 'className');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes", 2, function() {
    var View = Backbone.View.extend({
      attributes: {
        id: 'id',
        'class': 'class'
      }
    });

    strictEqual(new View().el.className, 'class');
    strictEqual(new View().el.id, 'id');
  });

  test("with attributes as a function", 1, function() {
    var View = Backbone.View.extend({
      attributes: function() {
        return {'class': 'dynamic'};
      }
    });

    strictEqual(new View().el.className, 'dynamic');
  });

  test("multiple views per element", 3, function() {
    var count = 0;
    var $el = $('

');

    var View = Backbone.View.extend({
      el: $el,
      events: {
        click: function() {
          count++;
        }
      }
    });

    var view1 = new View;
    $el.trigger("click");
    equal(1, count);

    var view2 = new View;
    $el.trigger("click");
    equal(3, count);

    view1.delegateEvents();
    $el.trigger("click");
    equal(5, count);
  });

  test("custom events", 2, function() {
    var count = 0;

    var View = Backbone.View.extend({
      el: $('body'),
      events: function() {
        return {"fake$event": "run"};
      },
      run: function() {
        count++;
      }
    });

    var view = new View;
    $('body').trigger('fake$event').trigger('fake$event');
    equal(count, 2);

    $('body').off('fake$event');
    $('body').trigger('fake$event');
    equal(count, 2);
  });

  test("#1048 - setElement uses provided object.", 2, function() {
    var $el = $('body');

    var view = new Backbone.View({el: $el});
    ok(view.$el === $el);

    view.setElement($el = $($el));
    ok(view.$el === $el);
  });

  test("#986 - Undelegate before changing element.", 1, function() {
    var button1 = $('<button></button>');
    var button2 = $('<button></button>');

    var View = Backbone.View.extend({
      events: {
        click: function(e) {
          ok(view.el === e.target);
        }
      }
    });

    var view = new View({el: button1});
    view.setElement(button2);

    button1.trigger('click');
    button2.trigger('click');
  });

  test("#1172 - Clone attributes object", 2, function() {
    var View = Backbone.View.extend({
      attributes: {foo: 'bar'}
    });

    var view1 = new View({id: 'foo'});
    strictEqual(view1.el.id, 'foo');

    var view2 = new View();
    ok(!view2.el.id);
  });

  test("#1228 - tagName can be provided as a function", 1, function() {
    var View = Backbone.View.extend({
      tagName: function() {
        return 'p';
      }
    });

    ok(new View().el.tagName.toLowerCase() == 'p');
  });

  test("views stopListening", 0, function() {
    var View = Backbone.View.extend({
      initialize: function() {
        this.listenTo(this.model, 'all x', function(){ ok(false); });
        this.listenTo(this.collection, 'all x', function(){ ok(false); });
      }
    });

    var view = new View({
      model: new Backbone.Model,
      collection: new Backbone.Collection
    });

    view.stopListening();
    view.model.trigger('x');
    view.collection.trigger('x');
  });

  test("Provide function for el.", 2, function() {
    var View = Backbone.View.extend({
      el: function() {
        return "

";
      }
    });

    var view = new View;
    ok(view.el.tagName.toLowerCase() == 'p');
    ok(view.$('a').length != 0);
  });

  test("events passed in options", 1, function() {
    var counter = 0;

    var View = Backbone.View.extend({
      el: '#testElement',
      increment: function() {
        counter++;
      }
    });

    var view = new View({
      events: {
        'click h1': 'increment'
      }
    });

    view.$('h1').trigger('click').trigger('click');
    equal(counter, 2);
  });

  test("remove", 2, function() {
    var el = view.el;
    document.body.appendChild(view.el);

    view.delegate('click', function() { ok(false); });
    view.listenTo(view, 'all x', function() { ok(false); });

    view.remove();

    strictEqual(view.el, el);
    notEqual(view.el.parentNode, document.body);

    view.$el.trigger('click');
    view.trigger('x');
  });

})();
<|endoftext|>


<commit_before>NCI.detailsNCI = $("#detailsNCI");
NCI.detailsTime = $("#detailsTime");
NCI.detailsFlows = $("#detailsFlows");
NCI.detailsEndpoints = $("#detailsEndpoints");
NCI.maxActivitySize = 0;

NCI.setupCommunities = function(data){
	NCI.Communities = data.Communities;
	NCI.CommunityGraph = data.CommunityGraph;
	NCI.Communities.sort(function(a, b){
		return a.Size- b.Size;
	});
	NCI.timestampNCI = data.NCI;
	NCI.timestamp = data.Time;

	NCI.detailsNCI.html(NCI.timestampNCI);
	NCI.detailsTime.html(NCI.parceDateForLastUpdate(NCI.timestamp));

	NCI.socialGraph.endpoints = 0;
	var sizesSum = 0;
	$.each(NCI.Communities, function(index, community){
		NCI.socialGraph.endpoints += community.Endpoints.length;
		sizesSum  += community.Size;
	});

	NCI.detailsEndpoints.html(NCI.parceNumberForView(sizesSum));
};

NCI.socialGraph  = (function(){
	var me = $("#socialGraph");

	var force;
	var color = d3.scale.category10();
	var notNetworkColor = "#000000";
	var isClustered = false;
	var isActivities = false;
	var isDevided = false;
	var isFiltered = false;

	me.show = function(devided, clustered, filtered, activities){
		if (NCI.Communities.length == 0){
			return;
		};
		//if we change type of graph (flows/activities) or need to redraw it from sratch
		if (isActivities != activities || !NCI.socialGraph.graph || (isClustered && !clustered)){
		    d3.select("#activities_graph").remove();
			var numOfPoints =  activities ?  NCI.CommunityGraph.Endpoints.length : NCI.socialGraph.endpoints;
			if (numOfPoints > NCI.max_vertices) {
				d3.select("#activities_graph").remove();
				d3.select("#socialGraph").append('text')
				.attr("id","activities_graph")
				.html('Too many endpoints to draw');
			} else {
				activities ? NCI.buildGraphData([NCI.CommunityGraph]) : NCI.buildGraphData(NCI.Communities);
				isClustered = clustered;
				isActivities = activities;
				isDevided = devided;
				isFiltered = filtered;
			    me.draw(devided, clustered, filtered);
				isClustered = clustered;
			}
		//otherwise just change appearance
		} else {
			isClustered = clustered;
			isActivities = activities;
			isDevided = devided;
			isFiltered = filtered;
		    me.setupNodes(filtered, devided, clustered);
		    force.start();
		}
	};

	//colorify and set radius
	me.setupNodes = function(filtered, devided, clustered){
		me.node.style("fill", function(d) {
			//if this dot is selected on Activities graph, draw it in red
			if (NCI.Social.selectedDot == d.name.split(":")[0])
			    return "FF0000";
		    if ( filtered && NCI.isExternal(d.name)){
			    return notNetworkColor;
		    };
		    return devided ? color(d.group) : color(0);
		});
		me.node.attr("r", function(d) {
			var radius = 4;
			if (NCI.Social.selectedDot == d.name.split(":")[0])
			    radius = 6;
			if (NCI.maxActivitySize > 0 && d.size) {
		 		radius = 4 + 8*(d.size/NCI.maxActivitySize);
		 	}
			return radius;
		});
		force.linkStrength(clustered ? 1 : 0);
	};

	me.draw = function(devided, clustered, filtered){
		var graphWidth = me.width();
		var graphHeight = $('#nciDetails').height() - 200;
		force = d3.layout.force()
		    .charge(-20)
			.linkDistance(30)
			.size([graphWidth,  graphHeight])
			.linkStrength(clustered ? 1 : 0);

	    me.activitiesGraphSvg = d3.select("#socialGraph").append("svg")
		    .attr("id","activities_graph")
			.attr("width", graphWidth)
			.attr("height", graphHeight);

		var setupLinks = function(){
			force.links(me.graph.links);
			me.activitiesGraphSvg.selectAll("line").remove();
			var linksData = me.activitiesGraphSvg.selectAll(".link").data(me.graph.links);
			me.link = linksData.enter().append("line")
		    .attr("class", "activities_link");
			linksData.exit().remove();
		};

		var setupNodes = function(){
			force.nodes(me.graph.nodes);
			me.activitiesGraphSvg.selectAll("circle").remove();
			var nodesData =  me.activitiesGraphSvg.selectAll(".node").data(me.graph.nodes);
            me.node = nodesData.enter().append("circle").call(force.drag);
            nodesData.exit().remove();
			me.setupNodes(isFiltered, isDevided, isClustered);
			me.node.append("title").html(function(d) { return d.name + "
" + d.connections + " connections" ; });
			if (isActivities) {
				me.node.on('click', function(d){
					var label = d.name.split(":")[0];
					if (NCI.Social.selectedDot == label){
						NCI.Social.removeCommunity(NCI.Social.selectedCommunity, NCI.Social.selectedDot);
						NCI.Social.selectedDot = undefined;
						setupLinks();
						setupNodes();
						force.start();
						return;
					} else if (NCI.Social.selectedDot !== undefined) {
						return;
					}
					NCI.Social.selectedDot = label;
					$.each(NCI.Communities, function(index, community){
						if (community.Label == NCI.Social.selectedDot){
							NCI.Social.selectedCommunity = community;
							NCI.Social.addCommunity(NCI.Social.selectedCommunity, NCI.Social.selectedDot);
							setupLinks();
							setupNodes();
							force.start();
							return false;
						}
					});
	 		    });
			};
		};

		setupLinks();
		setupNodes();
	    force.on("tick", function() {
	        me.link.attr("x1", function(d) { return d.source.x; })
	            .attr("y1", function(d) { return d.source.y; })
	            .attr("x2", function(d) { return d.target.x; })
	            .attr("y2", function(d) { return d.target.y; });

	        me.node.attr("cx", function(d) { return d.x; })
	            .attr("cy", function(d) { return d.y; });
		});
		force.start();
	};

	return me;
}());

NCI.Social = {}

NCI.Social.removeCommunity = function(community, endpoint){
    NCI.socialGraph.graph.nodes = $.grep(NCI.socialGraph.graph.nodes, function(node, index){
		var remove = node.group == 2;
		if (remove)
		  delete NCI.Social.endpointsHash[node.name];
		return !remove;
	});

    NCI.socialGraph.graph.links = $.grep(NCI.socialGraph.graph.links, function(link, index){
		var remove = NCI.Social.endpointsHash[link.target.name] === undefined || NCI.Social.endpointsHash[link.source.name] === undefined
		return !remove
	});
}

NCI.Social.addCommunity = function(community, endpoint){
	var externalIndex = 0;
	$.each(NCI.socialGraph.graph.nodes, function(index, node){
		if (node.name.split(":")[0] == endpoint){
			 externalIndex = node.index;
			 return
		}
	});

	var addConnection = function(endPoint, group, endpoints){
		if (endPoint == endpoint)
		     return  externalIndex;
		if (!NCI.Social.endpointsHash[endPoint]){
			var index = Object.keys(NCI.Social.endpointsHash).length
			NCI.Social.endpointsHash[endPoint] = {index: index,
				external: !endpoints.indexOf(endPoint),
				connections: 0,
			    group: group};

				NCI.socialGraph.graph.nodes.push({
					"index": index,
					"name": endPoint,
					"group": group,
					"connections": "test",
					"external": false
				});

		}
		NCI.Social.endpointsHash[endPoint].connections++;
		return NCI.Social.endpointsHash[endPoint].index;
	};

	$.each(community.Interactions, function(index, interacton){
		NCI.socialGraph.graph.links.push({
			"source": addConnection(interacton[0], 2, community.Endpoints),
			"target": addConnection(interacton[1], 2, community.Endpoints),
			"value": 1});
	});
}

NCI.buildGraphData = function(communities){
    NCI.socialGraph.graph = { "nodes":[], "links": []};
	NCI.Social.endpointsHash = {};

	var addConnection = function(endPoint, group, endpoints){
		if (!NCI.Social.endpointsHash[endPoint]){
			NCI.Social.endpointsHash[endPoint] = {index: Object.keys(NCI.Social.endpointsHash).length,
				external: !endpoints.indexOf(endPoint),
				connections: 0,
			    group: group};
		}
		NCI.Social.endpointsHash[endPoint].connections++;
		return NCI.Social.endpointsHash[endPoint].index;
	};

	$.each(communities, function(index, community){
		$.each(community.Interactions, function(index2, interacton){
			NCI.socialGraph.graph.links.push({
				"source": addConnection(interacton[0], index, community.Endpoints),
				"target": addConnection(interacton[1], index, community.Endpoints),
				"value": 1});
		});
	});

	NCI.maxActivitySize = 0;
	$.each(Object.keys(NCI.Social.endpointsHash), function(index, key){
		var endpoint = NCI.Social.endpointsHash[key];
		var semiIndex = key.search(":");
		var size = (semiIndex >= 0) ? key.substring(semiIndex + 1) : 0;
		if (NCI.maxActivitySize < parseInt(size))
		    NCI.maxActivitySize = parseInt(size);
		NCI.socialGraph.graph.nodes.push({
			"index": index,
			"name": key,
			"group": endpoint.group,
			"connections": endpoint.connections,
			"external": endpoint.external,
			"size": size
		});
	});
	return NCI.socialGraph.graph;
};

$(".hide-ncidetails").on('click', function(){
	$('#nciDetails').removeClass('details-view-show');
	NCI.nciHistogram.clean();
	NCI.socialGraph.text("");
	NCI.CommunityGraph = [];
	NCI.Communities = [];
	NCI.detailsEndpoints.html("");
	NCI.detailsNCI.html("");
	NCI.detailsTime.html("");
	NCI.detailsFlows.html("");
	NCI.socialGraph.graph = undefined;
	$($('#nciDetailsTabs').find("dd a")[0]).click();
});

$('#nciDetailsTabs').on('toggled', function (event, tab) {
	switch(tab[0].id) {
	    case "panelFlows":
	        NCI.socialGraph.show( false, false, false, false);
	        break;
	    case "panelFlowsByActivities":
	        NCI.socialGraph.show(true, false, false, false);
	        break;
	    case "panelFlowsPretty":
	        NCI.socialGraph.show(true, true, false, false);
	        break;
	    case "panelInternalFlows":
	        NCI.socialGraph.show(true, true, true, false);
	        break;
	    case "panelActivities":
	        NCI.socialGraph.show(false, false, false, true);
	        break;
	    case "panelActivitiesPretty":
	        NCI.socialGraph.show(true, true, false, true);
	        break;
	    case "panelActivitiesInternal":
	        NCI.socialGraph.show(true, true, true, true);
	        break;
	    default:
			NCI.nciHistogram.show();
			NCI.socialGraph.text("");
			NCI.socialGraph.graph = undefined;
	};
});
<commit_msg>Multiple activities selection for drill down<commit_after>NCI.detailsNCI = $("#detailsNCI");
NCI.detailsTime = $("#detailsTime");
NCI.detailsFlows = $("#detailsFlows");
NCI.detailsEndpoints = $("#detailsEndpoints");
NCI.maxActivitySize = 0;

NCI.setupCommunities = function(data){
	NCI.Communities = data.Communities;
	NCI.CommunityGraph = data.CommunityGraph;
	NCI.Communities.sort(function(a, b){
		return a.Size- b.Size;
	});
	NCI.timestampNCI = data.NCI;
	NCI.timestamp = data.Time;

	NCI.detailsNCI.html(NCI.timestampNCI);
	NCI.detailsTime.html(NCI.parceDateForLastUpdate(NCI.timestamp));

	NCI.socialGraph.endpoints = 0;
	var sizesSum = 0;
	$.each(NCI.Communities, function(index, community){
		NCI.socialGraph.endpoints += community.Endpoints.length;
		sizesSum  += community.Size;
	});

	NCI.detailsEndpoints.html(NCI.parceNumberForView(sizesSum));
};

NCI.socialGraph  = (function(){
	var me = $("#socialGraph");

	var force;
	var color = d3.scale.category10();
	var notNetworkColor = "#000000";
	var isClustered = false;
	var isActivities = false;
	var isDevided = false;
	var isFiltered = false;

	me.show = function(devided, clustered, filtered, activities){
		if (NCI.Communities.length == 0){
			return;
		};
		//if we change type of graph (flows/activities) or need to redraw it from sratch
		if (isActivities != activities || !NCI.socialGraph.graph || (isClustered && !clustered)){
		    d3.select("#activities_graph").remove();
			var numOfPoints =  activities ?  NCI.CommunityGraph.Endpoints.length : NCI.socialGraph.endpoints;
			if (numOfPoints > NCI.max_vertices) {
				d3.select("#activities_graph").remove();
				d3.select("#socialGraph").append('text')
				.attr("id","activities_graph")
				.html('Too many endpoints to draw');
			} else {
				activities ? NCI.buildGraphData([NCI.CommunityGraph]) : NCI.buildGraphData(NCI.Communities);
				isClustered = clustered;
				isActivities = activities;
				isDevided = devided;
				isFiltered = filtered;
			    me.draw(devided, clustered, filtered);
				isClustered = clustered;
			}
		//otherwise just change appearance
		} else {
			isClustered = clustered;
			isActivities = activities;
			isDevided = devided;
			isFiltered = filtered;
		    me.setupNodes(filtered, devided, clustered);
		    force.start();
		}
	};

	//colorify and set radius
	me.setupNodes = function(filtered, devided, clustered){
		me.node.style("fill", function(d) {
			//if this dot is selected on Activities graph, draw it in red
			if (NCI.Social.selectedDot == d.name.split(":")[0])
			    return "FF0000";
		    if ( filtered && NCI.isExternal(d.name)){
			    return notNetworkColor;
		    };
		    return devided ? color(d.group) : color(0);
		});
		me.node.attr("r", function(d) {
			var radius = 4;
			if (NCI.Social.selectedDot == d.name.split(":")[0])
			    radius = 6;
			if (NCI.maxActivitySize > 0 && d.size) {
		 		radius = 4 + 8*(d.size/NCI.maxActivitySize);
		 	}
			return radius;
		});
		force.linkStrength(clustered ? 1 : 0);
	};

	me.draw = function(devided, clustered, filtered){
		var graphWidth = me.width();
		var graphHeight = $('#nciDetails').height() - 200;
		force = d3.layout.force()
		    .charge(-20)
			.linkDistance(30)
			.size([graphWidth,  graphHeight])
			.linkStrength(clustered ? 1 : 0);

	    me.activitiesGraphSvg = d3.select("#socialGraph").append("svg")
		    .attr("id","activities_graph")
			.attr("width", graphWidth)
			.attr("height", graphHeight);

		var setupLinks = function(){
			force.links(me.graph.links);
			me.activitiesGraphSvg.selectAll("line").remove();
			var linksData = me.activitiesGraphSvg.selectAll(".link").data(me.graph.links);
			me.link = linksData.enter().append("line")
		    .attr("class", "activities_link");
			linksData.exit().remove();
		};

		NCI.Social.selectedDots = []
		var setupNodes = function(){
			force.nodes(me.graph.nodes);
			me.activitiesGraphSvg.selectAll("circle").remove();
			var nodesData =  me.activitiesGraphSvg.selectAll(".node").data(me.graph.nodes);
            me.node = nodesData.enter().append("circle").call(force.drag);
            nodesData.exit().remove();
			me.setupNodes(isFiltered, isDevided, isClustered);
			me.node.append("title").html(function(d) { return d.name + "
" + d.connections + " connections" ; });
			if (isActivities) {
				me.node.on('click', function(d){
					var label = d.name.split(":")[0];
					var group = NCI.Social.selectedDots.indexOf(label) + 1;
					if (group > 0){
						NCI.Social.selectedDots.splice(group - 1, 1)
						NCI.Social.removeCommunity(group);
						setupLinks();
						setupNodes();
						force.start();
						return;
					}
					NCI.Social.selectedDots.push(label);
					$.each(NCI.Communities, function(index, community){
						if (community.Label == label){
							NCI.buildGraphData.addCommunity(community, label);
							setupLinks();
							setupNodes();
							force.start();
							return false;
						}
					});
	 		    });
			};
		};

		setupLinks();
		setupNodes();
	    force.on("tick", function() {
	        me.link.attr("x1", function(d) { return d.source.x; })
	            .attr("y1", function(d) { return d.source.y; })
	            .attr("x2", function(d) { return d.target.x; })
	            .attr("y2", function(d) { return d.target.y; });

	        me.node.attr("cx", function(d) { return d.x; })
	            .attr("cy", function(d) { return d.y; });
		});
		force.start();
	};

	return me;
}());

NCI.Social = {}

NCI.Social.removeCommunity = function(group){
    NCI.socialGraph.graph.nodes = $.grep(NCI.socialGraph.graph.nodes, function(node, index){
		var remove = node.group == group
		if (remove)
		  delete NCI.Social.endpointsHash[node.name];
		return !remove;
	});

    NCI.socialGraph.graph.links = $.grep(NCI.socialGraph.graph.links, function(link, index){
		var remove = NCI.Social.endpointsHash[link.target.name] === undefined || NCI.Social.endpointsHash[link.source.name] === undefined
		return !remove
	});
	NCI.socialGraph.groupNumber--;
};

NCI.buildGraphData = function(communities){
    NCI.socialGraph.graph = { "nodes":[], "links": []};
    NCI.socialGraph.groupNumber = 0;
	NCI.Social.endpointsHash = {};
	NCI.maxActivitySize = 0;

	NCI.buildGraphData.addCommunity = function(community, mainEndpoint){
		var communityEndpoints = {};
		var startIndex = Object.keys(NCI.Social.endpointsHash).length
		var addConnection = function(endPoint, group, endpoints){
			var ip = endPoint.split(":")[0];
			if (!NCI.Social.endpointsHash[ip]){
			    if (!communityEndpoints[ip]){
					var size = endPoint.split(":")[1];
				    var index = Object.keys(communityEndpoints).length + startIndex
				    communityEndpoints[ip] = {
					    index: index,
					    external: !endpoints.indexOf(endPoint),
					    connections: 0,
						size: size,
				        group: group};
			    };
			    communityEndpoints[ip].connections++;
			    return communityEndpoints[ip].index;
		    } else {
		    	return NCI.Social.endpointsHash[ip].index;
		    }
		};

		$.each(community.Interactions, function(index, interacton){
			NCI.socialGraph.graph.links.push({
				source: addConnection(interacton[0], NCI.socialGraph.groupNumber, community.Endpoints),
				target: addConnection(interacton[1], NCI.socialGraph.groupNumber, community.Endpoints),
				value: 1});
		});

		$.each(Object.keys(communityEndpoints), function(index, key){
			if (mainEndpoint == key)
			   return
			var endpoint = communityEndpoints[key];
			if (NCI.maxActivitySize < parseInt(endpoint.size))
			    NCI.maxActivitySize = parseInt(endpoint.size);
			NCI.socialGraph.graph.nodes.push({
				index: endpoint.index,
				name: key,
				group: endpoint.group,
				connections: endpoint.connections,
				external: endpoint.external,
				size: endpoint.size
			});
			NCI.Social.endpointsHash[key] = communityEndpoints[key]
		});
		NCI.socialGraph.groupNumber++
	};

	$.each(communities, function(index, community){
		NCI.buildGraphData.addCommunity(community)
	});

	return NCI.socialGraph.graph;
};

$(".hide-ncidetails").on('click', function(){
	$('#nciDetails').removeClass('details-view-show');
	NCI.nciHistogram.clean();
	NCI.socialGraph.text("");
	NCI.CommunityGraph = [];
	NCI.Communities = [];
	NCI.detailsEndpoints.html("");
	NCI.detailsNCI.html("");
	NCI.detailsTime.html("");
	NCI.detailsFlows.html("");
	NCI.socialGraph.graph = undefined;
	$($('#nciDetailsTabs').find("dd a")[0]).click();
});

$('#nciDetailsTabs').on('toggled', function (event, tab) {
	switch(tab[0].id) {
	    case "panelFlows":
	        NCI.socialGraph.show( false, false, false, false);
	        break;
	    case "panelFlowsByActivities":
	        NCI.socialGraph.show(true, false, false, false);
	        break;
	    case "panelFlowsPretty":
	        NCI.socialGraph.show(true, true, false, false);
	        break;
	    case "panelInternalFlows":
	        NCI.socialGraph.show(true, true, true, false);
	        break;
	    case "panelActivities":
	        NCI.socialGraph.show(false, false, false, true);
	        break;
	    case "panelActivitiesPretty":
	        NCI.socialGraph.show(true, true, false, true);
	        break;
	    case "panelActivitiesInternal":
	        NCI.socialGraph.show(true, true, true, true);
	        break;
	    default:
			NCI.nciHistogram.show();
			NCI.socialGraph.text("");
			NCI.socialGraph.graph = undefined;
	};
});
<|endoftext|>


<commit_before>'use strict'

const ExtractTextPlugin = require('extract-text-webpack-plugin')

const merge = require('deep-assign')
const webpack = require('webpack')

const options = require('./options')
const base = require('./webpack.base.js')

const config = merge(base, {
  entry: options.paths.resolve('src/index.js'),

  output: {
    filename: options.isProduction ? 'vue-grid.min.js' : 'vue-grid.js',
    path: options.paths.output.main,
    library: 'VueGrid',
    libraryExport: 'default',
    libraryTarget: 'umd'
  },

  plugins: [
    new webpack.BannerPlugin({
      banner: options.banner,
      raw: true,
      entryOnly: true
    }),

    new ExtractTextPlugin({
      filename: options.isProduction ? 'vue-grid.min.css' : 'vue-grid.css'
    })
  ]
})

/*
// First item in module.rules array is Vue
config.module.rules[0].options.loaders = {
  scss: ExtractTextPlugin.extract({
    loader: 'css-loader!sass-loader',
    fallbackLoader: 'vue-style-loader'
  })
}
*/

// debug and production
config.plugins = config.plugins.concat([
  new webpack.LoaderOptionsPlugin({
    minimize: true
  }),
  new webpack.DefinePlugin({
    VERSION: JSON.stringify(options.version)
  })
])

if (options.isProduction) {
  // production only
  config.plugins = config.plugins.concat([
    // Set the production environment
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),

    // Minify with dead-code elimination
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ])
}

module.exports = config
<commit_msg>Make sure we don't include Buffer class polyfill.<commit_after>'use strict'

const ExtractTextPlugin = require('extract-text-webpack-plugin')

const merge = require('deep-assign')
const webpack = require('webpack')

const options = require('./options')
const base = require('./webpack.base.js')

const config = merge(base, {
  // without this, webpack throws in a polyfill for node.js's Buffer class
  node: {
    Buffer: false,
    process: false
  },

  entry: options.paths.resolve('src/index.js'),

  output: {
    filename: options.isProduction ? 'vue-grid.min.js' : 'vue-grid.js',
    path: options.paths.output.main,
    library: 'VueGrid',
    libraryExport: 'default',
    libraryTarget: 'umd'
  },

  plugins: [
    new webpack.BannerPlugin({
      banner: options.banner,
      raw: true,
      entryOnly: true
    }),

    new ExtractTextPlugin({
      filename: options.isProduction ? 'vue-grid.min.css' : 'vue-grid.css'
    })
  ]
})

/*
// First item in module.rules array is Vue
config.module.rules[0].options.loaders = {
  scss: ExtractTextPlugin.extract({
    loader: 'css-loader!sass-loader',
    fallbackLoader: 'vue-style-loader'
  })
}
*/

// debug and production
config.plugins = config.plugins.concat([
  new webpack.LoaderOptionsPlugin({
    minimize: true
  }),
  new webpack.DefinePlugin({
    VERSION: JSON.stringify(options.version)
  })
])

if (options.isProduction) {
  // production only
  config.plugins = config.plugins.concat([
    // Set the production environment
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),

    // Minify with dead-code elimination
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      }
    })
  ])
}

module.exports = config
<|endoftext|>


<commit_before>(function() {
  'use strict';
  angular
    .module('polls')
    .controller('PollsListController', PollsListController);

  PollsListController.$inject = ['PollsService', 'PollsApi'];

  function PollsListController(PollsService, PollsApi) {
    var vm = this;
    vm.polls = [];
    loadPolls();
    vm.progressVal = 57;
    vm.progressVal2 = 0;

    function loadPolls() {
      PollsService.query().$promise
      .then(_polls => {
        vm.polls = _polls;
        var promises = [];
        vm.polls.forEach(poll => {
          promises.push(loadPoll(poll));
        });
        return Promise.all(promises);
      })
      .then(res => {
        console.log(res);
        console.log('load done');
      })
      .catch(err => {
        console.log(err);
      });
    }

    function loadPoll(poll) {
      return new Promise((resolve, reject) => {
        loadOpts(poll._id)
        .then(_opts => {
          poll.opts = _opts || [];
          return loadVoteopts(poll._id);
        })
        .then(res => {
          poll.votes = res.votes || [];
          poll.voteopts = res.voteopts || [];
          poll.total =  poll.voteopts;
          poll.opts.forEach(opt => {
            opt.voteCnt = _.where(poll.voteopts, { opt: opt._id }).length || 0;
          });
          return resolve(poll);
        })
        .catch(err => {
          return reject(err);
        });
      });
    }

    function loadOpts(pollID) {
      return new Promise((resolve, reject) => {
        PollsApi.findOpts(pollID)
          .then(res => {
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }

    function loadVoteopts(pollId) {
      return new Promise((resolve, reject) => {
        PollsApi.findVoteopts(poll._id)
        .then(res => {
          return resolve(res.data);
        })
        .catch(err => {
          return reject(err);
        });
      });
    }
  }
})();<commit_msg>Commited from HaNhatLenh at Sun, Jun 25, 2017 11:24:33 AM<commit_after>(function() {
  'use strict';
  angular
    .module('polls')
    .controller('PollsListController', PollsListController);

  PollsListController.$inject = ['PollsService', 'PollsApi'];

  function PollsListController(PollsService, PollsApi) {
    var vm = this;
    vm.polls = [];
    loadPolls();
    vm.progressVal = 57;
    vm.progressVal2 = 0;

    function loadPolls() {
      PollsService.query().$promise
      .then(_polls => {
        vm.polls = _polls;
        var promises = [];
        vm.polls.forEach(poll => {
          promises.push(loadPoll(poll));
        });
        return Promise.all(promises);
      })
      .then(res => {
        console.log(res);
        console.log('load done');
      })
      .catch(err => {
        console.log(err);
      });
    }

    function loadPoll(poll) {
      return new Promise((resolve, reject) => {
        loadOpts(poll._id)
        .then(_opts => {
          poll.opts = _opts || [];
          return loadVoteopts(poll._id);
        })
        .then(res => {
          poll.votes = res.votes || [];
          poll.voteopts = res.voteopts || [];
          poll.total =  poll.voteopts;
          poll.opts.forEach(opt => {
            opt.voteCnt = _.where(poll.voteopts, { opt: opt._id }).length || 0;
          });
          return resolve(poll);
        })
        .catch(err => {
          return reject(err);
        });
      });
    }

    function loadOpts(pollID) {
      return new Promise((resolve, reject) => {
        PollsApi.findOpts(pollID)
          .then(res => {
            return resolve(res.data);
          })
          .catch(err => {
            return reject(err);
          });
      });
    }

    function loadVoteopts(pollId) {
      return new Promise((resolve, reject) => {
        PollsApi.findVoteopts(pollId)
        .then(res => {
          return resolve(res.data);
        })
        .catch(err => {
          return reject(err);
        });
      });
    }
  }
})();<|endoftext|>


<commit_before>/*global define*/
define(function () {

    'use strict';

    return {

        //Line chart
//        chart: {
//            events: {},
//
//            type: 'line', //Tipo di grafico:  area, areaspline, boxplot, bubble, column, line, pie, scatter, spline
//
//            alignTicks: false,
//            backgroundColor: '#FFFFFF', //Colore di background
//            //borderColor: '#3fa8da', //Colore bordo intorno
//            //borderWidth: 1, //Spessore bordo intorno
//            //borderRadius: 0, //Smusso bordo intorno
//            //margin: [5,5,5,5], //Margine intorno (vince sullo spacing)
//            spacing: [20, 1, 1, 1],//Spacing intorno (molto simile al margin - Di default il bottom è 15, qui l'ho messo a 10 per essere uguale agli altri)
//            //plotBackgroundColor: 'red', //Colore di background solo area chart
//            plotBorderColor: '#ffffff', //Colore bordo intorno solo area chart
//            plotBorderWidth: 0, //Spessore bordo intorno solo area chart
//            //showAxes: false, //Mostra gli assi quando le serie sono aggiunte dinamicamente
//            style: {
//                fontFamily: 'Roboto', // Font di tutto
//                fontSize: '12px', // La dimensione qui vale solo per i titoli
//                fontWeight: 300 // Con Roboto è molto bello giocare con i pesi
//            },
//            zoomType: 'xy', //Attiva lo zoom e stabilisce in quale dimensione
//            //selectionMarkerFill: 'rgba(0,0,0,0.25)',//Colore di fonfo della selezione per lo zoom (trasparente per far vedere sotto)
//
//
//
//            resetZoomButton: {
//                position: {
//                    align: 'right', //Allineamento zoom orizzontale
//                    //verticalAlign:'middle' //Allineamento zoom verticale
//                    x: -10 //Posizione del pulsante rispetto all'allineamento (valori positivi > destra) e al PLOT
//
//                },
//                theme: {
//                    fill: '#FFFFFF', //Colore di background pulsante reset zoom
//                    stroke: '#666666', //Colore di stroke pulsante reset zoom
//                    width: 60, //Larghezza del pulsante reset
//                    //r:0, //Smusso pulsante reset zoom
//                    style: {
//                        textAlign: 'center', //CSS style aggiunto da me per centrare il testo
//                        fontSize: 10
//                    },
//                    states: {
//                        hover: {
//                            fill: '#e6e6e6', //Colore di background hover pulsante reset zoom
//                            stroke: '#666666', //Colore di stroke hover pulsante reset zoom
//                            style: {
//                                //color: 'white' //Colore testo hover pulsante reset zoom
//                            }
//                        }
//                    }
//                }
//
//            }
//        },
//        colors: [ //Colori delle charts
//            '#379bcd',
//            '#76BE94',
//            '#744490',
//            '#E10079',
//            '#2D1706',
//            '#F1E300',
//            '#F7AE3C',
//            '#DF3328'
//        ],
//        credits: {
//            enabled: false //Attiva o disattiva il link di HighCharts dalla chart
//        },
//        exporting: {
//            enabled: true
//        },
//        navigation: { //Modifica lo stile dei bottoni e spesso del solo bottone dell'esportazione (lo sfondo)
//            buttonOptions: {
//                theme: {
//                    'stroke-width': 1, // Peso stroke del bottone
//                    stroke: '#666666', // Colore stroke del bottone
//                    r: 0, // Smusso stroke del bottone,
//                    states: {
//                        hover: {
//                            stroke: '#666666', // Press stroke del bottone
//                            fill: '#e6e6e6' // Rollover del bottone
//                        },
//                        select: {
//                            stroke: '#666666', // Press stroke del bottone
//                            fill: '#e6e6e6' // Press Fill del bottone
//                        }
//                    }
//                }
//            }
//        },
//        legend: { //Modifica style della legenda
//            enabled: true, //Attiva la legenda
//            floating: false, // IMPORTANTE - Permette alla plot area di stare sotto alla legenda - si guadagna molto spazio
//
//            //margin: 100, //Margine dell'intero blocco legenda dall'area di PLOT (Solo quando non è floating)
//            //padding: 20, //Padding del box legenda (Ingrandisce il box)
//            backgroundColor: '#FFFFFF', //Colore di sfondo della legenda
//            //layout: 'horizontal', //Tipologia di legenda
//            align: 'center', //Allineamento orizzontale del box della legenda (left, center, right)
//            verticalAlign: 'bottom', //allineamento verticale della legenda (top, middle, bottom)
//            //width: 200, //Larghezza della legenda (Aggiunge Margini e padding)
//            //x: -8,//Offset della posizione della legenda rispetto all'allineamento (valori positivi > destra)
//            //y: -8,//Offset della posizione della legenda rispetto all'allineamento (valori positivi > verso il basso)
//            //maxHeight: 90, //IMPORTANTE - Indica l'altezza massima della legenda, se superata, mostra la paginazione (vedi sotto)
//            //borderColor: '#666666', //Colore del bordo della legenda
//            borderWidth: 0, //Spessore bordo della legenda
//            //borderRadius: 3, //Smusso della legenda
//            //itemDistance: 10, //Distanza X degli elementi quando la legenda è in verticale
//            //symbolWidth: 20, //Larghezza del simbolo rettangolo quando la legenda ne ha uno (accanto al nome - default 16)
//            //symbolHeight: 20, //Altezza del simbolo rettangolo quando la legenda ne ha uno (accanto al nome - default 12)
//            //symbolRadius: 3, //Smusso del simbolo rettangolo quando la legenda ne ha uno (default 2)
//            symbolPadding: 10, //Distanza tra simbolo e legenda (default 5)
//            //itemMarginBottom: 5, //Margine inferiore di ogni elemento della legenda
//            //itemMarginTop: 5, //Margine superiore di ogni elemento della legenda
//            //lineHeight: 20, //Altezza di ogni elemento della legenda (il valore di default è 16)
//            itemStyle: {
//                cursor: 'pointer',
//                color: '#666666',
//                fontSize: '14px',
//                fontWeight: 300
//            },
//            itemHiddenStyle: { //Colore dell'elemento legenda quando è disattivato
//                color: '#eeeeee'
//            },
//            itemHoverStyle: { //Colore dell'elemento legenda in rollover
//                color: '#3ca7da'
//            },
//            navigation: { //Paginazione Legenda - stilizzazione
//                activeColor: '#3ca7da', //Colore freccia attiva legenda
//                inactiveColor: '#666666', //Colore freccia disattiva legenda
//                arrowSize: 8, //Dimensioni freccia
//                animation: true, //Attiva/Disattiva animazione
//                style: { //Stile CSS applicato solo alla navigazione della legenda
//                    color: '#666666',
//                    fontSize: '10px'
//                }
//            }
//        },
///*        plotOptions: {
//            series: {
//                allowPointSelect: true, //Permette di selezionare i punti della chart
//                //pointPlacement: "on", Per partire dall'origine
//                animation: { // Configura l'animazione di entrata
//                    duration: 1000,
//                    easing: 'swing'
//                },
//                connectNulls: true,
//                cropThreshold: 3,
//                lineWidth: 1, // IMPORTANTE - Cambia lo spessore delle linee della chart
//                states: {
//                    hover: {
//                        lineWidth: 1
//                    }
//                },
//                fillColor: {
//                },
//                marker: {
//                    enabled: false, //Attiva o disattiva i marker
//                    //symbol: 'url(http://www.mentaltoy.com/resources/logoChart.png)', //Questo paramentro carica un simbolo personalizzato. Si può anche avere una chart con marker diverse sulle linee
//                    symbol: 'circle', // Tipologia di marker
//                    radius: 4,
//                    lineWidth: 1,
//                    states: {
//                        hover: {
//                            enabled: true, // Attiva o disattiva il marker quando si passa sopra la chart
//                            symbol: 'circle',
//                            radius: 5,
//                            lineWidth: 2
//                        }
//                    }
//                }
//            }
//        },*/
//
//
//        title: {
//            //enabled: false,
//            text: '',
//            x: -20 //center
//        },
//        subtitle: {
//            text: null,
//            x: -20
//        },
//        xAxis: {
//            gridLineWidth: 1, // IMPORTANTE - Attiva le linee verticali
//            lineColor: '#e0e0e0',
//            tickColor: '#e0e0e0',
//            gridLineColor: '#eeeeee',
//            tickLength: 7,
//            //tickmarkPlacement: 'on', Per partire dall'origine
//            labels: {
//                y: 25,
//                style: {
//                    color: '#666666',
//                    fontWeight: '300',
//                    fontSize: 12
//                }
//            },
//            //type: 'datetime',
///*            dateTimeLabelFormats: { // don't display the dummy year
//                //month: '%e. %b',
//                year: '%Y'
//            },*/
//            title: {
//                enabled: false,
//                text: 'null'
//            }
//        },
//        yAxis: {
//            gridLineWidth: 1, // IMPORTANTE - Attiva le linee verticali
//            lineWidth: 1,
//            //tickWidth: 1,
//            lineColor: '#e0e0e0',
//            gridLineColor: '#eeeeee',
//            labels: {
//                style: {
//                    color: '#666666',
//                    fontWeight: '300',
//                    fontSize: 12
//                }
//            },
//            title: {
//                enabled: false,
//                text: 'null'
//            },
//            plotLines: [
//                {
//                    value: 0,
//                    width: 1
//                }
//            ]
//        },
//        tooltip: {
//            //valueSuffix: '',
//           // backgroundColor: 'rgba(255, 255, 255, 0.95)',
//            borderWidth: 1,
//            shadow: true,
//            crosshairs: "mixed",
//           // shared: true
//        }

    };
});<commit_msg>removed require async loading<commit_after>/*global define*/
define(function () {

    'use strict';

    return {

       title: {
           enabled: false,
           text: null
       },
       subtitle: {
           enabled: false
       }

        //Line chart
//        chart: {
//            events: {},
//
//            type: 'line', //Tipo di grafico:  area, areaspline, boxplot, bubble, column, line, pie, scatter, spline
//
//            alignTicks: false,
//            backgroundColor: '#FFFFFF', //Colore di background
//            //borderColor: '#3fa8da', //Colore bordo intorno
//            //borderWidth: 1, //Spessore bordo intorno
//            //borderRadius: 0, //Smusso bordo intorno
//            //margin: [5,5,5,5], //Margine intorno (vince sullo spacing)
//            spacing: [20, 1, 1, 1],//Spacing intorno (molto simile al margin - Di default il bottom è 15, qui l'ho messo a 10 per essere uguale agli altri)
//            //plotBackgroundColor: 'red', //Colore di background solo area chart
//            plotBorderColor: '#ffffff', //Colore bordo intorno solo area chart
//            plotBorderWidth: 0, //Spessore bordo intorno solo area chart
//            //showAxes: false, //Mostra gli assi quando le serie sono aggiunte dinamicamente
//            style: {
//                fontFamily: 'Roboto', // Font di tutto
//                fontSize: '12px', // La dimensione qui vale solo per i titoli
//                fontWeight: 300 // Con Roboto è molto bello giocare con i pesi
//            },
//            zoomType: 'xy', //Attiva lo zoom e stabilisce in quale dimensione
//            //selectionMarkerFill: 'rgba(0,0,0,0.25)',//Colore di fonfo della selezione per lo zoom (trasparente per far vedere sotto)
//
//
//
//            resetZoomButton: {
//                position: {
//                    align: 'right', //Allineamento zoom orizzontale
//                    //verticalAlign:'middle' //Allineamento zoom verticale
//                    x: -10 //Posizione del pulsante rispetto all'allineamento (valori positivi > destra) e al PLOT
//
//                },
//                theme: {
//                    fill: '#FFFFFF', //Colore di background pulsante reset zoom
//                    stroke: '#666666', //Colore di stroke pulsante reset zoom
//                    width: 60, //Larghezza del pulsante reset
//                    //r:0, //Smusso pulsante reset zoom
//                    style: {
//                        textAlign: 'center', //CSS style aggiunto da me per centrare il testo
//                        fontSize: 10
//                    },
//                    states: {
//                        hover: {
//                            fill: '#e6e6e6', //Colore di background hover pulsante reset zoom
//                            stroke: '#666666', //Colore di stroke hover pulsante reset zoom
//                            style: {
//                                //color: 'white' //Colore testo hover pulsante reset zoom
//                            }
//                        }
//                    }
//                }
//
//            }
//        },
//        colors: [ //Colori delle charts
//            '#379bcd',
//            '#76BE94',
//            '#744490',
//            '#E10079',
//            '#2D1706',
//            '#F1E300',
//            '#F7AE3C',
//            '#DF3328'
//        ],
//        credits: {
//            enabled: false //Attiva o disattiva il link di HighCharts dalla chart
//        },
//        exporting: {
//            enabled: true
//        },
//        navigation: { //Modifica lo stile dei bottoni e spesso del solo bottone dell'esportazione (lo sfondo)
//            buttonOptions: {
//                theme: {
//                    'stroke-width': 1, // Peso stroke del bottone
//                    stroke: '#666666', // Colore stroke del bottone
//                    r: 0, // Smusso stroke del bottone,
//                    states: {
//                        hover: {
//                            stroke: '#666666', // Press stroke del bottone
//                            fill: '#e6e6e6' // Rollover del bottone
//                        },
//                        select: {
//                            stroke: '#666666', // Press stroke del bottone
//                            fill: '#e6e6e6' // Press Fill del bottone
//                        }
//                    }
//                }
//            }
//        },
//        legend: { //Modifica style della legenda
//            enabled: true, //Attiva la legenda
//            floating: false, // IMPORTANTE - Permette alla plot area di stare sotto alla legenda - si guadagna molto spazio
//
//            //margin: 100, //Margine dell'intero blocco legenda dall'area di PLOT (Solo quando non è floating)
//            //padding: 20, //Padding del box legenda (Ingrandisce il box)
//            backgroundColor: '#FFFFFF', //Colore di sfondo della legenda
//            //layout: 'horizontal', //Tipologia di legenda
//            align: 'center', //Allineamento orizzontale del box della legenda (left, center, right)
//            verticalAlign: 'bottom', //allineamento verticale della legenda (top, middle, bottom)
//            //width: 200, //Larghezza della legenda (Aggiunge Margini e padding)
//            //x: -8,//Offset della posizione della legenda rispetto all'allineamento (valori positivi > destra)
//            //y: -8,//Offset della posizione della legenda rispetto all'allineamento (valori positivi > verso il basso)
//            //maxHeight: 90, //IMPORTANTE - Indica l'altezza massima della legenda, se superata, mostra la paginazione (vedi sotto)
//            //borderColor: '#666666', //Colore del bordo della legenda
//            borderWidth: 0, //Spessore bordo della legenda
//            //borderRadius: 3, //Smusso della legenda
//            //itemDistance: 10, //Distanza X degli elementi quando la legenda è in verticale
//            //symbolWidth: 20, //Larghezza del simbolo rettangolo quando la legenda ne ha uno (accanto al nome - default 16)
//            //symbolHeight: 20, //Altezza del simbolo rettangolo quando la legenda ne ha uno (accanto al nome - default 12)
//            //symbolRadius: 3, //Smusso del simbolo rettangolo quando la legenda ne ha uno (default 2)
//            symbolPadding: 10, //Distanza tra simbolo e legenda (default 5)
//            //itemMarginBottom: 5, //Margine inferiore di ogni elemento della legenda
//            //itemMarginTop: 5, //Margine superiore di ogni elemento della legenda
//            //lineHeight: 20, //Altezza di ogni elemento della legenda (il valore di default è 16)
//            itemStyle: {
//                cursor: 'pointer',
//                color: '#666666',
//                fontSize: '14px',
//                fontWeight: 300
//            },
//            itemHiddenStyle: { //Colore dell'elemento legenda quando è disattivato
//                color: '#eeeeee'
//            },
//            itemHoverStyle: { //Colore dell'elemento legenda in rollover
//                color: '#3ca7da'
//            },
//            navigation: { //Paginazione Legenda - stilizzazione
//                activeColor: '#3ca7da', //Colore freccia attiva legenda
//                inactiveColor: '#666666', //Colore freccia disattiva legenda
//                arrowSize: 8, //Dimensioni freccia
//                animation: true, //Attiva/Disattiva animazione
//                style: { //Stile CSS applicato solo alla navigazione della legenda
//                    color: '#666666',
//                    fontSize: '10px'
//                }
//            }
//        },
///*        plotOptions: {
//            series: {
//                allowPointSelect: true, //Permette di selezionare i punti della chart
//                //pointPlacement: "on", Per partire dall'origine
//                animation: { // Configura l'animazione di entrata
//                    duration: 1000,
//                    easing: 'swing'
//                },
//                connectNulls: true,
//                cropThreshold: 3,
//                lineWidth: 1, // IMPORTANTE - Cambia lo spessore delle linee della chart
//                states: {
//                    hover: {
//                        lineWidth: 1
//                    }
//                },
//                fillColor: {
//                },
//                marker: {
//                    enabled: false, //Attiva o disattiva i marker
//                    //symbol: 'url(http://www.mentaltoy.com/resources/logoChart.png)', //Questo paramentro carica un simbolo personalizzato. Si può anche avere una chart con marker diverse sulle linee
//                    symbol: 'circle', // Tipologia di marker
//                    radius: 4,
//                    lineWidth: 1,
//                    states: {
//                        hover: {
//                            enabled: true, // Attiva o disattiva il marker quando si passa sopra la chart
//                            symbol: 'circle',
//                            radius: 5,
//                            lineWidth: 2
//                        }
//                    }
//                }
//            }
//        },*/
//
//
//        title: {
//            //enabled: false,
//            text: '',
//            x: -20 //center
//        },
//        subtitle: {
//            text: null,
//            x: -20
//        },
//        xAxis: {
//            gridLineWidth: 1, // IMPORTANTE - Attiva le linee verticali
//            lineColor: '#e0e0e0',
//            tickColor: '#e0e0e0',
//            gridLineColor: '#eeeeee',
//            tickLength: 7,
//            //tickmarkPlacement: 'on', Per partire dall'origine
//            labels: {
//                y: 25,
//                style: {
//                    color: '#666666',
//                    fontWeight: '300',
//                    fontSize: 12
//                }
//            },
//            //type: 'datetime',
///*            dateTimeLabelFormats: { // don't display the dummy year
//                //month: '%e. %b',
//                year: '%Y'
//            },*/
//            title: {
//                enabled: false,
//                text: 'null'
//            }
//        },
//        yAxis: {
//            gridLineWidth: 1, // IMPORTANTE - Attiva le linee verticali
//            lineWidth: 1,
//            //tickWidth: 1,
//            lineColor: '#e0e0e0',
//            gridLineColor: '#eeeeee',
//            labels: {
//                style: {
//                    color: '#666666',
//                    fontWeight: '300',
//                    fontSize: 12
//                }
//            },
//            title: {
//                enabled: false,
//                text: 'null'
//            },
//            plotLines: [
//                {
//                    value: 0,
//                    width: 1
//                }
//            ]
//        },
//        tooltip: {
//            //valueSuffix: '',
//           // backgroundColor: 'rgba(255, 255, 255, 0.95)',
//            borderWidth: 1,
//            shadow: true,
//            crosshairs: "mixed",
//           // shared: true
//        }

    };
});<|endoftext|>


<commit_before>/**
 * Util method to get effect
 */
import {checkStatus} from './customEvent'

const makeProxy = (e) => {
  const proxy = {}
  for (const key in e) {
    if (typeof e[key] === 'function') {
      proxy[key] = e[key].bind(e)
    } else {
      proxy[key] = e[key]
    }
  }
  return proxy
}

const bodyListener = function (callback, options, e) {
  const {respectEffect = false, customEvent = false} = options
  const {id} = this.props

  const tip = e.target.getAttribute('data-tip') || null
  const forId = e.target.getAttribute('data-for') || null

  const target = e.target
  if (this.isCustomEvent(target) && !customEvent) {
    return
  }

  const isTargetBelongsToTooltip =
    (id == null && forId == null) || forId === id

  if (tip != null &&
    (!respectEffect || this.getEffect(target) === 'float') &&
    isTargetBelongsToTooltip
  ) {
    const proxy = makeProxy(e)
    proxy.currentTarget = target
    callback(proxy)
  }
}

const findCustomEvents = (targetArray, dataAttribute) => {
  const events = {}
  targetArray.forEach(target => {
    const event = target.getAttribute(dataAttribute)
    if (event) event.split(' ').forEach(event => events[event] = true)
  })

  return events
}

const getBody = () => document.getElementsByTagName('body')[0]

export default function (target) {
  target.prototype.isBodyMode = function () {
    return !!this.props.bodyMode
  }

  target.prototype.bindBodyListener = function (targetArray) {
    const {event, eventOff, possibleCustomEvents,
      possibleCustomEventsOff} = this.state
    const body = getBody()

    const customEvents = findCustomEvents(targetArray, 'data-event')
    const customEventsOff = findCustomEvents(targetArray, 'data-event-off')

    if (event != null) customEvents[event] = true
    if (eventOff != null) customEventsOff[eventOff] = true
    possibleCustomEvents.split(' ').forEach(event => customEvents[event] = true)
    possibleCustomEventsOff.split(' ').forEach(event => customEventsOff[event] = true)

    this.unbindBodyListener(body)

    const listeners = this.bodyModeListeners = {}
    if (event == null) {
      listeners.mouseover = bodyListener.bind(this, this.showTooltip, {})
      listeners.mousemove = bodyListener.bind(this, this.updateTooltip, { respectEffect: true })
      listeners.mouseout = bodyListener.bind(this, this.hideTooltip, {})
    }

    for (const event in customEvents) {
      listeners[event] = bodyListener.bind(this, (e) => {
        const targetEventOff = e.currentTarget.getAttribute('data-event-off') || eventOff
        checkStatus.call(this, targetEventOff, e)
      }, { customEvent: true })
    }
    for (const event in customEventsOff) {
      listeners[event] = bodyListener.bind(this, this.hideTooltip, { customEvent: true })
    }
    for (const event in listeners) {
      body.addEventListener(event, listeners[event])
    }
  }

  target.prototype.unbindBodyListener = function (body) {
    body = body || getBody()

    const listeners = this.bodyModeListeners
    for (const event in listeners) {
      body.removeEventListener(event, listeners(event))
    }
  }
}
<commit_msg>Fix invalid parentheses<commit_after>/**
 * Util method to get effect
 */
import {checkStatus} from './customEvent'

const makeProxy = (e) => {
  const proxy = {}
  for (const key in e) {
    if (typeof e[key] === 'function') {
      proxy[key] = e[key].bind(e)
    } else {
      proxy[key] = e[key]
    }
  }
  return proxy
}

const bodyListener = function (callback, options, e) {
  const {respectEffect = false, customEvent = false} = options
  const {id} = this.props

  const tip = e.target.getAttribute('data-tip') || null
  const forId = e.target.getAttribute('data-for') || null

  const target = e.target
  if (this.isCustomEvent(target) && !customEvent) {
    return
  }

  const isTargetBelongsToTooltip =
    (id == null && forId == null) || forId === id

  if (tip != null &&
    (!respectEffect || this.getEffect(target) === 'float') &&
    isTargetBelongsToTooltip
  ) {
    const proxy = makeProxy(e)
    proxy.currentTarget = target
    callback(proxy)
  }
}

const findCustomEvents = (targetArray, dataAttribute) => {
  const events = {}
  targetArray.forEach(target => {
    const event = target.getAttribute(dataAttribute)
    if (event) event.split(' ').forEach(event => events[event] = true)
  })

  return events
}

const getBody = () => document.getElementsByTagName('body')[0]

export default function (target) {
  target.prototype.isBodyMode = function () {
    return !!this.props.bodyMode
  }

  target.prototype.bindBodyListener = function (targetArray) {
    const {event, eventOff, possibleCustomEvents,
      possibleCustomEventsOff} = this.state
    const body = getBody()

    const customEvents = findCustomEvents(targetArray, 'data-event')
    const customEventsOff = findCustomEvents(targetArray, 'data-event-off')

    if (event != null) customEvents[event] = true
    if (eventOff != null) customEventsOff[eventOff] = true
    possibleCustomEvents.split(' ').forEach(event => customEvents[event] = true)
    possibleCustomEventsOff.split(' ').forEach(event => customEventsOff[event] = true)

    this.unbindBodyListener(body)

    const listeners = this.bodyModeListeners = {}
    if (event == null) {
      listeners.mouseover = bodyListener.bind(this, this.showTooltip, {})
      listeners.mousemove = bodyListener.bind(this, this.updateTooltip, { respectEffect: true })
      listeners.mouseout = bodyListener.bind(this, this.hideTooltip, {})
    }

    for (const event in customEvents) {
      listeners[event] = bodyListener.bind(this, (e) => {
        const targetEventOff = e.currentTarget.getAttribute('data-event-off') || eventOff
        checkStatus.call(this, targetEventOff, e)
      }, { customEvent: true })
    }
    for (const event in customEventsOff) {
      listeners[event] = bodyListener.bind(this, this.hideTooltip, { customEvent: true })
    }
    for (const event in listeners) {
      body.addEventListener(event, listeners[event])
    }
  }

  target.prototype.unbindBodyListener = function (body) {
    body = body || getBody()

    const listeners = this.bodyModeListeners
    for (const event in listeners) {
      body.removeEventListener(event, listeners[event])
    }
  }
}
<|endoftext|>