<commit_before>Ranger.defaults = {
  min: 0,
  max: 100,
  valueFormat: function(a) {return a;},
  valueParse: function(a) {return a;},
  maxRanges: Infinity
};

function Ranger(options) {
  var $base = $('
');
  options = $.extend({}, Ranger.defaults, options);
  options.min = options.valueParse(options.min);
  options.max = options.valueParse(options.max);

  function normaliseRaw(value) {
    return options.min + value * (options.max - options.min);
  }

  $base.normalise = function (value) {
    return options.valueFormat(normaliseRaw(value));
  };

  function abnormaliseRaw(value) {
    return (value - options.min)/(options.max - options.min);
  }

  $base.abnormalise = function (value) {
    return abnormaliseRaw(options.valueParse(value));
  };

  $base.ranges = [];

  $base.addRange = function(range, index) {
    $range = Range({
      value: range,
      parent: $base,
      snap: options.snap ? abnormaliseRaw(options.snap + options.min) : null,
      label: options.label
    });
    $base.ranges.push($range);
    $base.append($range);
    $range.on('changing', function(ev, n$range) {
      ev.stopPropagation();
      $base.trigger('changing', [$base.val()]);
    }).on('change', function(ev, nrange) {
      ev.stopPropagation();
      $base.trigger('change', [$base.val()]);
    });
    return $range;
  };

  $base.val = function(ranges) {
    if(typeof ranges === 'undefined') {
      return $base.ranges.map(function(range) {
        return range.val().map($base.normalise);
      });
    }

    if($base.ranges.length > ranges.length) {
      for(var i = ranges.length, l = $base.ranges.length; i < l; ++i) {
        $base.ranges[i].remove();
      }
      $base.ranges.length = ranges.length;
    }

    ranges.forEach(function(range, i) {
      if($base.ranges[i]) {
        $base.ranges[i].val(range.map($base.abnormalise));
      } else {
        $base.addRange(range.map($base.abnormalise));
      }
    });

    return this;
  };

  $base.on('click', function(ev) {
    if(ev.target === ev.currentTarget && $base.ranges.length < options.maxRanges) {
      var mid = ev.pageX - $base.offset().left;
      var left = (mid - $base.width() / 25) / $base.width();
      var right = (mid + $base.width() / 25) / $base.width();

      $base.addRange([left, right]);
    }
  });

  if(options.values) $base.val(options.values);

  return $base;
}

function Range(options) {
  var $el = $('
')
    .append('
')
    .append('')
    .append('
');

  if(typeof options.label === 'function') {
    $el.on('changing', function(ev, range) {
      $el.find('.barlabel').text(options.label.call($el,range.map(options.parent.normalise)));
    });
  } else {
    $el.find('.barlabel').text(options.label);
  }

  $el.val = function(range) {
    if(typeof range === 'undefined') {
      return $el.range;
    }
    var a;

    if(options.snap) {
      range = range.map(function(val) {
        return Math.round(val / options.snap) * options.snap;
      });
    }
    $el.range = range;
    $el.trigger('changing', [range]);
    $el.css({
      left: 100*range[0] + '%',
      minWidth: 100*(range[1] - range[0]) + '%'
    });

    return $el;

    function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
  };

  if(options.value) $el.val(options.value);

  $el.on('mousedown', function(ev) {
    if ($(ev.target).is('.handle:first-child')) {
      $('body').addClass('resizing');
      $(document).on('mousemove',resizeLeft);
    } else if ($(ev.target).is('.handle:last-child')) {
      $('body').addClass('resizing');
      $(document).on('mousemove',resizeRight);
    } else {
      $('body').addClass('dragging');
      $(document).on('mousemove',drag);
    }

    var startLeft = $el.offset().left,
        startPosLeft = $el.position().left,
        mouseOffset = ev.clientX ? ev.clientX - $el.offset().left : 0,
        startWidth = $el.width(),
        parent = options.parent,
        parentOffset = parent.offset(),
        parentWidth = parent.width();

    var nextLeft, prevRight;

    $el.siblings('.bar').each(function() {
      var $this = $(this), off = $this.offset(), width = $this.width();
      if(off.left >= startLeft + startWidth) { // to the right of current bar
        if(!nextLeft || off.left <= nextLeft) { // no next or closer to current than next
          nextLeft = off.left;
        }
      }
      if(off.left + width <= startLeft) { // to the left of current bar
        if(!prevRight || off.left + width >= prevRight) { // no prev or closer to current than prev
          prevRight = off.left + width;
        }
      }
    });

    var drawing = false;

    $(document).on('mouseup', function() {
      $el.trigger('change', [$el.range]);
      $(this).off('mouseup mousemove');
      $('body').removeClass('resizing dragging');
    });

    function resizeRight(ev) {
      var width = ev.clientX - startLeft;

      if (drawing) return;
      if (width > parentWidth - startPosLeft) width = parentWidth - startPosLeft;
      if (nextLeft && startLeft + width >= nextLeft) width = nextLeft - startLeft;
      if (width >= 10) {
        requestAnimationFrame(function() {
          drawing = false;
          var right = width / parentWidth;
          $el.val([$el.range[0], $el.range[0] + right]);
        });
        drawing = true;
      } else {
        $(document).trigger('mouseup');
        $el.find('.handle:first-child').trigger('mousedown');
      }
    }

    function drag(ev) {
      var left = ev.clientX - parentOffset.left - mouseOffset;

      if (drawing) return;
      if (nextLeft && left + startWidth >= nextLeft) left = nextLeft - startWidth;
      if (prevRight && left <= prevRight) left = prevRight;
      if (left >= 0 && left <= parentWidth - $el.width()) {
        requestAnimationFrame(function() {
          drawing = false;
          var rangeOffset = left / parentWidth - $el.range[0];
          $el.val([left / parentWidth, $el.range[1] + rangeOffset]);
        });
        drawing = true;
      } else {
        mouseOffset = ev.clientX - $el.offset().left;
      }
    }

    function resizeLeft(ev) {
      var left = ev.clientX - parentOffset.left - mouseOffset;
      var width = startPosLeft + startWidth - left;

      if (drawing) return;
      if (left < 0) {
        left = 0;
        width = startPosLeft + startWidth;
      }
      if (prevRight && left <= prevRight) {
        left = prevRight;
        width = startPosLeft + startWidth - left;
      }
      if (width >= 10) {
        requestAnimationFrame(function() {
          drawing = false;
          var lRel = left / parentWidth;
          $el.val([lRel, $el.range[1]]);
        });
        drawing = true;
      } else {
        $(document).trigger('mouseup');
        $el.find('.handle:last-child').trigger('mousedown');
      }
    }
  });

  return $el;
}<commit_msg>move requestanimationframe to actual drawing<commit_after>Ranger.defaults = {
  min: 0,
  max: 100,
  valueFormat: function(a) {return a;},
  valueParse: function(a) {return a;},
  maxRanges: Infinity
};

function Ranger(options) {
  var $base = $('
');
  options = $.extend({}, Ranger.defaults, options);
  options.min = options.valueParse(options.min);
  options.max = options.valueParse(options.max);

  function normaliseRaw(value) {
    return options.min + value * (options.max - options.min);
  }

  $base.normalise = function (value) {
    return options.valueFormat(normaliseRaw(value));
  };

  function abnormaliseRaw(value) {
    return (value - options.min)/(options.max - options.min);
  }

  $base.abnormalise = function (value) {
    return abnormaliseRaw(options.valueParse(value));
  };

  $base.ranges = [];

  $base.addRange = function(range, index) {
    $range = Range({
      value: range,
      parent: $base,
      snap: options.snap ? abnormaliseRaw(options.snap + options.min) : null,
      label: options.label
    });
    $base.ranges.push($range);
    $base.append($range);
    $range.on('changing', function(ev, n$range) {
      ev.stopPropagation();
      $base.trigger('changing', [$base.val()]);
    }).on('change', function(ev, nrange) {
      ev.stopPropagation();
      $base.trigger('change', [$base.val()]);
    });
    return $range;
  };

  $base.val = function(ranges) {
    if(typeof ranges === 'undefined') {
      return $base.ranges.map(function(range) {
        return range.val().map($base.normalise);
      });
    }

    if($base.ranges.length > ranges.length) {
      for(var i = ranges.length, l = $base.ranges.length; i < l; ++i) {
        $base.ranges[i].remove();
      }
      $base.ranges.length = ranges.length;
    }

    ranges.forEach(function(range, i) {
      if($base.ranges[i]) {
        $base.ranges[i].val(range.map($base.abnormalise));
      } else {
        $base.addRange(range.map($base.abnormalise));
      }
    });

    return this;
  };

  $base.on('click', function(ev) {
    if(ev.target === ev.currentTarget && $base.ranges.length < options.maxRanges) {
      var mid = ev.pageX - $base.offset().left;
      var left = (mid - $base.width() / 25) / $base.width();
      var right = (mid + $base.width() / 25) / $base.width();

      $base.addRange([left, right]);
    }
  });

  if(options.values) $base.val(options.values);

  return $base;
}

function Range(options) {
  var $el = $('
')
    .append('
')
    .append('')
    .append('
');

  if(typeof options.label === 'function') {
    $el.on('changing', function(ev, range) {
      $el.find('.barlabel').text(options.label.call($el,range.map(options.parent.normalise)));
    });
  } else {
    $el.find('.barlabel').text(options.label);
  }

  var drawing = false;

  $el.val = function(range) {
    if(typeof range === 'undefined') {
      return $el.range;
    }
    var a;

    if(options.snap) {
      range = range.map(function(val) {
        return Math.round(val / options.snap) * options.snap;
      });
    }
    $el.range = range;
    $el.trigger('changing', [range]);
    requestAnimationFrame(function() {
      drawing = false;
      $el.css({
        left: 100*range[0] + '%',
        minWidth: 100*(range[1] - range[0]) + '%'
      });
    });
    drawing = true;

    return $el;

    function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
  };

  if(options.value) $el.val(options.value);

  $el.on('mousedown', function(ev) {
    if ($(ev.target).is('.handle:first-child')) {
      $('body').addClass('resizing');
      $(document).on('mousemove',resizeLeft);
    } else if ($(ev.target).is('.handle:last-child')) {
      $('body').addClass('resizing');
      $(document).on('mousemove',resizeRight);
    } else {
      $('body').addClass('dragging');
      $(document).on('mousemove',drag);
    }

    var startLeft = $el.offset().left,
        startPosLeft = $el.position().left,
        mouseOffset = ev.clientX ? ev.clientX - $el.offset().left : 0,
        startWidth = $el.width(),
        parent = options.parent,
        parentOffset = parent.offset(),
        parentWidth = parent.width();

    var nextLeft, prevRight;

    $el.siblings('.bar').each(function() {
      var $this = $(this), off = $this.offset(), width = $this.width();
      if(off.left >= startLeft + startWidth) { // to the right of current bar
        if(!nextLeft || off.left <= nextLeft) { // no next or closer to current than next
          nextLeft = off.left;
        }
      }
      if(off.left + width <= startLeft) { // to the left of current bar
        if(!prevRight || off.left + width >= prevRight) { // no prev or closer to current than prev
          prevRight = off.left + width;
        }
      }
    });

    $(document).on('mouseup', function() {
      $el.trigger('change', [$el.range]);
      $(this).off('mouseup mousemove');
      $('body').removeClass('resizing dragging');
    });

    function resizeRight(ev) {
      var width = ev.clientX - startLeft;

      if (drawing) return;
      if (width > parentWidth - startPosLeft) width = parentWidth - startPosLeft;
      if (nextLeft && startLeft + width >= nextLeft) width = nextLeft - startLeft;
      if (width >= 10) {
        var right = width / parentWidth;
        $el.val([$el.range[0], $el.range[0] + right]);
      } else {
        $(document).trigger('mouseup');
        $el.find('.handle:first-child').trigger('mousedown');
      }
    }

    function drag(ev) {
      var left = ev.clientX - parentOffset.left - mouseOffset;

      if (drawing) return;
      if (nextLeft && left + startWidth >= nextLeft) left = nextLeft - startWidth;
      if (prevRight && left <= prevRight) left = prevRight;
      if (left >= 0 && left <= parentWidth - $el.width()) {
        var rangeOffset = left / parentWidth - $el.range[0];
        $el.val([left / parentWidth, $el.range[1] + rangeOffset]);
      } else {
        mouseOffset = ev.clientX - $el.offset().left;
      }
    }

    function resizeLeft(ev) {
      var left = ev.clientX - parentOffset.left - mouseOffset;
      var width = startPosLeft + startWidth - left;

      if (drawing) return;
      if (left < 0) {
        left = 0;
        width = startPosLeft + startWidth;
      }
      if (prevRight && left <= prevRight) {
        left = prevRight;
        width = startPosLeft + startWidth - left;
      }
      if (width >= 10) {
        var lRel = left / parentWidth;
        $el.val([lRel, $el.range[1]]);
      } else {
        $(document).trigger('mouseup');
        $el.find('.handle:last-child').trigger('mousedown');
      }
    }
  });

  return $el;
}<|endoftext|>


<commit_before>require.config(
    {
        waitSeconds: 15,
        paths: {
            jquery: 'https://code.jquery.com/jquery-1.11.1.min',
            jqueryui: 'https://code.jquery.com/ui/1.10.4/jquery-ui.min',
            bootstrap: 'https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min',
            jsyaml: 'https://nodeca.github.io/js-yaml/js/js-yaml',
            marked: 'lib/marked',
            tocify: 'https://cdn.rawgit.com/gfranko/jquery.tocify.js/master/src/javascripts/jquery.tocify.min',
            fileSaver: 'https://cdn.jsdelivr.net/filesaver.js/0.1/FileSaver.min',
            mustache: 'https://cdn.jsdelivr.net/mustache.js/0.8.1/mustache.min',
            citeproc: 'lib/citeproc',
            xmldom: 'lib/xmldom',
            xmle4x: 'lib/xmle4x',
            linkify: 'https://soapbox.github.io/jQuery-linkify/dist/jquery.linkify.min'
        },
        shim: {
            bootstrap: { deps: ['jquery'] },
            powertip: { deps: ['jquery'] },
            linkify: { deps: ['jquery'] },
            tocify: { deps: ['jquery', 'jqueryui'] },
            citeproc: { deps: ['xmldom'] }
        }
    }
)

require(['jquery', 'jsyaml', 'marked', 'mustache', 'citations', 'config', 'fileSaver', 'tocify' ], function ($, yaml, marked, mustache, citations, config) {

    var getDocumentIDByName = function (doc) {
        return doc.replace(/(\.| )/g, '_');
    }

    function fixTOCIdentifiers() {

        var source = $("html");
        source.find(".tocify-item a").each(function () {
            var tthis = $(this);
            tthis.attr("href", '#' + tthis.parent().data("unique"))
        })
        source.find("div[data-unique]").each(function () {
            var tthis = $(this);
            tthis.attr("id", tthis.data("unique"))
        })
    }

    function saveAsPrintableHtml() {

        var source = $("html");
        var blob = new Blob(['' + source.html() + ''], {type: "text/html;charset=utf-8"});
        saveAs(blob, "printable.html");
    }

    var $head = $('head');
    $head.append('<title>' + config.title + '</title>')
    $head.append('<meta name="keywords" content="' + config.keywords + '"/>')
    $head.append('<meta name="author" content="' + config.author + '"/>')
    $head.append('<meta name="subject" content="' + config.subject + '"/>')
    $head.append('<meta name="organisation" content="' + config.organisation.name + '"/>')
    $head.append('<meta charset="' + config.charset + '"/>')
    $head.attr('lang', config.language);

    Object.keys(config.structure).forEach(function (section) {
        config.structure[section].forEach(function (doc) {
            $.ajax({
                url: config.source_dir + '/' + doc,
                dataType: 'text',
                async: false,
                success: function (result) {
                    var doc_id = getDocumentIDByName(doc);
                    var html = $(mustache.render(marked(result), config));
                    var container = $('

').append(html);
                    $('#content').append(container);
                },
                error: function (e) {
                    console.log("failed to load " + doc, e);
                }
            });
        })
    })

    console.log('word-count: ' + $(".main").text().split(/\s+/).length)

    var level_1 = level_2 = level_3 = level_4 = level_5 = 0;
    $(".main").find("h1,h2,h3,h4,h5").each(function (index) {
        var tag = this.tagName.toLowerCase();
        var $this = $(this);
        $this.html(function (index, content) {

            if (tag == 'h1') {
                content = '' + ++level_1 + '\n' + content;
                level_2 = level_3 = level_4 = level_5 = 0;
            }
            if (tag == 'h2') {
                content = '' + level_1 + "." + ++level_2 + '\n' + content;
                level_3 = level_4 = level_5 = 0;
            }
            if (tag == 'h3') {
                content = '' + level_1 + "." + level_2 + "." + ++level_3 + '\n' + content;
                level_4 = level_5 = 0;
            }
            if (tag == 'h4') {
                content = '' + level_1 + "." + level_2 + "." + level_3 + "." + ++level_4 + '\n' + content;
                level_5 = 0;
            }
            if (tag == 'h5') {
                content = '' + level_1 + "." + level_2 + "." + level_3 + "." + level_4 + "." + ++level_5 + '\n' + content;
            }
            return content;
        })
    })
    $("#toc_md").tocify({ context: "#content", theme: "bootstrap3", scrollHistory: false, ignoreSelector: "#acknowledgements_md>,#dedication_md>,#declarations_md>,#toc_md h1,.cover h1"});
    $("table").addClass("table table-bordered table-hover table-condensed");
    $("p:empty").remove();
    fixTOCIdentifiers();
//    saveAsPrintableHtml();
});<commit_msg>added automatic figure and table numbering<commit_after>require.config(
    {
        waitSeconds: 15,
        paths: {
            jquery: 'https://code.jquery.com/jquery-1.11.1.min',
            jqueryui: 'https://code.jquery.com/ui/1.10.4/jquery-ui.min',
            bootstrap: 'https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min',
            jsyaml: 'https://nodeca.github.io/js-yaml/js/js-yaml',
            marked: 'lib/marked',
            tocify: 'https://cdn.rawgit.com/gfranko/jquery.tocify.js/master/src/javascripts/jquery.tocify.min',
            fileSaver: 'https://cdn.jsdelivr.net/filesaver.js/0.1/FileSaver.min',
            mustache: 'https://cdn.jsdelivr.net/mustache.js/0.8.1/mustache.min',
            citeproc: 'lib/citeproc',
            xmldom: 'lib/xmldom',
            xmle4x: 'lib/xmle4x',
            linkify: 'https://soapbox.github.io/jQuery-linkify/dist/jquery.linkify.min'
        },
        shim: {
            bootstrap: { deps: ['jquery'] },
            powertip: { deps: ['jquery'] },
            linkify: { deps: ['jquery'] },
            tocify: { deps: ['jquery', 'jqueryui'] },
            citeproc: { deps: ['xmldom'] }
        }
    }
)

require(['jquery', 'jsyaml', 'marked', 'mustache', 'citations', 'config', 'fileSaver', 'tocify' ], function ($, yaml, marked, mustache, citations, config) {

    var getDocumentIDByName = function (doc) {
        return doc.replace(/(\.| )/g, '_');
    }

    function fixTOCIdentifiers() {

        var source = $("html");
        source.find(".tocify-item a").each(function () {
            var tthis = $(this);
            tthis.attr("href", '#' + tthis.parent().data("unique"))
        })
        source.find("div[data-unique]").each(function () {
            var tthis = $(this);
            tthis.attr("id", tthis.data("unique"))
        })
    }

    function saveAsPrintableHtml() {

        var source = $("html");
        var blob = new Blob(['' + source.html() + ''], {type: "text/html;charset=utf-8"});
        saveAs(blob, "printable.html");
    }

    var $head = $('head');
    $head.append('<title>' + config.title + '</title>')
    $head.append('<meta name="keywords" content="' + config.keywords + '"/>')
    $head.append('<meta name="author" content="' + config.author + '"/>')
    $head.append('<meta name="subject" content="' + config.subject + '"/>')
    $head.append('<meta name="organisation" content="' + config.organisation.name + '"/>')
    $head.append('<meta charset="' + config.charset + '"/>')
    $head.attr('lang', config.language);

    Object.keys(config.structure).forEach(function (section) {
        config.structure[section].forEach(function (doc) {
            $.ajax({
                url: config.source_dir + '/' + doc,
                dataType: 'text',
                async: false,
                success: function (result) {
                    var doc_id = getDocumentIDByName(doc);
                    var html = $(mustache.render(marked(result), config));
                    var container = $('

').append(html);
                    $('#content').append(container);
                },
                error: function (e) {
                    console.log("failed to load " + doc, e);
                }
            });
        })
    })

    console.log('word-count: ' + $(".main").text().split(/\s+/).length)

    var level_1 = level_2 = level_3 = level_4 = level_5 = figcaption = tablecaption = 0;
    $(".main").find("h1,h2,h3,h4,h5,figcaption,table>caption").each(function (index) {
        var tag = this.tagName.toLowerCase();
        var $this = $(this);
        $this.html(function (index, content) {

            if (tag == 'h1') {
                content = '' + ++level_1 + '\n' + content;
                level_2 = level_3 = level_4 = level_5 = figcaption = tablecaption = 0;
            }
            if (tag == 'h2') {
                content = '' + level_1 + "." + ++level_2 + '\n' + content;
                level_3 = level_4 = level_5 = 0;
            }
            if (tag == 'h3') {
                content = '' + level_1 + "." + level_2 + "." + ++level_3 + '\n' + content;
                level_4 = level_5 = 0;
            }
            if (tag == 'h4') {
                content = '' + level_1 + "." + level_2 + "." + level_3 + "." + ++level_4 + '\n' + content;
                level_5 = 0;
            }
            if (tag == 'h5') {
                content = '' + level_1 + "." + level_2 + "." + level_3 + "." + level_4 + "." + ++level_5 + '\n' + content;
            }

            if (tag == 'figcaption') {
                content = 'Figure ' + level_1 + "." + ++figcaption + '' + content;
            }

            if (tag == 'caption') {
                content = 'Table ' + level_1 + "." + ++tablecaption + '' + content;
            }
            return content;
        })
    })
    $("#toc_md").tocify({ context: "#content", theme: "bootstrap3", scrollHistory: false, ignoreSelector: "#acknowledgements_md>,#dedication_md>,#declarations_md>,#toc_md h1,.cover h1"});
    $("table").addClass("table table-bordered table-hover table-condensed");
    $("p:empty").remove();
    fixTOCIdentifiers();
//    saveAsPrintableHtml();
});<|endoftext|>


<commit_before>/* =============================================================

    Drop v1.3
    Simple, progressively enhanced dropdown menus by Chris Ferdinandi.
    http://gomakethings.com

    Free to use under the MIT License.
    http://gomakethings.com/mit/

 * ============================================================= */

(function($) {
    $(function () {
        // Close dropdown menus when you click outside of them
        $('body').click(function(){
          $('.dropdown > a').removeClass('active'); // Remove any '.active' classes from dropdown links
          $('.dropdown').removeClass('active'); // Remove any '.active' classes from dropdown list items
          $('.dropdown-menu').removeClass('active'); // Hide any visible dropdown menus
        });

        // When a dropdown menu link is clicked
        $('.dropdown > a').click(function(e) {
            e.stopPropagation(); // Stop the "close all dropdowns" function
            e.preventDefault(); // Prevent the default link action
            $(this).toggleClass('active').next($('.dropdown-menu')).toggleClass('active'); // If the dropdown menu is hidden, show it. Otherwise, hide it.
            $(this).parent('.dropdown').toggleClass('active'); // Add/remove '.active' class to the dropdown list item
            $(this).parent().siblings('.dropdown').removeClass('active').children('a').removeClass('active').next($('.dropdown-menu')).removeClass('active'); // Hide all other dropdown menus
        });

        // When click inside a dropdown menu
        $('.dropdown-menu').click(function(e) {
            e.stopPropagation(); // Stop the "close all dropdowns" function
        });
    });
})(jQuery);

/* =============================================================

    Progressively Enhanced JS v1.0
    Adds .js class to <body> for progressive enhancement.

    Script by Chris Ferdinandi.
    http://gomakethings.com

    Licensed under WTFPL.
    http://www.wtfpl.net

 * ============================================================= */

(function($) {
    $(function () {
        $('body').addClass('js'); // On page load, add the .js class to the <body> element.
    });
})(jQuery);
<commit_msg>Switched to the MIT License<commit_after>/* =============================================================

    Drop v1.3
    Simple, progressively enhanced dropdown menus by Chris Ferdinandi.
    http://gomakethings.com

    Free to use under the MIT License.
    http://gomakethings.com/mit/

 * ============================================================= */

(function($) {
    $(function () {
        // Close dropdown menus when you click outside of them
        $('body').click(function(){
          $('.dropdown > a').removeClass('active'); // Remove any '.active' classes from dropdown links
          $('.dropdown').removeClass('active'); // Remove any '.active' classes from dropdown list items
          $('.dropdown-menu').removeClass('active'); // Hide any visible dropdown menus
        });

        // When a dropdown menu link is clicked
        $('.dropdown > a').click(function(e) {
            e.stopPropagation(); // Stop the "close all dropdowns" function
            e.preventDefault(); // Prevent the default link action
            $(this).toggleClass('active').next($('.dropdown-menu')).toggleClass('active'); // If the dropdown menu is hidden, show it. Otherwise, hide it.
            $(this).parent('.dropdown').toggleClass('active'); // Add/remove '.active' class to the dropdown list item
            $(this).parent().siblings('.dropdown').removeClass('active').children('a').removeClass('active').next($('.dropdown-menu')).removeClass('active'); // Hide all other dropdown menus
        });

        // When click inside a dropdown menu
        $('.dropdown-menu').click(function(e) {
            e.stopPropagation(); // Stop the "close all dropdowns" function
        });
    });
})(jQuery);

/* =============================================================

    Progressively Enhanced JS v1.0
    Adds .js class to <body> for progressive enhancement.

    Script by Chris Ferdinandi.
    http://gomakethings.com

    Free to use under the MIT License.
    http://gomakethings.com/mit/

 * ============================================================= */

(function($) {
    $(function () {
        $('body').addClass('js'); // On page load, add the .js class to the <body> element.
    });
})(jQuery);
<|endoftext|>


<commit_before>require([
  '$api/models',
  '$views/list#List',
  '$views/throbber#Throbber',
  'scripts/vendor/jquery-2.0.3.min',
  'scripts/vendor/underscore-min#_',
  'scripts/blog_track_list'
], function(models, List, Throbber, jQuery, _, blog_track_list) {
  'use strict';

  // blogs
  var blogNames = [
    'seejohnrun.tumblr.com', 'magerleagues.tumblr.com', 'strle.tumblr.com'
  ];

  $(function () {

    // Load templates
    var $container = $('#container');
    var bcTemplate = _.template($('#blog-card-template').html());
    var blogsTemplate = _.template($('#blogs-template').html());
    var blogTemplate = _.template($('#blog-template').html());
    var blogHeaderTemplate = _.template($('#blog-header-template').html());

    // Handle new requests
    var start = function (args) {
      $container.html('');
      if (args.length > 0 && args[0] === 'blogName') {
        loadBlog(args[1]);
      } else {
        loadBlogDirectory();
      }
    };

    // Load all pages
    var loadBlogDirectory = function () {
      // Load the template
      $container.html(blogsTemplate());
      var $blogs = $container.find('.blogs');
      var throbber = Throbber.forElement($blogs[0]);
      // Add each of the friends as a link
      blog_track_list.loadFriends(blogNames, function (blogs) {
        blogs.forEach(function (blogDetail) {
          blogDetail.avatar64 = 'http://api.tumblr.com/v2/blog/' + blogDetail.name + '.tumblr.com/avatar/64';
          $blogs.append(bcTemplate(blogDetail));
        });
        throbber.hide();
      });
    };

    var loadBlog = function (blogName) {

      $container.html(blogTemplate());
      var $blog = $container.find('#blog');
      var blogThrobber = Throbber.forElement($blog[0]);

      blog_track_list.trackListing(blogName, function (blog, uris) {

        uris = _.compact(uris);

        blogThrobber.hide();
        if (uris.length === 0) { return; }

        // Load up detail about this person
        blog.avatar128 = 'http://api.tumblr.com/v2/blog/' + blog.name + '.tumblr.com/avatar/128';
        $blog.append(blogHeaderTemplate(blog));

        // Make an OTF playlist
        var tempName = 'tumblr:' + blog.name + ':' + new Date().getTime().toString();
        models.Playlist.createTemporary(tempName).done(function (playlist) {

          // Add the tracks to the playlist
          playlist.load('tracks');
          playlist.tracks.add(models.Track.fromURIs(uris)).done(function () {

            // And put it in a list
            var list = new List.forPlaylist(playlist);
            $blog.append(list.node);
            list.init(); // TODO not sure what this does

          });

        });

      });

    };

    // Hook into load and update
    models.application.load('arguments').done(function (app) { start(app.arguments); });
    models.application.addEventListener('arguments', function (e) {
      start(e.data.arguments);
    });

  });

});
<commit_msg>Added a few more blogs<commit_after>require([
  '$api/models',
  '$views/list#List',
  '$views/throbber#Throbber',
  'scripts/vendor/jquery-2.0.3.min',
  'scripts/vendor/underscore-min#_',
  'scripts/blog_track_list'
], function(models, List, Throbber, jQuery, _, blog_track_list) {
  'use strict';

  // blogs
  var blogNames = [
    'seejohnrun.tumblr.com',
    'magerleagues.tumblr.com',
    'strle.tumblr.com',
    'gotmelookingsocrazyrightnow.tumblr.com',
    'pitchfork.tumblr.com',
    'nprmusic.tumblr.com',
    'rollingstone.tumblr.com',

  ];

  $(function () {

    // Load templates
    var $container = $('#container');
    var bcTemplate = _.template($('#blog-card-template').html());
    var blogsTemplate = _.template($('#blogs-template').html());
    var blogTemplate = _.template($('#blog-template').html());
    var blogHeaderTemplate = _.template($('#blog-header-template').html());

    // Handle new requests
    var start = function (args) {
      $container.html('');
      if (args.length > 0 && args[0] === 'blogName') {
        loadBlog(args[1]);
      } else {
        loadBlogDirectory();
      }
    };

    // Load all pages
    var loadBlogDirectory = function () {
      // Load the template
      $container.html(blogsTemplate());
      var $blogs = $container.find('.blogs');
      var throbber = Throbber.forElement($blogs[0]);
      // Add each of the friends as a link
      blog_track_list.loadFriends(blogNames, function (blogs) {
        blogs.forEach(function (blogDetail) {
          blogDetail.avatar64 = 'http://api.tumblr.com/v2/blog/' + blogDetail.name + '.tumblr.com/avatar/64';
          $blogs.append(bcTemplate(blogDetail));
        });
        throbber.hide();
      });
    };

    var loadBlog = function (blogName) {

      $container.html(blogTemplate());
      var $blog = $container.find('#blog');
      var blogThrobber = Throbber.forElement($blog[0]);

      blog_track_list.trackListing(blogName, function (blog, uris) {

        uris = _.compact(uris);

        blogThrobber.hide();
        if (uris.length === 0) { return; }

        // Load up detail about this person
        blog.avatar128 = 'http://api.tumblr.com/v2/blog/' + blog.name + '.tumblr.com/avatar/128';
        $blog.append(blogHeaderTemplate(blog));

        // Make an OTF playlist
        var tempName = 'tumblr:' + blog.name + ':' + new Date().getTime().toString();
        models.Playlist.createTemporary(tempName).done(function (playlist) {

          // Add the tracks to the playlist
          playlist.load('tracks');
          playlist.tracks.add(models.Track.fromURIs(uris)).done(function () {

            // And put it in a list
            var list = new List.forPlaylist(playlist);
            $blog.append(list.node);
            list.init(); // TODO not sure what this does

          });

        });

      });

    };

    // Hook into load and update
    models.application.load('arguments').done(function (app) { start(app.arguments); });
    models.application.addEventListener('arguments', function (e) {
      start(e.data.arguments);
    });

  });

});
<|endoftext|>


<commit_before>$(document).ready(function() {
    var canvas = document.getElementById('render');
    var ctx = canvas.getContext('2d');

    // scratchCanvas hack for clip() fix in Chrome/Chromium
    var scratchCanvas = document.createElement('canvas');
    scratchCanvas.width = 100;
    scratchCanvas.height = 100;
    var scratchCtx = scratchCanvas.getContext('2d');

    var wordArr = [];
    var iconObj;

    /* hard coded values for 320px width layout */
    // top and left margins
    var startX = 16;
    var startY = 20;
    // spacing between icons
    var spaceX = 76;
    var spaceY = 90;

    // load data.json
    $.getJSON('data.json', function(data) {
        iconObj = data;
    }).fail(function() {
        alert('There was a problem loading/reading JSON.');
    });

    $("#form-submit").click(function() {
        wordArr = [];
        $("#render-form :input").each(function() {
            var input = $(this);
            if (input.val() !== "") {
                wordArr.push(input.val().toUpperCase().replace(/[0-9_\W]/g, '').split(""));
            }
        });
        renderLayout();
    });

    function renderLayout() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        var backgroundImage = addImage('images/ios-background.png');
        $(backgroundImage).on('imgload', function() {
            for (var i = 0; i < wordArr.length; i++) {
                for (var j = 0; j < wordArr[i].length; j++) {
                    // get random icon
                    var icon = iconObj[wordArr[i][j]][Math.floor(Math.random() * iconObj[wordArr[i][j]].length)];
                    addIcon('images/' + icon + '.jpg', startX + spaceX * j, startY + spaceY * i);
                }
            }
            renderTray();
            $(backgroundImage).off();
        });

    }

    // function assumes clearing canvas is not needed
    function renderTray() {
        for(var i = 0; i < 4; i++) {
            var icon = iconObj.MISC[Math.floor(Math.random() * iconObj.MISC.length)];
            addIcon('images/' + icon + '.png', startX + spaceX * i, startY + spaceY * 5, 10.5, 0.51, 0.51);
        }
    }

    function addImage(url, x, y, scaleX, scaleY) {
        var img = new Image();
        img.src = url;

        img.onload = function() {
            ctx.drawImage(img, x || 0, y || 0, img.width * (scaleX || 0.5), img.height * (scaleY || 0.5));
            $(img).trigger('imgload');
        }

        return img;
    }

    function addIcon(url, x, y, radius, scaleX, scaleY) {
        var img = new Image();
        img.src = url;

        img.onload = function() {
            ctx.save();

            // code taken from http://stackoverflow.com/a/13854185/1593122
            // hack for fixing clip() issue in Chrome/Chromium

            scratchCtx.clearRect(0, 0, scratchCanvas.width, scratchCanvas.height);
            scratchCtx.globalCompositeOperation = 'source-over';

            scratchCtx.drawImage(img, 0, 0, img.width * (scaleX || 0.4), img.height * (scaleY || 0.4));

            scratchCtx.fillStyle = '#fff';
            scratchCtx.globalCompositeOperation = 'destination-in';
            roundedImage(scratchCtx, 0, 0, img.width * (scaleX || 0.4), img.height * (scaleY || 0.4), radius || 10.5);
            scratchCtx.fill();

            ctx.drawImage(scratchCanvas, x, y);

            ctx.restore();
        }
    }

    // code taken from http://stackoverflow.com/a/19593950/1593122
    function roundedImage(ctx, x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
    }
});
<commit_msg>update to create a translucent rectangle for the tray<commit_after>$(document).ready(function() {
    var canvas = document.getElementById('render');
    var ctx = canvas.getContext('2d');

    // scratchCanvas hack for clip() fix in Chrome/Chromium
    var scratchCanvas = document.createElement('canvas');
    scratchCanvas.width = 100;
    scratchCanvas.height = 100;
    var scratchCtx = scratchCanvas.getContext('2d');

    var wordArr = [];
    var iconObj;

    /* hard coded values for 320px width layout */
    // top and left margins
    var startX = 16;
    var startY = 20;
    // spacing between icons
    var spaceX = 76;
    var spaceY = 90;

    // load data.json
    $.getJSON('data.json', function(data) {
        iconObj = data;
    }).fail(function() {
        alert('There was a problem loading/reading JSON.');
    });

    $("#form-submit").click(function() {
        wordArr = [];
        $("#render-form :input").each(function() {
            var input = $(this);
            if (input.val() !== "") {
                wordArr.push(input.val().toUpperCase().replace(/[0-9_\W]/g, '').split(""));
            }
        });
        renderLayout();
    });

    function renderLayout() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        var backgroundImage = addImage('images/ios-background.png');
        $(backgroundImage).on('imgload', function() {
            for (var i = 0; i < wordArr.length; i++) {
                for (var j = 0; j < wordArr[i].length; j++) {
                    // get random icon
                    var icon = iconObj[wordArr[i][j]][Math.floor(Math.random() * iconObj[wordArr[i][j]].length)];
                    addIcon('images/' + icon + '.jpg', startX + spaceX * j, startY + spaceY * i);
                }
            }
            renderTray();
            $(backgroundImage).off();
        });

    }

    // function assumes clearing canvas is not needed
    function renderTray() {
        // draw a rectangle for the tray
        ctx.globalAlpha = 0.2;  // change alpha to make tray translucent
        ctx.beginPath();
        ctx.rect(0, startY + spaceY * 5, canvas.width, canvas.height - startY - spaceY * 5);
        ctx.fillStyle = "#ffffff";
        ctx.fill();
        ctx.closePath();
        ctx.globalAlpha = 1;    // set alpha back to 1

        for(var i = 0; i < 4; i++) {
            var icon = iconObj.MISC[Math.floor(Math.random() * iconObj.MISC.length)];
            addIcon('images/' + icon + '.png', startX + spaceX * i, startY + spaceY * 5, 10.5, 0.51, 0.51);
        }
    }

    function addImage(url, x, y, scaleX, scaleY) {
        var img = new Image();
        img.src = url;

        img.onload = function() {
            ctx.drawImage(img, x || 0, y || 0, img.width * (scaleX || 0.5), img.height * (scaleY || 0.5));
            $(img).trigger('imgload');
        }

        return img;
    }

    function addIcon(url, x, y, radius, scaleX, scaleY) {
        var img = new Image();
        img.src = url;

        img.onload = function() {
            ctx.save();

            // code taken from http://stackoverflow.com/a/13854185/1593122
            // hack for fixing clip() issue in Chrome/Chromium

            scratchCtx.clearRect(0, 0, scratchCanvas.width, scratchCanvas.height);
            scratchCtx.globalCompositeOperation = 'source-over';

            scratchCtx.drawImage(img, 0, 0, img.width * (scaleX || 0.4), img.height * (scaleY || 0.4));

            scratchCtx.fillStyle = '#fff';
            scratchCtx.globalCompositeOperation = 'destination-in';
            roundedImage(scratchCtx, 0, 0, img.width * (scaleX || 0.4), img.height * (scaleY || 0.4), radius || 10.5);
            scratchCtx.fill();

            ctx.drawImage(scratchCanvas, x, y);

            ctx.restore();
        }
    }

    // code taken from http://stackoverflow.com/a/19593950/1593122
    function roundedImage(ctx, x, y, width, height, radius) {
        ctx.beginPath();
        ctx.moveTo(x + radius, y);
        ctx.lineTo(x + width - radius, y);
        ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        ctx.lineTo(x + width, y + height - radius);
        ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        ctx.lineTo(x + radius, y + height);
        ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        ctx.lineTo(x, y + radius);
        ctx.quadraticCurveTo(x, y, x + radius, y);
        ctx.closePath();
    }
});
<|endoftext|>


<commit_before>$(document).ready(function() {
    if (("standalone" in window.navigator) && window.navigator.standalone) {
        // For iOS Apps
        $('a').on('click', function(e) {
            e.preventDefault();
            var new_location = $(this).attr('href');
            if (new_location != undefined && new_location.substr(0, 1) != '#' && $(this).attr('data-method') == undefined) {
                window.location = new_location;
            }
        });
    }
});

$("#hamburger").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
});

var shareSocial = function(message) {
    if (!message) {
        swal({
            title: "Share on social media?",
            text: "",
            confirmButtonText: "Cancel",
            confirmButtonColor: "#c0c0c0",
            html: true
        });
    } else {
        swal({
            title: "Share " + message + " on social media?",
            text: "",
            confirmButtonText: "Cancel",
            confirmButtonColor: "#c0c0c0",
            html: true
        });
    }
};

var shareOn = function(network) {
    swal("Success!", "Shared on " + network + "!", "success");
};

var profile = function(cub) {
    console.log("Opening profile for " + cub)
    window.open("/pinewood/pages/profiles/" + cub, "_self");
};
<commit_msg>Trying one last time<commit_after>(function(a, b, c) {
    if (c in b && b[c]) {
        var d, e = a.location,
            f = /^(a|html)$/i;
        a.addEventListener("click", function(a) {
            d = a.target;
            while (!f.test(d.nodeName)) d = d.parentNode;
            "href" in d && (chref = d.href).replace(e.href, "").indexOf("#") && (!/^[a-z\+\.\-]+:/i.test(chref) || chref.indexOf(e.protocol + "//" + e.host) === 0) && (a.preventDefault(), e.href = d.href)
        }, !1)
    }
})(document, window.navigator, "standalone");

$("#hamburger").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
});

var shareSocial = function(message) {
    if (!message) {
        swal({
            title: "Share on social media?",
            text: "",
            confirmButtonText: "Cancel",
            confirmButtonColor: "#c0c0c0",
            html: true
        });
    } else {
        swal({
            title: "Share " + message + " on social media?",
            text: "",
            confirmButtonText: "Cancel",
            confirmButtonColor: "#c0c0c0",
            html: true
        });
    }
};

var shareOn = function(network) {
    swal("Success!", "Shared on " + network + "!", "success");
};

var profile = function(cub) {
    console.log("Opening profile for " + cub)
    window.open("/pinewood/pages/profiles/" + cub, "_self");
};
<|endoftext|>


<commit_before>var datasource = "./data/data.json"
var backi= -1;

// HELPER FUNCTIONS
var timeLeftDescription = function(x) {

  var t = x.getTime();
  if(t<0) t=0;

  var tseconds = t / 1000;
  var seconds = Math.floor(tseconds) % 60;
  var tminutes = tseconds / 60;
  var minutes = Math.floor(tminutes) % 60;
  var thours = tminutes / 60;
  var hours = Math.floor(thours) % 24;
  var tdays = thours / 24;
  var days = Math.floor(tdays);

  return days + " days, " +
         ((hours < 10) ? "0" : "") + hours + "h " +
         ((minutes < 10) ? "0" : "") + minutes + "m " +
         ((seconds < 10) ? "0" : "") + seconds + "s";
}

// load DATABASE
// Note: data is a list of json objects of this form containing, "venue", "area", "deadline" as parsable string for data (see http://www.w3schools.com/js/js_dates.asp) and optionally "approx" that indicates if the date is just based on a previous date
var deadlines = new Array();
var deadlines_approx = new Array();
// var conference_dates = new Array();
// probably not the best idea to make it synchronous, but the quick and dirty hack works for now
$.ajaxSetup({'async': false});
$.getJSON(datasource, function(data) {
  var now = new Date();
  for (var i in data) {
    d = new Date(data[i].deadline);
    while(d < now){
      d.setFullYear(d.getFullYear()+1);
      data[i].approx = 1;
    }
    data[i].deadline = d;
    if(data[i].approx){
      deadlines_approx.push(data[i]);
    }
    else{
      deadlines.push(data[i]);
    }
  }
  deadlines.sort(function(a,b) {
    return a.deadline.getTime() - b.deadline.getTime();
  });
  deadlines_approx.sort(function(a,b) {
    return a.deadline.getTime() - b.deadline.getTime();
  });

  // conference_dates.push({
  //   start: new Date(d.conference_dates.start),
  //   end: new Date(d.conference_dates.end)
  // });
});

// Friday, March 1st, 11:59pm UTC
//deadlines.push({venue: "UAI", area: "Machine Learning", deadline: new Date("Friday, March 1st, 11:59pm UTC"), approx: 1});
// Mar. 15, 2013
//deadlines.push({venue: "IROS", area: "Robotics", deadline: new Date(2014, 2, 15, 23, 59, 0, 0)});

// Display function, called every second or so
function refreshDisplay() {

    var dc = new Date();
    $("#currtime").text("Current time: " + dc);

    // calculate and display deadlines
    for(var i=0;i<deadlines.length;i++) {
      var dl = deadlines[i];
      refreshDeadline(i, dl, dc, deadlines);
    }
    for(var i=0;i<deadlines_approx.length;i++) {
      var dl = deadlines_approx[i];
      refreshDeadline(i, dl, dc, deadlines_approx);
    }

}

function refreshDeadline(i, dl, dc, deadlines__){

  suffix = ""
  warningString= "";
  if("approx" in dl) {
    warningString= "based on previous year!";
    suffix= "_approx"
  }

  var timeLeft = new Date(dl.deadline.getTime() - dc.getTime());

  var venue = dl.venue;

  if("location" in dl)
    venue = venue + "  (" + dl.location + ")";

  if("link" in dl)
    venue = "" + venue + "";

  if("conference_dates" in dl) {
    conference_dates =
      new Date(dl.conference_dates.start).toDateString().slice(0, -5) + " to "
      + new Date(dl.conference_dates.end).toDateString();
  } else {
    conference_dates = "Not known";
  }

  $("#deadline" + suffix + i).html(
    "
" + timeLeftDescription(timeLeft) + "
"
  + "
" + venue + "
"
  + "
" + dl.area + "
"
  + "
 Deadline: " + dl.deadline.toUTCString() + "
"
  + "
 Conference Dates: " + conference_dates + "
"
  + "
" + warningString + "
"
  + "
hide
"
  );
  var hid = "#hide"+suffix+i;
  var did = "#deadline"+suffix+i;
  $(hid).click(function(x) {
    return function() {
      $(x).hide();
      return false;
    }
  }(did));

  var linkid = "#link"+suffix+i;
  $(linkid).click(function(x) {
    return function() {
      window.open(x);
      return false;
    }
  }(dl.link));

  if(backi !== -1) {
    var dl = deadlines[backi];
    if(backapprox)
      dl = deadlines_approx[backi];

    var venue = dl.venue;
    if("link" in dl)
      venue = "" + venue + "";
    var timeLeft= new Date(dl.deadline.getTime() - dc.getTime());
    $("#backfacetext").html(
      venue + "
"
      + timeLeftDescription(timeLeft)
      );

    var linkid = "#link"+suffix+i;
    $(linkid).click(function(x) {
      return function() {
        window.open(x);
        return false;
      }
    }(dl.link));
  }
}

// int main(){}
$(document).ready(function() {

  // create divs for all deadlines and insert into DOM
  for(var i=0;i<deadlines.length;i++) {
    var dl= deadlines[i];
    $("

").appendTo("div#deadlinesdiv");
    var divid= "#deadline" + i;
    var hidid= "#hide" + i;

    $(divid).hide();
    $(divid).fadeIn(200*(i+1), function() { }); // create a nice fade in effect

    $(divid).click(function(z,zapprox) { // Fade in backface and make a giant timer for this event on click
      // self-executing function hackery :)
      return function() {
        backi = z;
        backapprox = zapprox;
        $("#backface").fadeIn("slow"); // fade in white stuff
      }
    }(i,false));
  }
  for(var i=0;i<deadlines_approx.length;i++) {
    var dl= deadlines_approx[i];
    $("

").appendTo("div#deadlinesdiv");
    var divid= "#deadline_approx" + i;
    var hidid= "#hide_approx" + i;

    $(divid).hide();
    $(divid).fadeIn(200*(i+1), function() { }); // create a nice fade in effect

    $(divid).click(function(z,zapprox) { // Fade in backface and make a giant timer for this event on click
      // self-executing function hackery :)
      return function() {
        backi = z;
        backapprox = zapprox;
        $("#backface").fadeIn("slow"); // fade in white stuff
      }
    }(i,true));
  }

  // set up deadline timer to redraw
  setInterval(
    function(){ refreshDisplay(); },
    1000
  );

  $("#backface").click(function() {
    backi = -1;
    $("#backface").fadeOut("slow");
  });

  $("#makeown").click(function() {
    backi = -1;
    $("#instrown").fadeToggle();
  });

  // draw!
  refreshDisplay();

});
<commit_msg>Added abstract deadline<commit_after>var datasource = "./data/data.json"
var backi= -1;

// HELPER FUNCTIONS
var timeLeftDescription = function(x) {

  var t = x.getTime();
  if(t<0) t=0;

  var tseconds = t / 1000;
  var seconds = Math.floor(tseconds) % 60;
  var tminutes = tseconds / 60;
  var minutes = Math.floor(tminutes) % 60;
  var thours = tminutes / 60;
  var hours = Math.floor(thours) % 24;
  var tdays = thours / 24;
  var days = Math.floor(tdays);

  return days + " days, " +
         ((hours < 10) ? "0" : "") + hours + "h " +
         ((minutes < 10) ? "0" : "") + minutes + "m " +
         ((seconds < 10) ? "0" : "") + seconds + "s";
}

// load DATABASE
// Note: data is a list of json objects of this form containing, "venue", "area", "deadline" as parsable string for data (see http://www.w3schools.com/js/js_dates.asp) and optionally "approx" that indicates if the date is just based on a previous date
var deadlines = new Array();
var deadlines_approx = new Array();
// var conference_dates = new Array();
// probably not the best idea to make it synchronous, but the quick and dirty hack works for now
$.ajaxSetup({'async': false});
$.getJSON(datasource, function(data) {
  var now = new Date();
  for (var i in data) {
    d = new Date(data[i].deadline);
    while(d < now){
      d.setFullYear(d.getFullYear()+1);
      data[i].approx = 1;
    }
    data[i].deadline = d;
    if(data[i].approx){
      deadlines_approx.push(data[i]);
    }
    else{
      deadlines.push(data[i]);
    }
  }
  deadlines.sort(function(a,b) {
    return a.deadline.getTime() - b.deadline.getTime();
  });
  deadlines_approx.sort(function(a,b) {
    return a.deadline.getTime() - b.deadline.getTime();
  });

  // conference_dates.push({
  //   start: new Date(d.conference_dates.start),
  //   end: new Date(d.conference_dates.end)
  // });
});

// Friday, March 1st, 11:59pm UTC
//deadlines.push({venue: "UAI", area: "Machine Learning", deadline: new Date("Friday, March 1st, 11:59pm UTC"), approx: 1});
// Mar. 15, 2013
//deadlines.push({venue: "IROS", area: "Robotics", deadline: new Date(2014, 2, 15, 23, 59, 0, 0)});

// Display function, called every second or so
function refreshDisplay() {

    var dc = new Date();
    $("#currtime").text("Current time: " + dc);

    // calculate and display deadlines
    for(var i=0;i<deadlines.length;i++) {
      var dl = deadlines[i];
      refreshDeadline(i, dl, dc, deadlines);
    }
    for(var i=0;i<deadlines_approx.length;i++) {
      var dl = deadlines_approx[i];
      refreshDeadline(i, dl, dc, deadlines_approx);
    }

}

function refreshDeadline(i, dl, dc, deadlines__){

  suffix = ""
  warningString= "";
  if("approx" in dl) {
    warningString= "based on previous year!";
    suffix= "_approx"
  }

  var timeLeft = new Date(dl.deadline.getTime() - dc.getTime());

  var venue = dl.venue;

  if("location" in dl)
    venue = venue + "  (" + dl.location + ")";

  if("link" in dl)
    venue = "" + venue + "";

  if("conference_dates" in dl) {
    conferenceDates =
      new Date(dl.conference_dates.start).toDateString().slice(0, -5) + " to "
      + new Date(dl.conference_dates.end).toDateString();
  } else {
    conferenceDates = "Not known";
  }

  if("abstract_deadline" in dl) {
    abstractDeadline = dl.abstract_deadline.toUTCString();
  } else {
    abstractDeadline = "None";
  }

  $("#deadline" + suffix + i).html(
    "
" + timeLeftDescription(timeLeft) + "
"
  + "
" + venue + "
"
  + "
" + dl.area + "
"
  + "
 Abstract Deadline: " + abstractDeadline + "
"
  + "
 Deadline: " + dl.deadline.toUTCString() + "
"
  + "
 Conference Dates: " + conferenceDates + "
"
  + "
" + warningString + "
"
  + "
hide
"
  );
  var hid = "#hide"+suffix+i;
  var did = "#deadline"+suffix+i;
  $(hid).click(function(x) {
    return function() {
      $(x).hide();
      return false;
    }
  }(did));

  var linkid = "#link"+suffix+i;
  $(linkid).click(function(x) {
    return function() {
      window.open(x);
      return false;
    }
  }(dl.link));

  if(backi !== -1) {
    var dl = deadlines[backi];
    if(backapprox)
      dl = deadlines_approx[backi];

    var venue = dl.venue;
    if("link" in dl)
      venue = "" + venue + "";
    var timeLeft= new Date(dl.deadline.getTime() - dc.getTime());
    $("#backfacetext").html(
      venue + "
"
      + timeLeftDescription(timeLeft)
      );

    var linkid = "#link"+suffix+i;
    $(linkid).click(function(x) {
      return function() {
        window.open(x);
        return false;
      }
    }(dl.link));
  }
}

// int main(){}
$(document).ready(function() {

  // create divs for all deadlines and insert into DOM
  for(var i=0;i<deadlines.length;i++) {
    var dl= deadlines[i];
    $("

").appendTo("div#deadlinesdiv");
    var divid= "#deadline" + i;
    var hidid= "#hide" + i;

    $(divid).hide();
    $(divid).fadeIn(200*(i+1), function() { }); // create a nice fade in effect

    $(divid).click(function(z,zapprox) { // Fade in backface and make a giant timer for this event on click
      // self-executing function hackery :)
      return function() {
        backi = z;
        backapprox = zapprox;
        $("#backface").fadeIn("slow"); // fade in white stuff
      }
    }(i,false));
  }
  for(var i=0;i<deadlines_approx.length;i++) {
    var dl= deadlines_approx[i];
    $("

").appendTo("div#deadlinesdiv");
    var divid= "#deadline_approx" + i;
    var hidid= "#hide_approx" + i;

    $(divid).hide();
    $(divid).fadeIn(200*(i+1), function() { }); // create a nice fade in effect

    $(divid).click(function(z,zapprox) { // Fade in backface and make a giant timer for this event on click
      // self-executing function hackery :)
      return function() {
        backi = z;
        backapprox = zapprox;
        $("#backface").fadeIn("slow"); // fade in white stuff
      }
    }(i,true));
  }

  // set up deadline timer to redraw
  setInterval(
    function(){ refreshDisplay(); },
    1000
  );

  $("#backface").click(function() {
    backi = -1;
    $("#backface").fadeOut("slow");
  });

  $("#makeown").click(function() {
    backi = -1;
    $("#instrown").fadeToggle();
  });

  // draw!
  refreshDisplay();

});
<|endoftext|>


<commit_before>
$(function() {

    // Populate using an object literal

    WTF.init({

         heading: [
             "It's a fucking",
             "Check this shit out, a fucking",
         ],
         response: [
             "Already fucking seen one",
             "Give me a-fucking-nother one",
             "Don't really give a fuck",
         ],
         template: [
             "@adj @weapon",
             "@weapon with @attach",
             "@weapon made of @material",
             "@weapon of @noun",

         ],
         weapon: [
             "sword",
             "club",
             "knife",
             "arrow",
             "rock",
             "war axe",
             "hammer",
             "mace",
             "tooth",
             "scythe",
             "flail",
             "staff",
             "spear",
             "whip",
             "halberd",
             "maul",
             "rapier",
             "longsword",
             "shortsword",
             "sickle",
             "trident",
             "scimitar",
             "shovel",
             "pickaxe",
             "gauntlet",
             "baton",

         ],
         adj: [
             "magical",
             "poisonous",
             "bloody",
             "broken",
             "masterwork",
             "legendary",
             "flaming",
             "mythical",
             "dwarven",
             "orcish",
             "elven",
             "vorpal",
             "acid",
             "slimy",
             "glowing",

         ],
         attach: [
             "blood on it",
             "spikes",
             "sparkles",
             "a mouth",
             "teeth",
             "runes",
             "elaborate decoration",
             "a hook",

         ],
         material: [
            "glass",
            "diamond",
            "fire",
            "yarn",
            "meat",
            "bone",
            "ice",
            "stone",
            "silver",
            "meteorite",
            "shadow",

        ],
        noun: [
            "annihilation",
            "justice",
            "evil",
            "war",
            "massacre",
            "honor",
            "light and shadow",
            "light",
            "darkness",
            "legend",
            "hope",
            "doom",
            "destiny",
            "the night",
            "sacrifice",

        ],

     });

    // Populate using a JSON file
    // WTF.init( 'sample.json' );

    // Populate using a Google spreadsheet ID (you must publish it first!)
    // @see https://support.google.com/drive/answer/37579?hl=en
    // WTF.init( '0AvG1Hx204EyydF9ub1M2cVJ3Z1VGdDhTSWg0ZV9LNGc' );

});<commit_msg>lance<commit_after>
$(function() {

    // Populate using an object literal

    WTF.init({

         heading: [
             "It's a fucking",
             "Check this shit out, a fucking",
         ],
         response: [
             "Already fucking seen one",
             "Give me a-fucking-nother one",
             "Don't really give a fuck",
         ],
         template: [
             "@adj @weapon",
             "@weapon with @attach",
             "@weapon made of @material",
             "@weapon of @noun",

         ],
         weapon: [
             "sword",
             "club",
             "knife",
             "arrow",
             "rock",
             "war axe",
             "hammer",
             "mace",
             "tooth",
             "scythe",
             "flail",
             "staff",
             "spear",
             "whip",
             "halberd",
             "maul",
             "rapier",
             "longsword",
             "shortsword",
             "sickle",
             "trident",
             "scimitar",
             "shovel",
             "pickaxe",
             "gauntlet",
             "baton",
             "lance",

         ],
         adj: [
             "magical",
             "poisonous",
             "bloody",
             "broken",
             "masterwork",
             "legendary",
             "flaming",
             "mythical",
             "dwarven",
             "orcish",
             "elven",
             "vorpal",
             "acid",
             "slimy",
             "glowing",

         ],
         attach: [
             "blood on it",
             "spikes",
             "sparkles",
             "a mouth",
             "teeth",
             "runes",
             "elaborate decoration",
             "a hook",

         ],
         material: [
            "glass",
            "diamond",
            "fire",
            "yarn",
            "meat",
            "bone",
            "ice",
            "stone",
            "silver",
            "meteorite",
            "shadow",

        ],
        noun: [
            "annihilation",
            "justice",
            "evil",
            "war",
            "massacre",
            "honor",
            "light and shadow",
            "light",
            "darkness",
            "legend",
            "hope",
            "doom",
            "destiny",
            "the night",
            "sacrifice",

        ],

     });

    // Populate using a JSON file
    // WTF.init( 'sample.json' );

    // Populate using a Google spreadsheet ID (you must publish it first!)
    // @see https://support.google.com/drive/answer/37579?hl=en
    // WTF.init( '0AvG1Hx204EyydF9ub1M2cVJ3Z1VGdDhTSWg0ZV9LNGc' );

});<|endoftext|>


<commit_before>var globalColorWheel;
var timersList = [];
var outerWheel, innerWheel;

var count = 0;
function callTimerCallbacks() {
  count = (count + 1) % 60;
  for(var i = 0; i < timersList.length; i++) {
    timersList[i](count);
  }
}

//---------------------------------------------------------------------------------
var Led = React.createClass({
  getInitialState:function() {
    return {rgb:{r:255, g:0, b:0}}; // Set it to red
  },

  setLed: function() {
    this.setState({rgb:globalColorWheel.state.rgb});
  },

  render: function(){
    var x = this.props.x;
    var y = this.props.y;
    var a = this.props.angle;
    var thickness = this.props.thickness;
    var dx = Math.round(Math.cos(a) * (thickness-2));
    var dy = Math.round(Math.sin(a) * (thickness-2));
    var rgb = this.state.rgb;

    return(
    <path
      d={
        "M" + x + "," + y + " " +
        "l" + (+dy/2) + "," + (dx/2) + " " +
        "l" + (+dx) + "," + (-dy) + " " +
        "l" + (-dy) + "," + (-dx) + " " +
        "l" + (-dx) + "," + (+dy) + " " +
        "z"
      }
      fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
      stroke = "black"
      onClick = {this.setLed}
    />);
  }
})

//---------------------------------------------------------------------------------
var LedOneWheel = React.createClass({
  getInitialState:function() {
    return {speed:0, angle:0, counter:60};
  },

  changeSpeed:function(speedInc) {
    if ((speedInc == 1 && this.state.speed < 1)
      || (speedInc == -1 && this.state.speed > -1)) {
      console.log("LedOneWheel n=", this.props.n, " speedInc=", speedInc);
      this.setState({speed:this.state.speed + speedInc})
    }
  },

  tick:function(count) {
    if (this.state.speed == 0)
      return;
    if (count==0 || count % this.state.counter == 0) {
      var a = this.state.angle;
      a = (a + this.state.speed) % this.props.n;
      this.setState({angle:a});
    }
  },

  componentDidMount: function() {
    timersList.push(this.tick);
    console.log("Adding timer for LedOneWheel");
  },

  componentWillUnmount: function() {
    var index = timersList.indexof(this.tick);
    if (index > -1) timersList.splice( index, 1 );
    console.log("Removing timer for LedOneWheel");
  },

  render:function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var r = this.props.r;
    var thickness = this.props.thickness;
    var r2 = r - thickness;
    var leds = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var x = radius + Math.round(Math.cos(a1)*r);
      var y = radius - Math.round(Math.sin(a1)*r);

      leds.push(<Led key={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
    }
    return (<g transform={"rotate(" + (360* this.state.angle/n) + " " + radius + " " + radius + ")"}>{leds}</g>);
  }
})

//---------------------------------------------------------------------------------
var LedWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("LedWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius};
  },

  computeAvailableRadius:function() {
    console.log("LedWheel.computeAvailableRadius", this.props.radius);
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', 100, this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  getDefaultProps: function() {
    return { radius:200 };
  },

  // thickeness is calculated from radius as follows
  //    radius^2 = thickness/2 ^2  + (r1 + thickness)^2
  //    thickness/2  / r1  = tan(PI/24)
  // Solving
  //   r1 = thickness / (2*tan(PI/24))
  //   radius^2 = thickness^2 * (  (1/2)^2 + (1/(2*tan(PI/24) + 1)^2 )

  render: function() {
    var radius = this.state.radius-1;
    var thickness = radius / Math.sqrt(0.25 + Math.pow(1 + (1/(2*Math.tan(Math.PI/24))), 2) );
    var r1 = thickness / (2 * Math.tan(Math.PI/24));
    var r2 = thickness / (2 * Math.tan(Math.PI/12));

    var self = this;
    return (<svg
      ref={function(input) { self.elem = input; }}
      height={radius*2} width={radius*2}>
        <LedOneWheel
          ref={function(input) { outerWheel = input; }}
          key="g0" n={24} radius={radius} thickness={thickness} circleIndex={0} r={r1}/>
        <LedOneWheel
          ref={function(input) { innerWheel = input; }}
          key="g1" n={12} radius={radius} thickness={thickness} circleIndex={1} r={r2}/>
      </svg>);
  }
})

//---------------------------------------------------------------------------------
var HueSquare = React.createClass({
  getInitialState: function() {
    return {hue:0}; // initial hue is 0, inicial color is red
  },

  getDefaultProps: function() {
    return { n: 8, radius:100, thickness:30 };
  },

  render: function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var thickness = this.props.thickness;

    var radius2 = radius - thickness - thickness/2;
    var squareSize = 2 * radius2/Math.sqrt(2) - 2; // side of square that fits in inner circle
    var smallSquareSize = squareSize/n;

    var colorSquares = [];
    var sat = 255;
    for(var j = 0; j < n; j++) {
      var val = 255;
      for(var i = 0; i < n; i++) {
        var hsv = {hue:this.state.hue, sat:sat, val:val};
        var rgb = hsv2rgb(hsv);

        //console.log(hsv, rgb);
        colorSquares.push(<path
          key={"path" + j + "_" + i}
          d={
            "M" + (radius -squareSize/2 + squareSize*j/n) + "," + (radius - squareSize/2 + squareSize*i/n) + " " +
            "l" + (+smallSquareSize) + "," + 0 + " " +
            "l" + 0 + "," + (+smallSquareSize) + " " +
            "l" + (-smallSquareSize) + "," + 0 + " " +
            "z"
          }
          fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
          stroke = "none"
        />);
        val = val -256/n;
      }
      sat = sat -256/n;
    }
    return (<g>{colorSquares}</g>);
  }
})

//---------------------------------------------------------------------------------
var ColorWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("ColorWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius, hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
  },

  computeAvailableRadius:function() {
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', this.handleResize);
    globalColorWheel = this;
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  selectHue: function(i, hue, rgb) {
    this.setState({hueIndex:i, hue:hue, rgb:rgb});
    this.hueSquare.setState({hue:hue});
  },

  getDefaultProps: function() {
    return { n: 24, radius:100};
  },

  render: function() {
    var n = this.props.n;
    var radius = this.state.radius -1;
    var thickness = Math.round(radius/3);
    // radus is the outer radius

    var radius2 = radius - thickness - thickness/2;
    var radius3 = radius - thickness/2;

    var colorSegments = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var a2 = Math.PI * 2 * (i+1)/n;
      var hue = Math.round(256 * i/n);
      var hsv = {hue:hue, sat:255, val:255};
      var rgb = hsv2rgb(hsv);
      var r = this.state.hueIndex == i ? radius : radius3;

      //console.log(hsv, rgb);
      colorSegments.push(<path
        key={"path" + i}
        id={"path" + i}
        d={
          "M" + (radius + Math.round(Math.cos(a1) * r)) + "," + (radius - Math.round(Math.sin(a1) * r)) + " " +
          "A" + r + "," + r + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * r)) + "," + (radius - Math.round(Math.sin(a2) * r)) + " " +
          "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
          "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
          "Z"
        }
        fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
        stroke = "black"
        strokeWidth = {this.state.hueIndex == i ? "1.5" : "1"}
        onClick = {this.selectHue.bind(this, i, hue, rgb)}
      />);
    }
    console.log("ColorWheel", radius);
    var self = this;
    return (<svg height={radius*2} width={radius*2}
      ref={function(input) { self.elem = input; }}
      >
      <g>{colorSegments}</g>
      <HueSquare
        ref={function(input) {self.hueSquare = input }}
        radius={this.state.radius} n={8} thickness={thickness} />
    </svg>);
  }
})

//---------------------------------------------------------------------------------
var LeftRightArrow = React.createClass({
  changeSpeed:function(speedInc) {
    this.setState({speed:(this.state.speed + speedInc)});
  },

  getInitialState: function() {
    return {speed:0};
  },

  render: function() {
    return(

              {this.props.label}
              <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}></button>
              {this.state.speed}
              <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}></button>

);
  }
})

