<commit_before>'use strict';

function Label(text, color) {
  this.text = text;
  this.color = color;
}

Label.prototype.render = function() {
  var label = $("");
  label.html(this.text);
  label.css('background-color', "#" + this.color);
  return label;
};

function IssueDetailView(issue) {
  this.issue = issue;
}

IssueDetailView.prototype.renderAvatar = function() {
  return $("

");
};

IssueDetailView.prototype.renderLabels = function() {
  return _.map(this.issue.labels, function(label) {
    return new Label(label.name, label.color).render();
  });
};

IssueDetailView.prototype.renderIssueAuthorAndDate = function() {
  var authorLink = $("" + this.issue.user.login + "");
  var createdAt = $("<time class='issue-created-at'>"+ moment(this.issue.created_at).format("lll") +"</time>");

  var authorAndDate = $("

");
  authorAndDate.append(authorLink);
  authorAndDate.append(createdAt);
  var container = $("

");
  container.append(authorAndDate);
  return container;
};

IssueDetailView.prototype.render = function() {
  var container = $('.issue-detail');
  var backButton = $("

");
  backButton.click(this.hide);
  container.append(backButton);

  var title = $("
#"+ this.issue.number +""+ this.issue.title +"
");
  var text = $("

" + prepareBody(this.issue.body) + "

");
  var labels = $("

");
  labels.append(this.renderLabels());

  container.append(this.renderAvatar());
  container.append(title);
  container.append($("
"));
  container.append(labels);
  container.append(this.renderIssueAuthorAndDate());
  container.append(text);
  $(container).show();
  $(".issue-list").hide();

  function prepareBody(body) {
    return markdown.toHTML(body);
  }
}

IssueDetailView.prototype.hide = function() {
  $(".issue-list").show();
  $(".issue-detail").hide();
  $(".issue-detail").empty();
};

function IssueListView(issues, detailCallback) {
  this.issues = issues;
  this.detailCallback = detailCallback;
}

IssueListView.prototype.render = function(detailCallback) {
  $(".issue-list").empty();
  var sortedIssues = _.sortBy(this.issues, function(issue) { return issue.created_at; })
  var views = _.map(sortedIssues.reverse(), this.renderIssueView.bind(this));
  $(".issue-list").append(views);
};

IssueListView.prototype.renderIssueView = function(issue) {
  var container = $("");
  var heading = $("

")
  container.attr('id', issue.id);
  heading.html(buildHeading());
  container.append(heading);
  container.click(this.detailCallback);
  return container;

  function buildHeading() {
    if(isPR()) {
      return "#" + issue.number + " [Pull Request] " + issue.title;
    }
    return "#" + issue.number + " " + issue.title;
  }

  function isPR() {
    return issue.hasOwnProperty("pull_request");
  }
};

function IssueStore(repositoryName) {
  this.repositoryName = repositoryName;
  this.database = new PouchDB(this.repositoryName);
}

IssueStore.prototype.getIssue = function(id) {
  return this.database.get(id);
};

IssueStore.prototype.allIssues = function() {
  return this.database.allDocs({include_docs: true});
};

IssueStore.prototype.bulkInsertIssues = function(docs) {
  return this.database.bulkDocs(_.map(docs, setDocId));
  function setDocId(issue) {
    issue['_id'] = issue.id.toString();
    return issue;
  }
};

(function() {
  var issueDetailView = null;
  var database = null;

  function repoName() {
    return $('#repositoryName').val().toString();
  }

  function renderListView() {
    database.allIssues()
      .then(function(docs) {
        return Promise.resolve(_.map(docs.rows, function(d) { return d.doc; }));
      })
      .then(function(plainDocs) {
        new IssueListView(plainDocs, showIssueDetail).render();
      });

    function showIssueDetail(ev) {
      var id = $(this).attr('id');
      database.getIssue(id)
        .then(function(issue) {
          issueDetailView = new IssueDetailView(issue);
          issueDetailView.render();
        })
        .catch(function(err) {
          console.log("ERR", err);
          new ErrorBanner(err);
        });
    }
  }

  function fetchIssues(ev) {
    ev.preventDefault();
    var repo = repoName();
    if(!repo || repo === "") {
      return;
    }

    if(issueDetailView) {
      issueDetailView.hide();
      issueDetailView = null;
    }
    $(".issue-list").empty();

    var gh = new GitHub();
    gh.getIssues(repo).listIssues()
      .then(function(resultSet) {
        database = new IssueStore(repo);
        return database.bulkInsertIssues(resultSet.data);
      })
      .then(function(){
        renderListView();
        $(".add-new-repo").hide();
      })
      .catch(function(err) {
        console.log("ERR", err);
        new ErrorBanner("Fetching issues for " + repo + " failed");
      });
  }

  function loadAvailableRepositories() {
    PouchDB.allDbs().then(function (dbs) {
      var dbEntries = dbs.map(function(db) {
        var dbEntry = $("" + db + "");
        dbEntry.click(function(ev) {
          if(issueDetailView) {
            issueDetailView.hide();
            issueDetailView = null;
          }
          database = new IssueStore(db);
          renderListView();
          $('.available-repos').hide();
        });
        return dbEntry;
      });
      $(".repository-list").append(dbEntries);
    }).catch(function (err) {
      console.error("Failed to fetch all databases", err);
      new ErrorBanner("Failed to fetch all databases");
    });
  }

  function ErrorBanner(message) {
    this.timeoutHandler = null;

    $(".error-banner").html(message);
    $('.error-banner').show();

    this.hideError = function() {
      $(".error-banner").html('');
      $('.error-banner').hide();
      window.clearTimeout(this.timeoutHandler);
      this.timeoutHandler = null;
    }
    this.timeoutHandler = setTimeout(this.hideError, 1000 * 5);
  }

  $(document).ready(function() {
    $('.fetch-issues').click(fetchIssues);
    loadAvailableRepositories();
    $(".show-available-repo-button").click(function() {
      $(".available-repos").toggle();
      $(".add-new-repo").hide();
    });

    $(".add-repo-button").click(function() {
      $(".add-new-repo").toggle();
      $(".available-repos").hide();
    });
  });
})();<commit_msg>refactor fetching repository name<commit_after>'use strict';

function Label(text, color) {
  this.text = text;
  this.color = color;
}

Label.prototype.render = function() {
  var label = $("");
  label.html(this.text);
  label.css('background-color', "#" + this.color);
  return label;
};

function IssueDetailView(issue) {
  this.issue = issue;
}

IssueDetailView.prototype.renderAvatar = function() {
  return $("

");
};

IssueDetailView.prototype.renderLabels = function() {
  return _.map(this.issue.labels, function(label) {
    return new Label(label.name, label.color).render();
  });
};

IssueDetailView.prototype.renderIssueAuthorAndDate = function() {
  var authorLink = $("" + this.issue.user.login + "");
  var createdAt = $("<time class='issue-created-at'>"+ moment(this.issue.created_at).format("lll") +"</time>");

  var authorAndDate = $("

");
  authorAndDate.append(authorLink);
  authorAndDate.append(createdAt);
  var container = $("

");
  container.append(authorAndDate);
  return container;
};

IssueDetailView.prototype.render = function() {
  var container = $('.issue-detail');
  var backButton = $("

");
  backButton.click(this.hide);
  container.append(backButton);

  var title = $("
#"+ this.issue.number +""+ this.issue.title +"
");
  var text = $("

" + prepareBody(this.issue.body) + "

");
  var labels = $("

");
  labels.append(this.renderLabels());

  container.append(this.renderAvatar());
  container.append(title);
  container.append($("
"));
  container.append(labels);
  container.append(this.renderIssueAuthorAndDate());
  container.append(text);
  $(container).show();
  $(".issue-list").hide();

  function prepareBody(body) {
    return markdown.toHTML(body);
  }
}

IssueDetailView.prototype.hide = function() {
  $(".issue-list").show();
  $(".issue-detail").hide();
  $(".issue-detail").empty();
};

function IssueListView(issues, detailCallback) {
  this.issues = issues;
  this.detailCallback = detailCallback;
}

IssueListView.prototype.render = function(detailCallback) {
  $(".issue-list").empty();
  var sortedIssues = _.sortBy(this.issues, function(issue) { return issue.created_at; })
  var views = _.map(sortedIssues.reverse(), this.renderIssueView.bind(this));
  $(".issue-list").append(views);
};

IssueListView.prototype.renderIssueView = function(issue) {
  var container = $("");
  var heading = $("

")
  container.attr('id', issue.id);
  heading.html(buildHeading());
  container.append(heading);
  container.click(this.detailCallback);
  return container;

  function buildHeading() {
    if(isPR()) {
      return "#" + issue.number + " [Pull Request] " + issue.title;
    }
    return "#" + issue.number + " " + issue.title;
  }

  function isPR() {
    return issue.hasOwnProperty("pull_request");
  }
};

function IssueStore(repositoryName) {
  this.repositoryName = repositoryName;
  this.database = new PouchDB(this.repositoryName);
}

IssueStore.prototype.getIssue = function(id) {
  return this.database.get(id);
};

IssueStore.prototype.allIssues = function() {
  return this.database.allDocs({include_docs: true});
};

IssueStore.prototype.bulkInsertIssues = function(docs) {
  return this.database.bulkDocs(_.map(docs, setDocId));
  function setDocId(issue) {
    issue['_id'] = issue.id.toString();
    return issue;
  }
};

(function() {
  var issueDetailView = null;
  var database = null;

  function renderListView() {
    database.allIssues()
      .then(function(docs) {
        return Promise.resolve(_.map(docs.rows, function(d) { return d.doc; }));
      })
      .then(function(plainDocs) {
        new IssueListView(plainDocs, showIssueDetail).render();
      });

    function showIssueDetail(ev) {
      var id = $(this).attr('id');
      database.getIssue(id)
        .then(function(issue) {
          issueDetailView = new IssueDetailView(issue);
          issueDetailView.render();
        })
        .catch(function(err) {
          console.log("ERR", err);
          new ErrorBanner(err);
        });
    }
  }

  function fetchIssues(ev) {
    ev.preventDefault();
    var repo = $('#repositoryName').val().toString();
    if(!repo || repo === "") {
      return;
    }

    if(issueDetailView) {
      issueDetailView.hide();
      issueDetailView = null;
    }
    $(".issue-list").empty();

    var gh = new GitHub();
    gh.getIssues(repo).listIssues()
      .then(function(resultSet) {
        database = new IssueStore(repo);
        return database.bulkInsertIssues(resultSet.data);
      })
      .then(function(){
        renderListView();
        $(".add-new-repo").hide();
      })
      .catch(function(err) {
        console.log("ERR", err);
        new ErrorBanner("Fetching issues for " + repo + " failed");
      });
  }

  function loadAvailableRepositories() {
    PouchDB.allDbs().then(function (dbs) {
      var dbEntries = dbs.map(function(db) {
        var dbEntry = $("" + db + "");
        dbEntry.click(function(ev) {
          if(issueDetailView) {
            issueDetailView.hide();
            issueDetailView = null;
          }
          database = new IssueStore(db);
          renderListView();
          $('.available-repos').hide();
        });
        return dbEntry;
      });
      $(".repository-list").append(dbEntries);
    }).catch(function (err) {
      console.error("Failed to fetch all databases", err);
      new ErrorBanner("Failed to fetch all databases");
    });
  }

  function ErrorBanner(message) {
    this.timeoutHandler = null;

    $(".error-banner").html(message);
    $('.error-banner').show();

    this.hideError = function() {
      $(".error-banner").html('');
      $('.error-banner').hide();
      window.clearTimeout(this.timeoutHandler);
      this.timeoutHandler = null;
    }
    this.timeoutHandler = setTimeout(this.hideError, 1000 * 5);
  }

  $(document).ready(function() {
    $('.fetch-issues').click(fetchIssues);
    loadAvailableRepositories();
    $(".show-available-repo-button").click(function() {
      $(".available-repos").toggle();
      $(".add-new-repo").hide();
    });

    $(".add-repo-button").click(function() {
      $(".add-new-repo").toggle();
      $(".available-repos").hide();
    });
  });
})();<|endoftext|>


<commit_before>/*
 Copyright 2017 Eduworks Corporation and other contributing parties.

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

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

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

if (queryParams.select != null && queryParams.select != "")
    $("#selectButton").css("visibility", "visible");
if (queryParams.select != null)
    $("#selectButton").show().text(queryParams.select);

var loading = 0;
var searchCompetencies = [];

function searchFrameworks() {
    var searchTerm = $("#search").val();
    if (searchTerm == null || searchTerm == "")
        searchTerm = "*";
    hideAll();
    setTimeout(function () {
        $("#frameworks").html("");
        searchCompetencies = [];
        for (var i = 0; i < servers.length; i++) {
            frameworkSearch(servers[i], searchTerm);
            if (searchTerm != "*") {
                frameworkSearchByCompetency(servers[i], searchTerm);
            }
        }
    }, 500);
}

function frameworkSearchByCompetency(server, searchTerm) {
    loading++;
    EcCompetency.search(server, searchTerm, function (competencies) {
        var subSearch = "";
        for (var v = 0; v < competencies.length; v++) {
            searchCompetencies.push(competencies[v].shortId());
            if (subSearch != "")
                subSearch += " OR ";
            subSearch += "competency:\"" + competencies[v].shortId() + "\"";
            if (!EcRepository.shouldTryUrl(competencies[v].id)) {
                if (subSearch != "")
                    subSearch += " OR ";
                var m = forge.md.md5.create();
                m.update(competencies[v].id);
                var md5 = m.digest().toHex();
                subSearch += "competency:\"" + md5 + "\"";
            }
        }
        if (subSearch != "") {
            frameworkSearch(server, subSearch, searchTerm);
        }
        loading--;
        if (loading == 0) {
            if ($("#frameworks").html() == "")
                $("#frameworks").html("No frameworks found.");
            showAll();
        }
    }, console.log, {
        size: 5000
    });
}

function frameworkSearch(server, searchTerm, subsearchTerm) {
    loading++;
    var search = "";
    if (queryParams.filter != null)
        search = "(" + searchTerm + ") AND (" + queryParams.filter + ")";
    else
        search = searchTerm;
    EcFramework.search(server, search, function (frameworks) {
        for (var v = 0; v < frameworks.length; v++) {
            var framework = frameworks[v];
            if (framework.name === undefined || framework.name == null || framework.name == "")
                continue;
            if ($("[id='" + framework.shortId() + "']").length == 0) {
                var p = $("#frameworks").append("

").children().last();
                p.attr("id", framework.shortId());
                p.attr("subsearch", subsearchTerm);
                p.click(click);
                var title = p.children().first();
                title.text(framework.getName());
                if (subsearchTerm != null)
                    p.prepend("*Matches inside. ");
                var desc = p.children().last();
                desc.text(framework.getDescription());
                if (searchTerm != "*" && subsearchTerm == null)
                    p.mark(searchTerm);
            }
        }
        loading--;
        if (loading == 0) {
            if ($("#frameworks").html() == "")
                $("#frameworks").html("No frameworks found.");
            showAll();
        }
    }, console.log, {
        size: 5000
    });
}

function select() {
    var ary = [];
    $("input:checked").parent().each(function (f) {
        ary.push($(this).attr("id"));
        var rId = $(this).attr("relationId");
        if (rId != null && rId !== undefined && rId != "")
            ary.push(rId);
    });
    parent.postMessage({
        message: "selected",
        selected: ary
    }, queryParams.origin);
}

function click(evt) {
    var subsearchTerm = $(evt.target).attr("subsearch");
    if (subsearchTerm == null)
        subsearchTerm = $(evt.target).parent().attr("subsearch");
    if (subsearchTerm == null)
        subsearchTerm = $(evt.target).parent().parent().attr("subsearch");
    frameworkId = $(evt.target).attr("id");
    if (frameworkId == null)
        frameworkId = $(evt.target).parent().attr("id");
    if (frameworkId == null)
        frameworkId = $(evt.target).parent().parent().attr("id");
    repo = null;
    $("#mainbar").find("#loading").show();
    $("#tree").hide();
    $("#sidebar").hide({
        complete: function () {
            $("#mainbar").show({
                complete: function () {}
            });
        }
    });
    for (var i = 0; i < servers.length; i++)
        if (frameworkId.startsWith(servers[i])) {
            repo = servers[i];
        }
    if (repo == null) {
        repo = servers[0];
    }
    refreshFramework(subsearchTerm);
}

function refreshFramework(subsearch) {
    var me = this;
    $("#tree").html("");
    me.fetches = 0;
    EcFramework.get(frameworkId, function (framework) {
        $("#title").text(framework.getName());
        if (framework.competency == null)
            framework.competency = [];
        if (framework.relation == null)
            framework.relation = [];
        if (queryParams.link == "true")
            $("#frameworkLink").attr("href", framework.shortId()).show();
        repo.precache(framework.competency.concat(framework.relation), function (success) {
            if (framework.competency.length == 0) {
                if ($("#tree").html() == "")
                    $("#tree").html("

This framework is empty.
");
                showAll();
            } else {
                me.fetches += framework.competency.length;
                for (var i = 0; i < framework.competency.length; i++) {
                    refreshCompetency(me, framework, i, subsearch);
                }
            }
        });
    }, console.log);
}

fetchFailure = function (failure) {
    this.fetches--;
    error(failure);
    if (this.fetches == 0) {
        if ($("#tree").html() == "")
            $("#tree").html("

This framework is empty.
");
        showAll();
    }
};

function refreshCompetency(me, framework, i, subsearch) {
    EcCompetency.get(framework.competency[i], function (competency) {
        me.fetches--;
        if (subsearch != null)
            if (!EcArray.has(searchCompetencies, competency.shortId())) {
                if (me.fetches == 0) {
                    if ($("#tree").html() == "")
                        $("#tree").html("

This framework is empty.
");
                    showAll();
                }
                return;
            }
        var treeNode = $("#tree").append("

").children().last();
        treeNode.attr("id", competency.shortId());
        if (competency.description != null && competency.description != "NULL" && competency.description != competency.name)
            treeNode.prepend("").children().first().text(competency.getDescription());
        treeNode.prepend("").children().first().text(competency.getName());
        if (queryParams.link == "true")
            treeNode.prepend(" ").children().first().attr("href", competency.shortId());
        if (queryParams.select != null)
            treeNode.prepend("<input type='checkbox'>").children().first().click(function (evt) {
                console.log(evt);
                $(evt.target).parent().find("input").prop("checked", evt.target.checked);
            });
        if (subsearch != null)
            treeNode.mark(subsearch);
        if (me.fetches == 0) {
            if (framework.relation != undefined && framework.relation.length > 0) {
                me.fetches += framework.relation.length;
                for (var i = 0; i < framework.relation.length; i++) {
                    EcAlignment.get(framework.relation[i], function (relation) {
                        me.fetches--;
                        if (relation.source !== undefined) {
                            if (relation.relationType == "narrows") {
                                if (relation.source == relation.target) return;
                                $(".competency[id=\"" + relation.target + "\"]").children().last().append($(".competency[id=\"" + relation.source + "\"]").attr("relationId", relation.shortId()));
                                if (!$(".competency[id=\"" + relation.target + "\"]").hasClass("expandable"))
                                    $(".competency[id=\"" + relation.target + "\"]").addClass("expandable").prepend("").children().first().html(" ").click(function (evt) {
                                        $(this).parent().children("ul").slideToggle();

                                        if ($(this).hasClass('collapsed')) {
                                            $(this).removeClass('collapsed');
                                            $(this).html(' ');
                                        } else {
                                            $(this).addClass('collapsed');
                                            $(this).html(' ');
                                        }
                                    });
                            }
                            if (me.fetches == 0) {
                                me.fetches += framework.relation.length;
                                for (var i = 0; i < framework.relation.length; i++) {
                                    EcAlignment.get(framework.relation[i], function (relation) {
                                        me.fetches--;
                                        if (relation.source !== undefined) {
                                            if (relation.relationType == "requires") {
                                                if (relation.source == relation.target) return;
                                                if ($(".competency[id=\"" + relation.target + "\"]").prevAll(".competency[id=\"" + relation.source + "\"]").length > 0)
                                                    $(".competency[id=\"" + relation.target + "\"]").insertBefore($(".competency[id=\"" + relation.source + "\"]"));
                                            }
                                        }
                                        if (me.fetches == 0) {
                                            if ($("#tree").html() == "")
                                                $("#tree").html("

This framework is empty.
");
                                            showAll();
                                        }
                                    }, fetchFailure);
                                }
                            }
                        }
                    }, fetchFailure);
                }
            } else {
                if ($("#tree").html() == "")
                    $("#tree").html("

This framework is empty.
");
                showAll();
            }
        }
    }, fetchFailure);
}

function showAll() {
    var now = 1000 - (new Date().getTime() - ms);
    if (now < 0)
        now = 0;
    $("#mainbar").find("#loading").delay(now).hide({
        complete: function () {
            $("#tree").show({
                complete: function () {
                    $("#mainbar").find("#loading").hide();
                }
            });
        }
    });
    $("#sidebar").find("#loading").delay(now).hide({
        complete: function () {
            $("#frameworks").show({
                complete: function () {
                    $("#sidebar").find("#loading").hide();
                }
            });
        }
    });
}

var ms = 0;

function hideAll() {
    ms = new Date().getTime();
    $("#tree").hide({
        complete: function () {
            $("#sidebar").find("#loading").show({});
        }
    });
    $("#frameworks").hide({
        complete: function () {
            $("#mainbar").find("#loading").show({});
        }
    });
}

$("#search").keyup(function (event) {
    if (event.keyCode == '13') {
        searchFrameworks();
    }
    return false;
});

$("#sidebar").show({});
searchFrameworks();
<commit_msg>Fixing mitigation of #16<commit_after>/*
 Copyright 2017 Eduworks Corporation and other contributing parties.

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

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

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

if (queryParams.select != null && queryParams.select != "")
    $("#selectButton").css("visibility", "visible");
if (queryParams.select != null)
    $("#selectButton").show().text(queryParams.select);

var loading = 0;
var searchCompetencies = [];

function searchFrameworks() {
    var searchTerm = $("#search").val();
    if (searchTerm == null || searchTerm == "")
        searchTerm = "*";
    hideAll();
    setTimeout(function () {
        $("#frameworks").html("");
        searchCompetencies = [];
        for (var i = 0; i < servers.length; i++) {
            frameworkSearch(servers[i], searchTerm);
            if (searchTerm != "*") {
                frameworkSearchByCompetency(servers[i], searchTerm);
            }
        }
    }, 500);
}

function frameworkSearchByCompetency(server, searchTerm) {
    loading++;
    EcCompetency.search(server, searchTerm, function (competencies) {
        var subSearch = "";
        for (var v = 0; v < competencies.length; v++) {
            searchCompetencies.push(competencies[v].shortId());
            if (subSearch != "")
                subSearch += " OR ";
            subSearch += "competency:\"" + competencies[v].shortId() + "\"";
            if (!EcRepository.shouldTryUrl(competencies[v].id)) {
                if (subSearch != "")
                    subSearch += " OR ";
                var m = forge.md.md5.create();
                m.update(competencies[v].id);
                var md5 = m.digest().toHex();
                subSearch += "competency:\"" + md5 + "\"";
            }
        }
        if (subSearch != "") {
            frameworkSearch(server, subSearch, searchTerm);
        }
        loading--;
        if (loading == 0) {
            if ($("#frameworks").html() == "")
                $("#frameworks").html("No frameworks found.");
            showAll();
        }
    }, console.log, {
        size: 5000
    });
}

function frameworkSearch(server, searchTerm, subsearchTerm) {
    loading++;
    var search = "";
    if (queryParams.filter != null)
        search = "(" + searchTerm + ") AND (" + queryParams.filter + ")";
    else
        search = searchTerm;
    EcFramework.search(server, search, function (frameworks) {
        for (var v = 0; v < frameworks.length; v++) {
            var framework = frameworks[v];
            if (framework.name === undefined || framework.name == null || framework.name == "")
                continue;
            if ($("[id='" + framework.shortId() + "']").length == 0) {
                var p = $("#frameworks").append("

").children().last();
                p.attr("id", framework.shortId());
                p.attr("subsearch", subsearchTerm);
                p.click(click);
                var title = p.children().first();
                title.text(framework.getName());
                if (subsearchTerm != null)
                    p.prepend("*Matches inside. ");
                var desc = p.children().last();
                desc.text(framework.getDescription());
                if (searchTerm != "*" && subsearchTerm == null)
                    p.mark(searchTerm);
            }
        }
        loading--;
        if (loading == 0) {
            if ($("#frameworks").html() == "")
                $("#frameworks").html("No frameworks found.");
            showAll();
        }
    }, console.log, {
        size: 5000
    });
}

function select() {
    var ary = [];
    $("input:checked").parent().each(function (f) {
        ary.push($(this).attr("id"));
        var rId = $(this).attr("relationId");
        if (rId != null && rId !== undefined && rId != "")
            ary.push(rId);
    });
    parent.postMessage({
        message: "selected",
        selected: ary
    }, queryParams.origin);
}

function click(evt) {
    var subsearchTerm = $(evt.target).attr("subsearch");
    if (subsearchTerm == null)
        subsearchTerm = $(evt.target).parent().attr("subsearch");
    if (subsearchTerm == null)
        subsearchTerm = $(evt.target).parent().parent().attr("subsearch");
    frameworkId = $(evt.target).attr("id");
    if (frameworkId == null)
        frameworkId = $(evt.target).parent().attr("id");
    if (frameworkId == null)
        frameworkId = $(evt.target).parent().parent().attr("id");
    repo = null;
    $("#mainbar").find("#loading").show();
    $("#tree").hide();
    $("#sidebar").hide({
        complete: function () {
            $("#mainbar").show({
                complete: function () {}
            });
        }
    });
    for (var i = 0; i < servers.length; i++)
        if (frameworkId.startsWith(servers[i])) {
            repo = servers[i];
        }
    if (repo == null) {
        repo = servers[0];
    }
    refreshFramework(subsearchTerm);
}

function refreshFramework(subsearch) {
    var me = this;
    $("#tree").html("");
    me.fetches = 0;
    EcFramework.get(frameworkId, function (framework) {
        $("#title").text(framework.getName());
        if (framework.competency == null)
            framework.competency = [];
        if (framework.relation == null)
            framework.relation = [];
        if (queryParams.link == "true")
            $("#frameworkLink").attr("href", framework.shortId()).show();
        repo.precache(framework.competency.concat(framework.relation), function (success) {
            if (framework.competency.length == 0) {
                if ($("#tree").html() == "")
                    $("#tree").html("

This framework is empty.
");
                showAll();
            } else {
                me.fetches += framework.competency.length;
                for (var i = 0; i < framework.competency.length; i++) {
                    refreshCompetency(me, framework, i, subsearch);
                }
            }
        });
    }, console.log);
}

fetchFailure = function (failure) {
    this.fetches--;
    error(failure);
    if (this.fetches == 0) {
        if ($("#tree").html() == "")
            $("#tree").html("

This framework is empty.
");
        showAll();
    }
};

function refreshCompetency(me, framework, i, subsearch) {
    EcCompetency.get(framework.competency[i], function (competency) {
        me.fetches--;
        if (subsearch != null)
            if (!EcArray.has(searchCompetencies, competency.shortId())) {
                if (me.fetches == 0) {
                    if ($("#tree").html() == "")
                        $("#tree").html("

This framework is empty.
");
                    showAll();
                }
                return;
            }
        var treeNode = $("#tree").append("

").children().last();
        treeNode.attr("id", competency.shortId());
        if (competency.description != null && competency.description != "NULL" && competency.description != competency.name)
            treeNode.prepend("").children().first().text(competency.getDescription());
        treeNode.prepend("").children().first().text(competency.getName());
        if (queryParams.link == "true")
            treeNode.prepend(" ").children().first().attr("href", competency.shortId());
        if (queryParams.select != null)
            treeNode.prepend("<input type='checkbox'>").children().first().click(function (evt) {
                console.log(evt);
                $(evt.target).parent().find("input").prop("checked", evt.target.checked);
            });
        if (subsearch != null)
            treeNode.mark(subsearch);
        if (me.fetches == 0) {
            if (framework.relation != undefined && framework.relation.length > 0) {
                me.fetches += framework.relation.length;
                for (var i = 0; i < framework.relation.length; i++) {
                    EcAlignment.get(framework.relation[i], function (relation) {
                        me.fetches--;
                        if (relation.source !== undefined) {
                            if (relation.relationType == "narrows") {
                                if (relation.source != relation.target) {
                                    $(".competency[id=\"" + relation.target + "\"]").children().last().append($(".competency[id=\"" + relation.source + "\"]").attr("relationId", relation.shortId()));
                                    if (!$(".competency[id=\"" + relation.target + "\"]").hasClass("expandable"))
                                        $(".competency[id=\"" + relation.target + "\"]").addClass("expandable").prepend("").children().first().html(" ").click(function (evt) {
                                            $(this).parent().children("ul").slideToggle();

                                            if ($(this).hasClass('collapsed')) {
                                                $(this).removeClass('collapsed');
                                                $(this).html(' ');
                                            } else {
                                                $(this).addClass('collapsed');
                                                $(this).html(' ');
                                            }
                                        });
                                }
                            }
                            if (me.fetches == 0) {
                                me.fetches += framework.relation.length;
                                for (var i = 0; i < framework.relation.length; i++) {
                                    EcAlignment.get(framework.relation[i], function (relation) {
                                        me.fetches--;
                                        if (relation.source !== undefined) {
                                            if (relation.relationType == "requires") {
                                                if (relation.source != relation.target) {
                                                    if ($(".competency[id=\"" + relation.target + "\"]").prevAll(".competency[id=\"" + relation.source + "\"]").length > 0)
                                                        $(".competency[id=\"" + relation.target + "\"]").insertBefore($(".competency[id=\"" + relation.source + "\"]"));
                                                }
                                            }
                                        }
                                        if (me.fetches == 0) {
                                            if ($("#tree").html() == "")
                                                $("#tree").html("

This framework is empty.
");
                                            showAll();
                                        }
                                    }, fetchFailure);
                                }
                            }
                        }
                    }, fetchFailure);
                }
            } else {
                if ($("#tree").html() == "")
                    $("#tree").html("

This framework is empty.
");
                showAll();
            }
        }
    }, fetchFailure);
}

function showAll() {
    var now = 1000 - (new Date().getTime() - ms);
    if (now < 0)
        now = 0;
    $("#mainbar").find("#loading").delay(now).hide({
        complete: function () {
            $("#tree").show({
                complete: function () {
                    $("#mainbar").find("#loading").hide();
                }
            });
        }
    });
    $("#sidebar").find("#loading").delay(now).hide({
        complete: function () {
            $("#frameworks").show({
                complete: function () {
                    $("#sidebar").find("#loading").hide();
                }
            });
        }
    });
}

var ms = 0;

function hideAll() {
    ms = new Date().getTime();
    $("#tree").hide({
        complete: function () {
            $("#sidebar").find("#loading").show({});
        }
    });
    $("#frameworks").hide({
        complete: function () {
            $("#mainbar").find("#loading").show({});
        }
    });
}

$("#search").keyup(function (event) {
    if (event.keyCode == '13') {
        searchFrameworks();
    }
    return false;
});

$("#sidebar").show({});
searchFrameworks();
<|endoftext|>


<commit_before>"use strict";

(function(win, doc, nav) {
    var canvas, context, width, height, num, size, resolution;
    var Spiral = function() {
        var radius = resolution || 6;
        //init is -1,-1
        var point = {
            x : 0,
            y : 0
        };
        //0:right;1:up,2:left,3:down
        var direction = {
            0 : {
                "x" : 1,
                "y" : 0
            },
            1 : {
                "x" : 0,
                "y" : 1
            },
            2 : {
                "x" : -1,
                "y" : 0
            },
            3 : {
                "x" : 0,
                "y" : -1
            }
        }
        var drawPoint = function(opt) {
            opt = opt || {};
            opt.x = opt.x || 0;
            opt.y = opt.y || 0;
            opt.radius = opt.radius || radius / 2;
            opt.color = opt.color || 'red';
            if (opt.x > width || opt.y > height) {
                return false;
            }
            context.beginPath();
            var coord = {
                x : (width / 2) + (opt.x * radius * 2),
                y : (height / 2) + (-1 * opt.y * radius * 2)
            };
            context.arc(coord.x, coord.y, opt.radius, 0, 2 * Math.PI, false);
            context.fillStyle = opt.color;
            context.fill();
            return true;
        };
        var setDirection = function(point, dirIndex) {
            if ((dirIndex >= 0 || dirIndex < 4)) {
                point.x += direction[dirIndex].x;
                point.y += direction[dirIndex].y;
            }
            return point;
        }
        var nextDirection = function(dir) {
            dir += 1;
            if (dir > 3) {
                dir = 0;
            }
            return dir;
        };
        var generate = function() {
            var directionSteps = 1;
            var directionIndex = 0;
            //var i = 1;
            var i = num;
            drawPoint({
                x : point.x,
                y : point.y,
                color : '#f00',
                radius : radius
            });
            var cont = true;
            if (window.Worker) {
                //creates a worker
                var primeWorker = new Worker("js/worker.prime.js");
                primeWorker.onmessage = function(oEvent) {
                    var data = JSON.parse(oEvent.data);
                    var pointToDraw = data;
                    drawPoint(pointToDraw);
                };
            }
            do {
                for (var k = 0; k < 2; k++) {
                    for (var ds = 0; ds < directionSteps; ds += 1) {
                        i += 1;
                        //increment number
                        point = setDirection(point, directionIndex);

                        if (window.Worker) {
                            //post to worker
                            primeWorker.postMessage(JSON.stringify({
                                point : point,
                                number : i,
                                radius : radius
                            }));
                        } else {
                            //no web worker :()
                            var pointToDraw = {};
                            if (isPrime(i)) {
                                pointToDraw = {
                                    x : point.x,
                                    y : point.y,
                                    color : '#000',
                                    radius : radius / 2
                                };
                            } else {
                                pointToDraw = {
                                    x : point.x,
                                    y : point.y,
                                    color : '#ddd',
                                    radius : 1
                                };
                            }
                            drawPoint(pointToDraw);
                        }

                        if (i > ((width / radius) * (width / radius) - 1)) {
                            cont = false;
                            return;
                        }
                    }
                    directionIndex = nextDirection(directionIndex);
                }
                directionSteps += 1;
            } while (cont) ;
        }
        return {
            generate : generate
        }
    };
    //is prime number?
    var isPrime = function(num) {
        if (num < 2)
            return false;
        for (var i = 2; i < num; i++) {
            if (num % i == 0)
                return false;
        }
        return true;
    }
    //generate
    var generate = function() {
        try {
            $('#canvas').hide();
            $('#error').hide();
            num = parseInt($('#startNum').val(), 10);
            if (num < 1) {
                throw 'Starting number must be > 0'
            }
            var canvasSize = parseInt($('#canvasSize').val(), 10);
            if (canvasSize < 1) {
                throw 'Size of spiral must be > 0'
            }
            resolution = 6;
            canvas = doc.getElementById("canvas");
            canvas.width = (canvasSize * resolution * 2);
            if (canvas.width != canvas.height) {
                canvas.height = canvas.width;
            }
            width = parseInt(canvas.width, 10);
            height = parseInt(canvas.height, 10)
            context = canvas.getContext("2d");
            context.rect(0, 0, width, height);
            context.fillStyle = '#fff';
            context.fill();
            var spiral = new Spiral();
            spiral.generate();
            $('#canvas').css('width', '100%');
            $('#canvas').show();
        } catch(e) {
            console.log(e);
            $('#error').html('Hmm... ' + e);
            $('#error').fadeIn();
        }

    }
    addEventListener("DOMContentLoaded", function() {
        $('#generateButton').click(function() {
            generate();
        });
        $('#canvas').click(function(elm) {
            var url = canvas.toDataURL("image/png");
            window.open(url, 'Ulam spiral');

        });
        generate();
    });

})(window, document, navigator);
<commit_msg>Calculating primes with web worker<commit_after>"use strict";

(function(win, doc, nav) {
    var canvas, context, width, height, num, size, resolution;
    var Spiral = function() {
        var radius = (resolution / 2) || 6;
        //init is -1,-1
        var point = {
            x : 0,
            y : 0
        };
        //0:right;1:up,2:left,3:down
        var direction = {
            0 : {
                "x" : 1,
                "y" : 0
            },
            1 : {
                "x" : 0,
                "y" : 1
            },
            2 : {
                "x" : -1,
                "y" : 0
            },
            3 : {
                "x" : 0,
                "y" : -1
            }
        }
        var drawPoint = function(opt) {
            opt = opt || {};
            opt.x = opt.x || 0;
            opt.y = opt.y || 0;
            opt.radius = opt.radius || radius / 2;
            opt.color = opt.color || 'red';
            if (opt.x > width || opt.y > height) {
                return false;
            }
            context.beginPath();
            var coord = {
                x : (width / 2) + (opt.x * radius * 2),
                y : (height / 2) + (-1 * opt.y * radius * 2)
            };
            context.arc(coord.x, coord.y, opt.radius, 0, 2 * Math.PI, false);
            context.fillStyle = opt.color;
            context.fill();
            return true;
        };
        var setDirection = function(point, dirIndex) {
            if ((dirIndex >= 0 || dirIndex < 4)) {
                point.x += direction[dirIndex].x;
                point.y += direction[dirIndex].y;
            }
            return point;
        }
        var nextDirection = function(dir) {
            dir += 1;
            if (dir > 3) {
                dir = 0;
            }
            return dir;
        };
        var generate = function() {
            var directionSteps = 1;
            var directionIndex = 0;
            //var i = 1;
            var i = num;
            drawPoint({
                x : point.x,
                y : point.y,
                color : '#f00',
                radius : radius
            });
            var cont = true;
            if (window.Worker) {
                //creates a worker
                var primeWorker = new Worker("js/worker.prime.js");
                primeWorker.onmessage = function(oEvent) {
                    var data = JSON.parse(oEvent.data);
                    var pointToDraw = data;
                    drawPoint(pointToDraw);
                };
            }
            do {
                for (var k = 0; k < 2; k++) {
                    for (var ds = 0; ds < directionSteps; ds += 1) {
                        i += 1;
                        //increment number
                        point = setDirection(point, directionIndex);

                        if (window.Worker) {
                            //post to worker
                            primeWorker.postMessage(JSON.stringify({
                                point : point,
                                number : i,
                                radius : radius
                            }));
                        } else {
                            //no web worker :()
                            var pointToDraw = {};
                            if (isPrime(i)) {
                                pointToDraw = {
                                    x : point.x,
                                    y : point.y,
                                    color : '#000',
                                    radius : radius / 2
                                };
                            } else {
                                pointToDraw = {
                                    x : point.x,
                                    y : point.y,
                                    color : '#ddd',
                                    radius : 1
                                };
                            }
                            drawPoint(pointToDraw);
                        }

                        if (i > ((width / radius) * (width / radius) - 1)) {
                            cont = false;
                            return;
                        }
                    }
                    directionIndex = nextDirection(directionIndex);
                }
                directionSteps += 1;
            } while (cont) ;
        }
        return {
            generate : generate
        }
    };
    //is prime number?
    var isPrime = function(num) {
        if (num < 2)
            return false;
        for (var i = 2; i < num; i++) {
            if (num % i == 0)
                return false;
        }
        return true;
    }
    //generate
    var generate = function() {
        try {
            $('#canvas').hide();
            $('#error').hide();
            num = parseInt($('#startNum').val(), 10);
            if (num < 1) {
                throw 'Starting number must be > 0'
            }
            var canvasSize = parseInt($('#canvasSize').val(), 10);
            if (canvasSize < 1) {
                throw 'Size of spiral must be > 0'
            }
            resolution = 12;
            canvas = doc.getElementById("canvas");
            canvas.width = (canvasSize * resolution);
            if (canvas.width != canvas.height) {
                canvas.height = canvas.width;
            }
            width = parseInt(canvas.width, 10);
            height = parseInt(canvas.height, 10)
            context = canvas.getContext("2d");
            context.rect(0, 0, width, height);
            context.fillStyle = '#fff';
            context.fill();
            var spiral = new Spiral();
            spiral.generate();
            $('#canvas').css('width', '100%');
            $('#canvas').show();
        } catch(e) {
            console.log(e);
            $('#error').html('Hmm... ' + e);
            $('#error').fadeIn();
        }

    }
    addEventListener("DOMContentLoaded", function() {
        $('#generateButton').click(function() {
            generate();
        });
        $('#canvas').click(function(elm) {
            var url = canvas.toDataURL("image/png");
            window.open(url, 'Ulam spiral');

        });
        generate();
    });

})(window, document, navigator);
<|endoftext|>


<commit_before>requirejs.config({
	shim: {
		'facebook': {
			export: 'FB'
		},
		'backbone': {
			deps: ["underscore", "jquery"],
			exports: "Backbone"
		},
		'underscore': {
			exports: "_"
		}
	},
	"paths": {
		"jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min",
		"facebook": "//connect.facebook.net/en_US/all",
		"underscore": "libs/underscore.min",
		"backbone": "libs/backbone.min",
		"json": "libs/json2",
		"text": "libs/text",

		'models': 'app/models/modelIndex',
		'model_want': 'app/models/want',
		'model_wants': 'app/models/wants',
		'model_search_item': 'app/models/searchItem',
		'model_search_results': 'app/models/searchResults',

		'views': 'app/views/viewIndex',
		'view_main': 'app/views/main',
		'view_search': 'app/views/search',

		'utils': 'app/utils'
	}
});

requirejs(["jquery", "underscore", "backbone", "views", "utils"], function($, _, Backbone, Views, Utils) {

	var App = _.extend({
		init: function() {
			FB.init({
				appId: '509825915758193',
				channelUrl: '//http://crowdbuy.sapuan.org/channel.html',
			});
			FB.login(function() {}, {
				scope: 'read_friendlists, user_about_me'
			});

			$('#loginbutton,#feedbutton').removeAttr('disabled');

			FB.getLoginStatus((function(that) {
				return function(response) {
					if (response.status === 'connected') {
						// Handle authentication here.
						Utils.logIn();

						FB.api('/me', function(response) {
							var welcomeString = this._randomWelcome();
							$('#welcome').html(welcomeString + response.first_name + '!');
						});
					} else {
						alert("Whoa, something went wrong! Try refreshing this page.");
					}

				};
			})(this));

			this.loadHome();

			this.SearchPane = new Views.SearchForm({
				el: '#search-bar',
				id: 'search'
			});

			this.listenTo(this.SearchPane, 'changeView', this.changeView);
			this.listenTo(this.SearchPane, 'goHome', this.loadHome);
			this.listenTo(this.view, 'changeView', this.changeView);
		},

		loadHome: function() {
			this.changeView(Views.Main);
		},

		changeView: function(newView) {
			if (typeof this.view !== 'undefined') {
				this.stopListening(this.view);
			}
			this.view = Utils.loadView(newView);
			this.listenTo(this.view, 'changeView', this.changeView);
			this.listenTo(this.view, 'goHome', this.loadHome);
		},

		_randomWelcome: function() {
			var welcomeMessages = ["Welcome, ", "Hey ", "Hello ", "Hi "];
			var rand = Math.floor(Math.random() * 4);
			return welcomeMessages[rand];
		}

	}, Backbone.Events);
	App.init();

});<commit_msg>Fix context.<commit_after>requirejs.config({
	shim: {
		'facebook': {
			export: 'FB'
		},
		'backbone': {
			deps: ["underscore", "jquery"],
			exports: "Backbone"
		},
		'underscore': {
			exports: "_"
		}
	},
	"paths": {
		"jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min",
		"facebook": "//connect.facebook.net/en_US/all",
		"underscore": "libs/underscore.min",
		"backbone": "libs/backbone.min",
		"json": "libs/json2",
		"text": "libs/text",

		'models': 'app/models/modelIndex',
		'model_want': 'app/models/want',
		'model_wants': 'app/models/wants',
		'model_search_item': 'app/models/searchItem',
		'model_search_results': 'app/models/searchResults',

		'views': 'app/views/viewIndex',
		'view_main': 'app/views/main',
		'view_search': 'app/views/search',

		'utils': 'app/utils'
	}
});

requirejs(["jquery", "underscore", "backbone", "views", "utils"], function($, _, Backbone, Views, Utils) {

	var App = _.extend({
		init: function() {
			FB.init({
				appId: '509825915758193',
				channelUrl: '//http://crowdbuy.sapuan.org/channel.html',
			});
			FB.login(function() {}, {
				scope: 'read_friendlists, user_about_me'
			});

			$('#loginbutton,#feedbutton').removeAttr('disabled');

			FB.getLoginStatus((function(that) {
				return function(response) {
					if (response.status === 'connected') {
						// Handle authentication here.
						Utils.logIn();

						FB.api('/me', function(response) {
							var welcomeString = that._randomWelcome();
							$('#welcome').html(welcomeString + response.first_name + '!');
						});
					} else {
						alert("Whoa, something went wrong! Try refreshing this page.");
					}

				};
			})(this));

			this.loadHome();

			this.SearchPane = new Views.SearchForm({
				el: '#search-bar',
				id: 'search'
			});

			this.listenTo(this.SearchPane, 'changeView', this.changeView);
			this.listenTo(this.SearchPane, 'goHome', this.loadHome);
			this.listenTo(this.view, 'changeView', this.changeView);
		},

		loadHome: function() {
			this.changeView(Views.Main);
		},

		changeView: function(newView) {
			if (typeof this.view !== 'undefined') {
				this.stopListening(this.view);
			}
			this.view = Utils.loadView(newView);
			this.listenTo(this.view, 'changeView', this.changeView);
			this.listenTo(this.view, 'goHome', this.loadHome);
		},

		_randomWelcome: function() {
			var welcomeMessages = ["Welcome, ", "Hey ", "Hello ", "Hi "];
			var rand = Math.floor(Math.random() * 4);
			return welcomeMessages[rand];
		}

	}, Backbone.Events);
	App.init();

});<|endoftext|>


<commit_before>import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Root from './components/Root';

export default function render(locals, callback) {
  var html = ReactDOMServer.renderToStaticMarkup(React.createElement(Root, locals))
  callback(null, '<!DOCTYPE html>' + html)
};
<commit_msg>Now import routes file<commit_after>import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Root from './components/Root';
import Routes from './routes';

export default function render(locals, callback) {
  var html = ReactDOMServer.renderToStaticMarkup(React.createElement(Root, locals))
  callback(null, '<!DOCTYPE html>' + html)
};
<|endoftext|>


<commit_before>/**
 * Created by amirchervinsky on 1/31/16.
 */
(function($) {
	$(window).load(function() {

		var colorThief = new ColorThief();
		var active = false;

		var sampleIntervalId = null;
		var refreshInterval = 500;
		var audioContext = null;
		var analyzerNode = null;
		var mediaSourceNode = null;
		var animationId = null;
		var status = 0; //flag for sound is playing 1 or stopped 0
		var allCapsReachBottom = false;
		var canvas = null;

		var targetDiv = $(".spectrumAnalyzer");
		var meterWidth = targetDiv.width() / 72; // show 72 bars

		targetDiv.append('<canvas id="canvas" width="' + targetDiv.width() + '" height="' + targetDiv.height() + '"></canvas>');
		canvas = targetDiv.find("#canvas").get(0);
		var vid = $("#vid").get(0);

		if (prepareAPI()){
			mediaSourceNode = audioContext.createMediaElementSource(vid);
			analyzerNode = audioContext.createAnalyser();
			mediaSourceNode.connect(analyzerNode);
			analyzerNode.connect(audioContext.destination);
		}

		function prepareAPI(){
			window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
			window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
			window.cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame;
			try {
				audioContext = new AudioContext();
				return true;
			} catch (e) {
				console.log('spectrumAnalyzer::Your browser does not support AudioContext');
				return false;
			}
		}

		function doSample(){
			var sample = new Float32Array(analyzerNode.frequencyBinCount);
			analyzerNode.getFloatFrequencyData(sample);
			if (animationId !== null) {
				cancelAnimationFrame(animationId);
			}

			var frameColors = colorThief.getPalette(vid,3);
			if (frameColors){
				var color1 = frameColors[0];
				var color2 = frameColors[1];
				var color3 = frameColors[2];
				var hex1 = rgbToHex(color1[0],color1[1],color1[2]);
				var hex2 = rgbToHex(color2[0],color2[1],color2[2]);
				var hex3 = rgbToHex(color3[0],color3[1],color3[2]);
			}
			drawSpectrum(hex1, hex2, hex3);
		}

		function drawSpectrum(hex1, hex2, hex3){
			var	cwidth = canvas.width;
			var	cheight = canvas.height - 2;
			var	gap = 2; //gap between meters
			var	capHeight = 2;
			var	capStyle = '#fff';
			var	meterNum = 800 / (10 + 2); //count of the meters
			var	capYPositionArray = [];    //store the vertical position of hte caps for the previous frame
			var ctx = canvas.getContext('2d');
			var	gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);

				if (hex1){
					gradient.addColorStop(1, hex1);
					gradient.addColorStop(0.5, hex2);
					gradient.addColorStop(0, hex3);
				}else{
					gradient.addColorStop(1, '#000');
					gradient.addColorStop(0.5, '#000');
					gradient.addColorStop(0, '#000');
				}

			var drawMeter = function() {
				var array = new Uint8Array(analyzerNode.frequencyBinCount);
				analyzerNode.getByteFrequencyData(array);
				if (status === 0) {
					//fix when some sounds end the value still not back to zero
					for (var i = array.length - 1; i >= 0; i--) {
						array[i] = 0;
					};
					allCapsReachBottom = true;
					for (var i = capYPositionArray.length - 1; i >= 0; i--) {
						allCapsReachBottom = allCapsReachBottom && (capYPositionArray[i] === 0);
					};
					if (allCapsReachBottom) {
						cancelAnimationFrame(animationId); //since the sound is top and animation finished, stop the requestAnimation to prevent potential memory leak,THIS IS VERY IMPORTANT!
						return;
					};
				};
				var step = 10;// Math.round(array.length / meterNum); //sample limited data from the total array
				ctx.clearRect(0, 0, cwidth, cheight);
				for (var i = 0; i < meterNum; i++) {
					var value = array[i * step];
					if (capYPositionArray.length < Math.round(meterNum)) {
						capYPositionArray.push(value);
					};
					ctx.fillStyle = capStyle;
					//draw the cap, with transition effect
					if (value < capYPositionArray[i]) {
						ctx.fillRect(i * (meterWidth+gap), cheight - (--capYPositionArray[i]), meterWidth, capHeight);
					} else {
						ctx.fillRect(i * (meterWidth+gap), cheight - value, meterWidth, capHeight);
						capYPositionArray[i] = value;
					};
					ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
					ctx.fillRect(i * (meterWidth+gap) /*meterWidth+gap*/ , cheight - value + capHeight, meterWidth, cheight); //the meter
				}
				animationId = requestAnimationFrame(drawMeter);
			}
			animationId = requestAnimationFrame(drawMeter);
		}

		function rgbToHex (r, g, b) {
			return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
		}

		status = 1;
		sampleIntervalId = setInterval(function(){
			doSample();
		}, refreshInterval);

	});
})(jQuery);
<commit_msg>better variables naming<commit_after>/**
 * Created by amirchervinsky on 1/31/16.
 */
(function($) {
	$(window).load(function() {

		var colorThief = new ColorThief();
		var active = false;

		var sampleIntervalId = null;
		var refreshInterval = 500;
		var audioContext = null;
		var analyzerNode = null;
		var mediaSourceNode = null;
		var animationId = null;
		var status = 0; //flag for sound is playing 1 or stopped 0
		var allCapsReachBottom = false;
		var canvas = null;

		var targetDiv = $(".spectrumAnalyzer");
		var numberOfBars = 62; // show 62 bars
		var	gap = 2; //gap between bars
		var meterWidth = (targetDiv.width() / numberOfBars) - gap;

		targetDiv.append('<canvas id="canvas" width="' + targetDiv.width() + '" height="' + targetDiv.height() + '"></canvas>');
		canvas = targetDiv.find("#canvas").get(0);
		var vid = $("#vid").get(0);

		if (prepareAPI()){
			mediaSourceNode = audioContext.createMediaElementSource(vid);
			analyzerNode = audioContext.createAnalyser();
			mediaSourceNode.connect(analyzerNode);
			analyzerNode.connect(audioContext.destination);
		}

		function prepareAPI(){
			window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext;
			window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame;
			window.cancelAnimationFrame = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.mozCancelAnimationFrame || window.msCancelAnimationFrame;
			try {
				audioContext = new AudioContext();
				return true;
			} catch (e) {
				console.log('spectrumAnalyzer::Your browser does not support AudioContext');
				return false;
			}
		}

		function doSample(){
			var sample = new Float32Array(analyzerNode.frequencyBinCount);
			analyzerNode.getFloatFrequencyData(sample);
			if (animationId !== null) {
				cancelAnimationFrame(animationId);
			}

			var frameColors = colorThief.getPalette(vid,3);
			if (frameColors){
				var color1 = frameColors[0];
				var color2 = frameColors[1];
				var color3 = frameColors[2];
				var hex1 = rgbToHex(color1[0],color1[1],color1[2]);
				var hex2 = rgbToHex(color2[0],color2[1],color2[2]);
				var hex3 = rgbToHex(color3[0],color3[1],color3[2]);
			}
			drawSpectrum(hex1, hex2, hex3);
		}

		function drawSpectrum(hex1, hex2, hex3){
			var	cwidth = canvas.width;
			var	cheight = canvas.height - 2;
			var	capHeight = 2;
			var	capStyle = '#fff';
			var	capYPositionArray = [];    //store the vertical position of hte caps for the previous frame
			var ctx = canvas.getContext('2d');
			var	gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);

				if (hex1){
					gradient.addColorStop(1, hex1);
					gradient.addColorStop(0.5, hex2);
					gradient.addColorStop(0, hex3);
				}else{
					gradient.addColorStop(1, '#000');
					gradient.addColorStop(0.5, '#000');
					gradient.addColorStop(0, '#000');
				}

			var drawMeter = function() {
				var array = new Uint8Array(analyzerNode.frequencyBinCount);
				analyzerNode.getByteFrequencyData(array);
				if (status === 0) {
					//fix when some sounds end the value still not back to zero
					for (var i = array.length - 1; i >= 0; i--) {
						array[i] = 0;
					};
					allCapsReachBottom = true;
					for (var i = capYPositionArray.length - 1; i >= 0; i--) {
						allCapsReachBottom = allCapsReachBottom && (capYPositionArray[i] === 0);
					};
					if (allCapsReachBottom) {
						cancelAnimationFrame(animationId); //since the sound is top and animation finished, stop the requestAnimation to prevent potential memory leak,THIS IS VERY IMPORTANT!
						return;
					};
				};
				var step = 10;// Math.round(array.length / numberOfBars); //sample limited data from the total array
				ctx.clearRect(0, 0, cwidth, cheight);
				for (var i = 0; i < numberOfBars; i++) {
					var value = array[i * step];
					if (capYPositionArray.length < Math.round(numberOfBars)) {
						capYPositionArray.push(value);
					};
					ctx.fillStyle = capStyle;
					//draw the cap, with transition effect
					if (value < capYPositionArray[i]) {
						ctx.fillRect(i * (meterWidth + gap), cheight - (--capYPositionArray[i]), meterWidth, capHeight);
					} else {
						ctx.fillRect(i * (meterWidth + gap), cheight - value, meterWidth, capHeight);
						capYPositionArray[i] = value;
					};
					ctx.fillStyle = gradient; //set the filllStyle to gradient for a better look
					ctx.fillRect(i * (meterWidth + gap) , cheight - value + capHeight, meterWidth, cheight); //the meter
				}
				animationId = requestAnimationFrame(drawMeter);
			}
			animationId = requestAnimationFrame(drawMeter);
		}

		function rgbToHex (r, g, b) {
			return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
		}

		status = 1;
		sampleIntervalId = setInterval(function(){
			doSample();
		}, refreshInterval);

	});
})(jQuery);
<|endoftext|>


<commit_before>var app = angular.module('hackalist', []);

app.controller('hackathonEvents', ['$http', '$scope', function($http, $scope){

  $scope.keys = function(obj){
    return obj? Object.keys(obj) : [];
  }

  $scope.Dates = {
    $http.get('../api/1.0/api.json').success(function (obj) {
      $scope.year = obj;
    }
  })
}]);
<commit_msg>Revert<commit_after>var app = angular.module('hackalist', []);

app.controller('hackathonEvents', ['$http', '$scope', function($http, $scope){
  $http.get('../api/1.0/api.json').success(function (data) {
    $scope.year = data;
  })
}]);
<|endoftext|>


<commit_before>
// Use natural aspect ratio of map to set height and maintain
// proper marker size
var sizeMap = function() {
  $(window).off('resize.fittext orientationchange.fittext');

  var width = $('#index-map').width(),
      windowWidth = $(window).width(),
      windowHeight = $(window).height(),
      aspect = 0.57,
      height = width * aspect,
      top = ((windowHeight / 2) - (height / 2));

  if (windowWidth > 699) {
    $('#index-map').css({
      'height': (height > windowHeight) ? windowHeight + 'px' : height + 'px',
      'width': (height > windowHeight) ? (windowHeight / aspect) + 'px' : '100%',
      'top': (top > 0) ? top + 'px' : 0,
      'left': (height > windowHeight) ? ((windowWidth - (windowHeight / aspect)) / 2) + 'px' : 0
    });

    // Fit the headline text
    $("#line1").fitText(0.57);
    $("#line2").fitText(0.38);
  } else {
    $('#index-map').css({
      'width': 'auto',
    });

    $("#line1").css('font-size', '1em');
    $("#line2").css('font-size', '1em');
    $("#project-title").fitText();
  }
}

var startAudio = function() {
  var soundtrack = document.getElementById('soundtrack');

  if (typeof soundtrack.loop == 'boolean') {
    soundtrack.loop = true;
  } else {
    soundtrack.addEventListener('ended', function() {
      this.currentTime = 0;
      this.play();
    }, false);
  }

  $('#mute').on('click', toggleAudio);
  soundtrack.play();
}

var toggleAudio = function() {
  var soundtrack = document.getElementById('soundtrack');
  if (soundtrack.paused) {
    soundtrack.volume = 0;
    soundtrack.play();
    $(soundtrack).animate({volume: 1}, 800);
    $('#mute .icon-volume-up').removeClass('active');
    $('#mute .icon-volume-off').addClass('active');
  } else {
    $('#mute .icon-volume-off').removeClass('active');
    $('#mute .icon-volume-up').addClass('active');
    $(soundtrack).animate({volume: 0}, 500, function() {
      soundtrack.pause();
    });
  }
}

var fullscreenOn = function() {
  $('#fullscreen .icon-resize-full').removeClass('active');
  $('#fullscreen .icon-resize-small').addClass('active');
}

var fullscreenOff = function() {
  $('#fullscreen .icon-resize-small').removeClass('active');
  $('#fullscreen .icon-resize-full').addClass('active');
}

var toggleFullscreen = function() {
  if (BigScreen.enabled) {
    BigScreen.toggle()
  }
}

var showModal = function(e) {
    $(e.currentTarget).css({
      'display': 'block'
    });
    var windowHeight = $(window).height(),
        windowWidth = $(window).width(),
        mapHeight = $('#index-map').height(),
        header = $(e.currentTarget).find('.modal-header')
        button = $(e.currentTarget).find('.conoce'),
        victims = $(e.currentTarget).find('.victims'),
        images = $(e.currentTarget).find('img'),
        fuzz = 82, // Padding + margin of modal
        elementHeight = windowHeight - header.outerHeight() - victims.outerHeight() - button.outerHeight() - fuzz;

    if (windowWidth > 699) {
      images.css({
        'height': elementHeight + 'px',
        'width': 'auto',
      });
    } else {
      images.css({
        'width': '100%',
        'height': 'auto',
      });
    }
}

var shownModal = function(e) {
  $(e.currentTarget).find('img.lazy').each(function() {
    var src = $(this).data('original');
    $(this).attr('src', src);
  });
}

var _rotateQuote = function(el) {
  var state = $(el).data('state');
  $('#marker-' + state).find('.marker-inner').tooltip('show');
}

var blockCarousel = false;

var slideQuote = function(e) {
  var isHovered = !!$('.marker-inner').filter(function() { return $(this).is(':hover'); }).length;
  if (!blockCarousel && !isHovered) {
      $('.marker-inner').tooltip('hide');
      setTimeout(function() {
        $('.marker-inner').parent().addClass('quote-rotator');
        _rotateQuote($(e.relatedTarget));
      }, 200);
    }
}

var markerHoverTimeout;
var hoverMarker = function(e) {
  $('.marker-inner').parent().removeClass('quote-rotator');
  $('.marker-inner')
    .not($(e.currentTarget))
    .tooltip('hide');
  blockCarousel = true;
  clearTimeout(markerHoverTimeout);
  markerHoverTimeout = setTimeout(function() { blockCarousel = false; }, 1000);
}

var initializeQuotes = function() {
  $('#quotes').animate({'opacity': 1}, 600);
  _rotateQuote($('#quotes').find('.carousel').find('.active'));
  $('#quotes').find('.carousel')
    .on('slide.bs.carousel', slideQuote)
}

var exitPage = function(e) {
  e.stopPropagation();
  var href = this.href;
  var soundtrack = document.getElementById('soundtrack');
  $('.modal.in').animate({opacity: 0}, 900);
  $('#index-map').animate({opacity: 0}, 900);
  $(soundtrack).animate({volume: 0}, 800, function() {
    window.location = href;
  });
  return false;
}

$(document).ready(function() {
  // Size map on init and resize
  sizeMap();
  $(window).on('resize', sizeMap);

  $('#index-map').animate({opacity: 1}, 1500);

  // Fire up quotes after a second
  if ($(window).width() > 699) {
    setTimeout(initializeQuotes, 1800);
    setTimeout(startAudio, 1800);
  }

  // Bind tooltips
  $('.marker-inner').tooltip();
  $('.nav-share, .nav-tool i').tooltip({
    delay: {show: 500, hide: 0},
    html: true,
  });

  // Initialize hover behavior
  $('.marker-inner').hover(hoverMarker);
  $('.marker-inner').parent().addClass('quote-rotator');

  // Bind modal open before it animates into view
  $('.modal').on('show.bs.modal', showModal);

  // Bind modal when it is shown
  $('.modal').on('shown.bs.modal', shownModal);

  // Bind fullscreen button behavior
  BigScreen.onexit = fullscreenOff;
  BigScreen.onenter = fullscreenOn;
  $('#fullscreen').on('click', toggleFullscreen);

  $('.conoce a').on('click', exitPage);

});

<commit_msg>fix indent<commit_after>
// Use natural aspect ratio of map to set height and maintain
// proper marker size
var sizeMap = function() {
  $(window).off('resize.fittext orientationchange.fittext');

  var width = $('#index-map').width(),
      windowWidth = $(window).width(),
      windowHeight = $(window).height(),
      aspect = 0.57,
      height = width * aspect,
      top = ((windowHeight / 2) - (height / 2));

  if (windowWidth > 699) {
    $('#index-map').css({
      'height': (height > windowHeight) ? windowHeight + 'px' : height + 'px',
      'width': (height > windowHeight) ? (windowHeight / aspect) + 'px' : '100%',
      'top': (top > 0) ? top + 'px' : 0,
      'left': (height > windowHeight) ? ((windowWidth - (windowHeight / aspect)) / 2) + 'px' : 0
    });

    // Fit the headline text
    $("#line1").fitText(0.57);
    $("#line2").fitText(0.38);
  } else {
    $('#index-map').css({
      'width': 'auto',
    });

    $("#line1").css('font-size', '1em');
    $("#line2").css('font-size', '1em');
    $("#project-title").fitText();
  }
}

var startAudio = function() {
  var soundtrack = document.getElementById('soundtrack');

  if (typeof soundtrack.loop == 'boolean') {
    soundtrack.loop = true;
  } else {
    soundtrack.addEventListener('ended', function() {
      this.currentTime = 0;
      this.play();
    }, false);
  }

  $('#mute').on('click', toggleAudio);
  soundtrack.play();
}

var toggleAudio = function() {
  var soundtrack = document.getElementById('soundtrack');
  if (soundtrack.paused) {
    soundtrack.volume = 0;
    soundtrack.play();
    $(soundtrack).animate({volume: 1}, 800);
    $('#mute .icon-volume-up').removeClass('active');
    $('#mute .icon-volume-off').addClass('active');
  } else {
    $('#mute .icon-volume-off').removeClass('active');
    $('#mute .icon-volume-up').addClass('active');
    $(soundtrack).animate({volume: 0}, 500, function() {
      soundtrack.pause();
    });
  }
}

var fullscreenOn = function() {
  $('#fullscreen .icon-resize-full').removeClass('active');
  $('#fullscreen .icon-resize-small').addClass('active');
}

var fullscreenOff = function() {
  $('#fullscreen .icon-resize-small').removeClass('active');
  $('#fullscreen .icon-resize-full').addClass('active');
}

var toggleFullscreen = function() {
  if (BigScreen.enabled) {
    BigScreen.toggle()
  }
}

var showModal = function(e) {
    $(e.currentTarget).css({
      'display': 'block'
    });
    var windowHeight = $(window).height(),
        windowWidth = $(window).width(),
        mapHeight = $('#index-map').height(),
        header = $(e.currentTarget).find('.modal-header')
        button = $(e.currentTarget).find('.conoce'),
        victims = $(e.currentTarget).find('.victims'),
        images = $(e.currentTarget).find('img'),
        fuzz = 82, // Padding + margin of modal
        elementHeight = windowHeight - header.outerHeight() - victims.outerHeight() - button.outerHeight() - fuzz;

    if (windowWidth > 699) {
      images.css({
        'height': elementHeight + 'px',
        'width': 'auto',
      });
    } else {
      images.css({
        'width': '100%',
        'height': 'auto',
      });
    }
}

var shownModal = function(e) {
  $(e.currentTarget).find('img.lazy').each(function() {
    var src = $(this).data('original');
    $(this).attr('src', src);
  });
}

var _rotateQuote = function(el) {
  var state = $(el).data('state');
  $('#marker-' + state).find('.marker-inner').tooltip('show');
}

var blockCarousel = false;

var slideQuote = function(e) {
  var isHovered = !!$('.marker-inner').filter(function() { return $(this).is(':hover'); }).length;
  if (!blockCarousel && !isHovered) {
    $('.marker-inner').tooltip('hide');
    setTimeout(function() {
      $('.marker-inner').parent().addClass('quote-rotator');
      _rotateQuote($(e.relatedTarget));
    }, 200);
  }
}

var markerHoverTimeout;
var hoverMarker = function(e) {
  $('.marker-inner').parent().removeClass('quote-rotator');
  $('.marker-inner')
    .not($(e.currentTarget))
    .tooltip('hide');
  blockCarousel = true;
  clearTimeout(markerHoverTimeout);
  markerHoverTimeout = setTimeout(function() { blockCarousel = false; }, 1000);
}

var initializeQuotes = function() {
  $('#quotes').animate({'opacity': 1}, 600);
  _rotateQuote($('#quotes').find('.carousel').find('.active'));
  $('#quotes').find('.carousel')
    .on('slide.bs.carousel', slideQuote)
}

var exitPage = function(e) {
  e.stopPropagation();
  var href = this.href;
  var soundtrack = document.getElementById('soundtrack');
  $('.modal.in').animate({opacity: 0}, 900);
  $('#index-map').animate({opacity: 0}, 900);
  $(soundtrack).animate({volume: 0}, 800, function() {
    window.location = href;
  });
  return false;
}

$(document).ready(function() {
  // Size map on init and resize
  sizeMap();
  $(window).on('resize', sizeMap);

  $('#index-map').animate({opacity: 1}, 1500);

  // Fire up quotes after a second
  if ($(window).width() > 699) {
    setTimeout(initializeQuotes, 1800);
    setTimeout(startAudio, 1800);
  }

  // Bind tooltips
  $('.marker-inner').tooltip();
  $('.nav-share, .nav-tool i').tooltip({
    delay: {show: 500, hide: 0},
    html: true,
  });

  // Initialize hover behavior
  $('.marker-inner').hover(hoverMarker);
  $('.marker-inner').parent().addClass('quote-rotator');

  // Bind modal open before it animates into view
  $('.modal').on('show.bs.modal', showModal);

  // Bind modal when it is shown
  $('.modal').on('shown.bs.modal', shownModal);

  // Bind fullscreen button behavior
  BigScreen.onexit = fullscreenOff;
  BigScreen.onenter = fullscreenOn;
  $('#fullscreen').on('click', toggleFullscreen);

  $('.conoce a').on('click', exitPage);

});

<|endoftext|>