//---------------------------------------------------------------------------------

ReactDOM.render(
      <LedWheel radius={200}/>,
      document.getElementById('main')
)

ReactDOM.render(
      <ColorWheel radius={100} n={24}/>,
      document.getElementById('right')
)

ReactDOM.render(
      <form className="ui form">
      <LeftRightArrow label="Outer Circle" wheelObj={outerWheel}/>
      <LeftRightArrow label="Inner Circle" wheelObj={innerWheel}/>
      </form>,
      document.getElementById('left')
)

window.setInterval(callTimerCallbacks, 20);
<commit_msg>Update main.js<commit_after>var globalColorWheel;
var timersList = [];
var outerWheel, innerWheel;

var count = 0;
function callTimerCallbacks() {
  count = (count + 1) % 60;
  for(var i = 0; i < timersList.length; i++) {
    timersList[i](count);
  }
}

//---------------------------------------------------------------------------------
var Led = React.createClass({
  getInitialState:function() {
    return {rgb:{r:255, g:0, b:0}}; // Set it to red
  },

  setLed: function() {
    this.setState({rgb:globalColorWheel.state.rgb});
  },

  render: function(){
    var x = this.props.x;
    var y = this.props.y;
    var a = this.props.angle;
    var thickness = this.props.thickness;
    var dx = Math.round(Math.cos(a) * (thickness-2));
    var dy = Math.round(Math.sin(a) * (thickness-2));
    var rgb = this.state.rgb;

    return(
    <path
      d={
        "M" + x + "," + y + " " +
        "l" + (+dy/2) + "," + (dx/2) + " " +
        "l" + (+dx) + "," + (-dy) + " " +
        "l" + (-dy) + "," + (-dx) + " " +
        "l" + (-dx) + "," + (+dy) + " " +
        "z"
      }
      fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
      stroke = "black"
      onClick = {this.setLed}
    />);
  }
})

//---------------------------------------------------------------------------------
var LedOneWheel = React.createClass({
  getInitialState:function() {
    return {speed:0, angle:0, counter:60};
  },

  changeSpeed:function(speedInc) {
    if ((speedInc == 1 && this.state.speed < 1)
      || (speedInc == -1 && this.state.speed > -1)) {
      console.log("LedOneWheel n=", this.props.n, " speedInc=", speedInc);
      this.setState({speed:this.state.speed + speedInc})
    }
  },

  tick:function(count) {
    if (this.state.speed == 0)
      return;
    if (count==0 || count % this.state.counter == 0) {
      var a = this.state.angle;
      a = (a + this.state.speed) % this.props.n;
      this.setState({angle:a});
    }
  },

  componentDidMount: function() {
    timersList.push(this.tick);
    console.log("Adding timer for LedOneWheel");
  },

  componentWillUnmount: function() {
    var index = timersList.indexof(this.tick);
    if (index > -1) timersList.splice( index, 1 );
    console.log("Removing timer for LedOneWheel");
  },

  render:function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var r = this.props.r;
    var thickness = this.props.thickness;
    var r2 = r - thickness;
    var leds = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var x = radius + Math.round(Math.cos(a1)*r);
      var y = radius - Math.round(Math.sin(a1)*r);

      leds.push(<Led key={i} angle={a1} thickness={thickness-2} x={x} y={y}/>);
    }
    return (<g transform={"rotate(" + (360* this.state.angle/n) + " " + radius + " " + radius + ")"}>{leds}</g>);
  }
})

//---------------------------------------------------------------------------------
var LedWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("LedWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius};
  },

  computeAvailableRadius:function() {
    console.log("LedWheel.computeAvailableRadius", this.props.radius);
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', 100, this.handleResize);
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  getDefaultProps: function() {
    return { radius:200 };
  },

  // thickeness is calculated from radius as follows
  //    radius^2 = thickness/2 ^2  + (r1 + thickness)^2
  //    thickness/2  / r1  = tan(PI/24)
  // Solving
  //   r1 = thickness / (2*tan(PI/24))
  //   radius^2 = thickness^2 * (  (1/2)^2 + (1/(2*tan(PI/24) + 1)^2 )

  render: function() {
    var radius = this.state.radius-1;
    var thickness = radius / Math.sqrt(0.25 + Math.pow(1 + (1/(2*Math.tan(Math.PI/24))), 2) );
    var r1 = thickness / (2 * Math.tan(Math.PI/24));
    var r2 = thickness / (2 * Math.tan(Math.PI/12));

    var self = this;
    return (<svg
      ref={function(input) { self.elem = input; }}
      height={radius*2} width={radius*2}>
        <LedOneWheel
          ref={function(input) { outerWheel = input; }}
          key="g0" n={24} radius={radius} thickness={thickness} circleIndex={0} r={r1}/>
        <LedOneWheel
          ref={function(input) { innerWheel = input; }}
          key="g1" n={12} radius={radius} thickness={thickness} circleIndex={1} r={r2}/>
      </svg>);
  }
})

//---------------------------------------------------------------------------------
var HueSquare = React.createClass({
  getInitialState: function() {
    return {hue:0}; // initial hue is 0, inicial color is red
  },

  getDefaultProps: function() {
    return { n: 8, radius:100, thickness:30 };
  },

  render: function() {
    var n = this.props.n;
    var radius = this.props.radius;
    var thickness = this.props.thickness;

    var radius2 = radius - thickness - thickness/2;
    var squareSize = 2 * radius2/Math.sqrt(2) - 2; // side of square that fits in inner circle
    var smallSquareSize = squareSize/n;

    var colorSquares = [];
    var sat = 255;
    for(var j = 0; j < n; j++) {
      var val = 255;
      for(var i = 0; i < n; i++) {
        var hsv = {hue:this.state.hue, sat:sat, val:val};
        var rgb = hsv2rgb(hsv);

        //console.log(hsv, rgb);
        colorSquares.push(<path
          key={"path" + j + "_" + i}
          d={
            "M" + (radius -squareSize/2 + squareSize*j/n) + "," + (radius - squareSize/2 + squareSize*i/n) + " " +
            "l" + (+smallSquareSize) + "," + 0 + " " +
            "l" + 0 + "," + (+smallSquareSize) + " " +
            "l" + (-smallSquareSize) + "," + 0 + " " +
            "z"
          }
          fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
          stroke = "none"
        />);
        val = val -256/n;
      }
      sat = sat -256/n;
    }
    return (<g>{colorSquares}</g>);
  }
})

//---------------------------------------------------------------------------------
var ColorWheel = React.createClass({
  // The state is minumum of the radius sepcified in the props, and the available radius
  getInitialState:function() {
    console.log("ColorWheel.getInitialState", this.props.radius);
    return {radius:this.props.radius, hueIndex:0, hue:0, rgb:{r:255,g:0,b:0}}; // initial hue is 0, inicial color is red
  },

  computeAvailableRadius:function() {
    if (this.elem) {
      // calculate parent's width - padding
      var p = this.elem.parentNode;
      var s= window.getComputedStyle(p);
      var w = p.clientWidth - parseFloat(s.paddingLeft) - parseFloat(s.paddingLeft); // Need parseFloat to get rid of px in 14px
      // Divide width by 2, and leave off an extra pixel
      var r = Math.min(this.props.radius, Math.round(w/2));
      console.log("Computed Radius", r);
      this.setState({radius:r})
    }
  },

  handleResize: function(e) {
    this.computeAvailableRadius();
  },

  componentDidMount: function() {
    this.computeAvailableRadius();
    window.addEventListener('resize', this.handleResize);
    globalColorWheel = this;
  },

  componentWillUnmount: function() {
    window.removeEventListener('resize', this.handleResize);
  },

  selectHue: function(i, hue, rgb) {
    this.setState({hueIndex:i, hue:hue, rgb:rgb});
    this.hueSquare.setState({hue:hue});
  },

  getDefaultProps: function() {
    return { n: 24, radius:100};
  },

  render: function() {
    var n = this.props.n;
    var radius = this.state.radius -1;
    var thickness = Math.round(radius/3);
    // radus is the outer radius

    var radius2 = radius - thickness - thickness/2;
    var radius3 = radius - thickness/2;

    var colorSegments = [];
    for(var i = 0; i < n; i++) {
      var a1 = Math.PI * 2 * i / n;
      var a2 = Math.PI * 2 * (i+1)/n;
      var hue = Math.round(256 * i/n);
      var hsv = {hue:hue, sat:255, val:255};
      var rgb = hsv2rgb(hsv);
      var r = this.state.hueIndex == i ? radius : radius3;

      //console.log(hsv, rgb);
      colorSegments.push(<path
        key={"path" + i}
        id={"path" + i}
        d={
          "M" + (radius + Math.round(Math.cos(a1) * r)) + "," + (radius - Math.round(Math.sin(a1) * r)) + " " +
          "A" + r + "," + r + " 0 0,0 " + (radius + Math.round(Math.cos(a2) * r)) + "," + (radius - Math.round(Math.sin(a2) * r)) + " " +
          "L" + (radius + Math.round(Math.cos(a2) * radius2)) + "," + (radius - Math.round(Math.sin(a2) * radius2)) + " " +
          "A" + radius2 + "," + radius2 + " 0 0,1 " + (radius + Math.round(Math.cos(a1) * radius2)) + "," + (radius - Math.round(Math.sin(a1) * radius2)) + " " +
          "Z"
        }
        fill={"rgb(" + rgb.r + "," + rgb.g + "," +  rgb.b + ")"}
        stroke = "black"
        strokeWidth = {this.state.hueIndex == i ? "1.5" : "1"}
        onClick = {this.selectHue.bind(this, i, hue, rgb)}
      />);
    }
    console.log("ColorWheel", radius);
    var self = this;
    return (<svg height={radius*2} width={radius*2}
      ref={function(input) { self.elem = input; }}
      >
      <g>{colorSegments}</g>
      <HueSquare
        ref={function(input) {self.hueSquare = input }}
        radius={this.state.radius} n={8} thickness={thickness} />
    </svg>);
  }
})

//---------------------------------------------------------------------------------
var LeftRightArrow = React.createClass({
  changeSpeed:function(speedInc) {
    this.setState({speed:(this.state.speed + speedInc)});
  },

  getInitialState: function() {
    return {speed:0};
  },

  render: function() {
    return(

          {this.props.label}

          <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, -1)}></button>

          {this.state.speed}

          <button type="button" className="ui compact icon button" onClick={this.changeSpeed.bind(this, +1)}></button>

);
  }
})

//---------------------------------------------------------------------------------

ReactDOM.render(
      <LedWheel radius={200}/>,
      document.getElementById('main')
)

ReactDOM.render(
      <ColorWheel radius={100} n={24}/>,
      document.getElementById('right')
)

ReactDOM.render(
      <form className="ui form">
      <LeftRightArrow label="Outer Circle" wheelObj={outerWheel}/>
      <LeftRightArrow label="Inner Circle" wheelObj={innerWheel}/>
      </form>,
      document.getElementById('left')
)

window.setInterval(callTimerCallbacks, 20);
<|endoftext|>


<commit_before>
var canvas, renderer, documents, documentsIndex, currentDoc, currentLayout;
var $pages = [];
var layoutingDuration = 500;
var disqus_shortname, disqus_identifier, disqus_url, disqus_title;

$(function () {
	initData();

	$('#layoutButtons').append($('<button class="btn active">Quartalsweise</button>').click(function () {
		setLayout(layouts.quarterly, layoutingDuration);
	}));
	$('#layoutButtons').append($('<button class="btn">Nach Qualität</button>').click(function () {
		setLayout(layouts.quality, layoutingDuration);
	}));
	/*$('#layoutButtons').append($('<button class="btn">Kartenansicht</button>'));*/
	$('#layoutButtons').append($('<button class="btn">Noch mehr Funktionen demnächst!</button>'));

	$('#intro-button').click(function(){
		$('#intro-controls').remove();
		$('#intro-more').fadeIn('fast');
	});

	$('#nav-intro').click(function(){

		if ($('#intro:hidden').length === 0) {
			$('#nav-intro').parent().removeClass('active');
			$('#intro').fadeOut('fast');
		} else {
			$('#intro').fadeIn('fast');
			$('#nav-intro').parent().addClass('active');
		}

	})

	$($updates.comments).each(function(idx,e){
		$('#sidebar-comments').append($('

'+e.article+'

'+e.date+'

'+e.content+'

'));
	});

	$($updates.changes).each(function(idx,e){
		var p = (e.change>=0) ? "+":"";
		$('#sidebar-changes').append($('

'+e.article+'

'+e.date+'

'+p+''+e.change+' Zeichen

'));
	});

	$('#impressum').hide();

	$('#link-impressum').popover({
		html: true,
		content: $('#impressum').html(),
		placement: 'top'
	});

	$('#lightbox-controls a').click(function(e){
		$(this).blur();
		e.preventDefault();
	});

	$('#share-twitter').click(function(){
		window.open($(this).attr('href'), "share", "width=500,height=300,status=no,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	});
	$('#share-facebook').click(function(){
		window.open($(this).attr('href'), "share", "width=500,height=300,status=no,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	});
	$('#share-google').click(function(){
		window.open($(this).attr('href'), "share", "width=500,height=300,status=no,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	});

	$('#download-document').click(function(){
		var d = $('#lightbox').data();
		location.href="data/images/"+d.issue+"-"+d.page+".png?download";
	});
	$('#download-text').click(function(){
		var d = $('#lightbox').data();
		location.href="download/text/"+d.issue+".txt?download";
	});

	disqus_shortname = 'afgpa';
 	disqus_identifier = (location.hash === "" || location.hash === "#") ? "default" : location.hash;
 	disqus_url = location.href;
	disqus_title = "Kommentare";

	(function() {
		var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
		dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
		(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	})();

	canvas = $('#canvas');
	renderer = new Renderer(canvas);
	documents = new Documents(renderer);
	setLayout(layouts.quarterly, 0);

	hashCheck();

	$(window).bind('hashchange', function(e){
		hashCheck();
	});

	$(window).bind('onhashchange', function(e){
		hashCheck();
	});

	$(window).resize((function () {
		var resizeStarted = false;
		var resizeInProg = false;
		var check = function () {
			if (resizeInProg) {
				resizeInProg = false;
				setTimeout(check, 250);
			} else {
				relayout(layoutingDuration);
				resizeStarted = false;
			}
		}
		return function () {
			resizeInProg = true;
			if (!resizeStarted) check();
			resizeStarted = true;
		}
	})())

	if ($('html').hasClass('lt-ie9')) {
		$('#search').html('');
	} else {
		initSearch();
	}

});

function relayout(duration) {
	documents.newLayout(currentLayout, duration);
}

function setLayout(layout, duration) {
	if (layout === currentLayout) return;
	if (currentLayout && currentLayout.hide) currentLayout.hide(duration);
	if (layout.show) layout.show(duration);
	if (currentLayout === undefined) {
		documents.newLayout(layout, 0);
	} else {
		documents.newLayout(layout, duration);
	}
	currentLayout = layout;
}

var layouts = {
	quality: {
		maxY: 0,
		show: function () {
			this.maxY = 0;
			var temp = [];
			for (var i = 0; i < $documents.length; i++) temp[i] = {index:i, quality:$documents[i].qualitySum};
			temp.sort(function (a,b) {
				return b.quality - a.quality;
			});
			var a = [];
			for (var i = 0; i < temp.length; i++) a[temp[i].index] = i;
			this.lookup = a;
		},
		projection: function () {
			var w0 = $('#canvas').innerWidth()-40;
			var w = w0 - 120;
			var n = Math.floor(w/41);
			if (n < 5) n = 5;
			var x0 = 100+(w-(n*41 - 20))/2;
			var lookup = this.lookup;
			var me = this;
			return function (index, data) {
				var i = lookup[index];
				var x = ((307-i) % n)*41+20 + x0;
				var y = Math.floor((307-i)/n)*50 + 20;
				if (me.maxY < y) me.maxY = y;
				return {x:x, y:y};
			}
		},
		lookup: []
	},
	quarterly: {
		maxY: 0,
		show: function (duration) {
			if (!this.labels) {
				this.maxY = 0;
				this.labels = $('

');
				var projection = this.projection();
				for (var i = 2005; i <= 2012; i++) {
					var p = projection(0, {w:0, j:i});
					this.labels.append($('
'+i+'
').css({top:p.y+1, left:20}));
					if (this.maxY < p.y) this.maxY = p.y+20;
				}
				canvas.append(this.labels);
			}
			this.labels.fadeIn(duration);
		},
		hide: function (duration) {
			if (this.labels) this.labels.fadeOut(duration);
		},
		labels: false,
		projection: function () {
			return function (i, data) {
				return {
					x: (data.w % 13)*41+120,
					y: (30-(Math.floor(data.w/13) + (data.j - 2005)*4))*50+30
				}
			}
		}
	}
};

<commit_msg>show according tabs in viewer for click on updates<commit_after>
var canvas, renderer, documents, documentsIndex, currentDoc, currentLayout;
var $pages = [];
var layoutingDuration = 500;
var disqus_shortname, disqus_identifier, disqus_url, disqus_title;

$(function () {
	initData();

	$('#layoutButtons').append($('<button class="btn active">Quartalsweise</button>').click(function () {
		setLayout(layouts.quarterly, layoutingDuration);
	}));
	$('#layoutButtons').append($('<button class="btn">Nach Qualität</button>').click(function () {
		setLayout(layouts.quality, layoutingDuration);
	}));
	/*$('#layoutButtons').append($('<button class="btn">Kartenansicht</button>'));*/
	$('#layoutButtons').append($('<button class="btn">Noch mehr Funktionen demnächst!</button>'));

	$('#intro-button').click(function(){
		$('#intro-controls').remove();
		$('#intro-more').fadeIn('fast');
	});

	$('#nav-intro').click(function(){

		if ($('#intro:hidden').length === 0) {
			$('#nav-intro').parent().removeClass('active');
			$('#intro').fadeOut('fast');
		} else {
			$('#intro').fadeIn('fast');
			$('#nav-intro').parent().addClass('active');
		}

	})

	$($updates.comments).each(function(idx,e){
		$('#sidebar-comments').append($('

'+e.article+'

'+e.date+'

'+e.content+'

'));
	});

	$($updates.changes).each(function(idx,e){
		var p = (e.change>=0) ? "+":"";
		$('#sidebar-changes').append($('

'+e.article+'

'+e.date+'

'+p+''+e.change+' Zeichen

'));
	});

	$('a','#sidebar-comments').click(function(evt){
		$('a','#lightbox-control-disqus').tab('show');
	});

	$('a','#sidebar-changes').click(function(){
		$('a','#lightbox-control-trans').tab('show');
	});

	$('#impressum').hide();

	$('#link-impressum').popover({
		html: true,
		content: $('#impressum').html(),
		placement: 'top'
	});

	$('#lightbox-controls a').click(function(e){
		$(this).blur();
		e.preventDefault();
	});

	$('#share-twitter').click(function(){
		window.open($(this).attr('href'), "share", "width=500,height=300,status=no,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	});
	$('#share-facebook').click(function(){
		window.open($(this).attr('href'), "share", "width=500,height=300,status=no,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	});
	$('#share-google').click(function(){
		window.open($(this).attr('href'), "share", "width=500,height=300,status=no,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	});

	$('#download-document').click(function(){
		var d = $('#lightbox').data();
		location.href="data/images/"+d.issue+"-"+d.page+".png?download";
	});
	$('#download-text').click(function(){
		var d = $('#lightbox').data();
		location.href="download/text/"+d.issue+".txt?download";
	});

	disqus_shortname = 'afgpa';
 	disqus_identifier = (location.hash === "" || location.hash === "#") ? "default" : location.hash;
 	disqus_url = location.href;
	disqus_title = "Kommentare";

	(function() {
		var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
		dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
		(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	})();

	canvas = $('#canvas');
	renderer = new Renderer(canvas);
	documents = new Documents(renderer);
	setLayout(layouts.quarterly, 0);

	hashCheck();

	$(window).bind('hashchange', function(e){
		hashCheck();
	});

	$(window).bind('onhashchange', function(e){
		hashCheck();
	});

	$(window).resize((function () {
		var resizeStarted = false;
		var resizeInProg = false;
		var check = function () {
			if (resizeInProg) {
				resizeInProg = false;
				setTimeout(check, 250);
			} else {
				relayout(layoutingDuration);
				resizeStarted = false;
			}
		}
		return function () {
			resizeInProg = true;
			if (!resizeStarted) check();
			resizeStarted = true;
		}
	})())

	if ($('html').hasClass('lt-ie9')) {
		$('#search').html('');
	} else {
		initSearch();
	}

});

function relayout(duration) {
	documents.newLayout(currentLayout, duration);
}

function setLayout(layout, duration) {
	if (layout === currentLayout) return;
	if (currentLayout && currentLayout.hide) currentLayout.hide(duration);
	if (layout.show) layout.show(duration);
	if (currentLayout === undefined) {
		documents.newLayout(layout, 0);
	} else {
		documents.newLayout(layout, duration);
	}
	currentLayout = layout;
}

var layouts = {
	quality: {
		maxY: 0,
		show: function () {
			this.maxY = 0;
			var temp = [];
			for (var i = 0; i < $documents.length; i++) temp[i] = {index:i, quality:$documents[i].qualitySum};
			temp.sort(function (a,b) {
				return b.quality - a.quality;
			});
			var a = [];
			for (var i = 0; i < temp.length; i++) a[temp[i].index] = i;
			this.lookup = a;
		},
		projection: function () {
			var w0 = $('#canvas').innerWidth()-40;
			var w = w0 - 120;
			var n = Math.floor(w/41);
			if (n < 5) n = 5;
			var x0 = 100+(w-(n*41 - 20))/2;
			var lookup = this.lookup;
			var me = this;
			return function (index, data) {
				var i = lookup[index];
				var x = ((307-i) % n)*41+20 + x0;
				var y = Math.floor((307-i)/n)*50 + 20;
				if (me.maxY < y) me.maxY = y;
				return {x:x, y:y};
			}
		},
		lookup: []
	},
	quarterly: {
		maxY: 0,
		show: function (duration) {
			if (!this.labels) {
				this.maxY = 0;
				this.labels = $('

');
				var projection = this.projection();
				for (var i = 2005; i <= 2012; i++) {
					var p = projection(0, {w:0, j:i});
					this.labels.append($('
'+i+'
').css({top:p.y+1, left:20}));
					if (this.maxY < p.y) this.maxY = p.y+20;
				}
				canvas.append(this.labels);
			}
			this.labels.fadeIn(duration);
		},
		hide: function (duration) {
			if (this.labels) this.labels.fadeOut(duration);
		},
		labels: false,
		projection: function () {
			return function (i, data) {
				return {
					x: (data.w % 13)*41+120,
					y: (30-(Math.floor(data.w/13) + (data.j - 2005)*4))*50+30
				}
			}
		}
	}
};

<|endoftext|>