<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require_tree .
<commit_msg>Initial go at checkbox behaviours<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require_tree .

(function($) {
  // TODO: Where does this go aaaaagh
  "use strict";

  var enableDocumentFilter = function(){
    this.each(function(){
      var $facet = $(this),
          $clearLink = $facet.find('.clear-selected');

      $('.js-openable-facet .head').on('click', function(){
        $(this).parent().toggleClass('open');
      });

      $clearLink.on('click', function(e){
        $("input[type='checkbox']", $facet).prop({
          indeterminate: false,
          "checked": false
        });
        $(this).addClass('js-hidden');
        return false;
      });

      $('.js-openable-facet input[type="checkbox"]').on('click', function(){
        var checked = $(this).prop("checked"),
            container = $(this).parent(),
            siblings = container.siblings();

        container.find('input[type="checkbox"]').prop({
          indeterminate: false,
          checked: checked
        });

        /* Show / hide clear link */
        function updateClearVisibility(el){
          var anyCheckedBoxes = $("input[type='checkbox']", $facet).is(":checked"),
              clearLinkHidden = $clearLink.hasClass('js-hidden')

          if (anyCheckedBoxes && clearLinkHidden) {
            $clearLink.removeClass('js-hidden');
          } else if (!anyCheckedBoxes && !clearLinkHidden) {
            $clearLink.addClass('js-hidden');
          }
        }

        /* Make nested checkboxes influence parents */
        function checkSiblings(el) {
          var parent = el.parent(),
          all = true;
          el.siblings().each(function() {
            return all = ($(this).children('input[type="checkbox"]').prop("checked") === checked);
          });

          if (all && checked) {
            parent.children('input[type="checkbox"]').prop({
              indeterminate: false,
              checked: checked
            });
            checkSiblings(parent);
          } else if (all && !checked) {
            parent.children('input[type="checkbox"]').prop("checked", checked);
            parent.children('input[type="checkbox"]').prop("indeterminate", (parent.find('input[type="checkbox"]:checked').length > 0));
            checkSiblings(parent);
          } else {
            el.parents("li").children('input[type="checkbox"]').prop({
              indeterminate: true,
              checked: false
            });
          }
        }
        updateClearVisibility(container);
        checkSiblings(container);
      });

    });
    return this
  }

  $.fn.extend({
    enableDocumentFilter: enableDocumentFilter
  });

})(jQuery);

jQuery(function($) {
  $(document).ready(function(){
    $(".facet-menu").enableDocumentFilter();
  })
});
<|endoftext|>


<commit_before>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery-1.7.1.min
//= require jquery-ui-1.8.18.custom.min
//= require jquery.defaultvalue
//= require session.min

// Used to detect initial (useless) popstate.
// If history.state exists, assume browser isn't going to fire initial popstate.
popped = 'state' in window.history;
initialURL = location.href;

$(document).ready(function() {
  BrowserFallbacks.init();
  Search.init();
  Dropdowns.init();
  Forms.init();
  Downloads.init();
  DownloadBox.init();
  AboutContent.init();
});

function onPopState(fn) {
  if (window.history && window.history.pushState) {
    return $(window).bind('popstate', function(event) {
      var section;
      initialPop = !popped && location.href === initialURL;
      popped = true;
      if (initialPop) {
        return;
      }
      fn();
    });
  }
}

var DownloadBox = {
  init: function() {
    $('#gui-os-filter').addClass('visible');
    var os = window.session.browser.os; // Mac, Win, Linux
    if(os == "Mac") {
      $(".monitor").addClass("mac");
      $("#download-link").text("Download " + $("#installer-version").attr('data-mac') + " for Mac").attr("href", "/download/mac");
      $("#gui-link").removeClass('mac').addClass('gui');
      $("#gui-link").text("Mac GUIs").attr("href", "/download/gui/mac");
      $("#gui-os-filter").attr('data-os', 'mac');
      $("#gui-os-filter").text("Only show GUIs for my OS (Mac)")
    } else if (os == "Windows") {
      $(".monitor").addClass("windows");
      $("#download-link").text("Download " + $("#installer-version").attr('data-win') + " for Windows").attr("href", "/download/win");
      $("#gui-link").removeClass('mac').addClass('gui');
      $("#gui-link").text("Windows GUIs").attr("href", "/download/gui/windows");
      $("#alt-link").removeClass("windows").addClass("mac");
      $("#alt-link").text("Mac Build").attr("href", "/download/mac");
      $("#gui-os-filter").attr('data-os', 'windows');
      $("#gui-os-filter").text("Only show GUIs for my OS (Windows)")
    } else if (os == "Linux") {
      $(".monitor").addClass("linux");
      $("#download-link").text("Downloads for Linux").attr("href", "/download/linux");
      $("#gui-link").removeClass('mac').addClass('gui');
      $("#gui-link").text("Linux GUIs").attr("href", "/download/gui/linux");
      $("#alt-link").removeClass("windows").addClass("mac");
      $("#alt-link").text("Mac Build").attr("href", "/download/mac");
      $("#gui-os-filter").attr('data-os', 'linux');
      $("#gui-os-filter").text("Only show GUIs for my OS (Linux)")
    } else {
    }
  }
}

var BrowserFallbacks = {
  init: function() {
    BrowserFallbacks.initPlaceholders();
  },

  initPlaceholders: function() {
    if (!Modernizr.input.placeholder) {
      $('input[placeholder], textarea[placeholder]').each(function(input) {
        $(this).defaultValue($(this).attr('placeholder'), 'active', 'inactive');
      });
    }
  }

}

var Search = {
  searching: false,
  currentSearch: '',
  selectedIndex: 0,

  init: function() {
    Search.observeFocus();
    Search.observeTextEntry();
    Search.observeResultsClicks();
  },

  observeFocus: function() {
    $('form#search input').focus(function() {
      $(this).parent('form#search').switchClass("", "focus", 200);
    });
    $('form#search input').blur(function() {
      Search.resetForm();
    });
  },

  observeTextEntry: function() {
    $('form#search input').keyup(function(e) {
      Search.runSearch();
    });

    $('form#search input').keydown(function(e) {
      if ($('#search-results').not(':visible') && e.which != 27) {
        $('#search-results').fadeIn(0.2);
        Search.highlight(Search.selectedIndex);
      }
      switch(e.which) {
        case 13: // enter
          Search.selectResultOption();
          return false;
          break;
        case 27: // esc
          Search.resetForm();
          break;
        case 38: // up
          e.preventDefault();
          Search.resultsNav("up");
          break;
        case 40: // down
          e.preventDefault();
          Search.resultsNav("down");
          break;
      };
    });
  },

  observeResultsClicks: function() {
    $('#search-results').mousedown(function(e) {
      e.preventDefault();
    });
  },

  runSearch: function() {
    var term = $('#search-text').val();
    if(term.length < 2) { return false };

    if(!Search.searching) {
      Search.searching = true;

      if(term != Search.currentSearch) {
        Search.currentSearch = term;
        $.get("/search", {search: term}, function(results) {
          $("#search-results").html(results);
          Search.searching = false;
        }, 'html');
      };
    }
    else {
      clearTimeout(Search.timeout);
      Search.timeout = setTimeout(function() {
        Search.searching = false;
        Search.runSearch();
      }, 300);
    }
  },

  selectResultOption: function() {
    var link = $('#search-results a')[Search.selectedIndex];
    var url = $(link).attr('href');
    if(!url) {
      var term = $('#search-text').val();
      url = "/search/results?search=" + term;
    }
    window.location.href = url;
    selectedIndex = 0;
  },

  resultsNav: function(direction) {
    Search.selectedIndex += (direction == "down") ? 1 : -1;
    Search.highlight(Search.selectedIndex);
  },

  highlight: function(index) {
    var links = $('#search-results a').removeClass('highlight');
    $(links[index]).addClass('highlight');
  },

  resetForm: function() {
    $('form#search').switchClass("focus", "", 200);
    $('#search-results').fadeOut(0.2);
    Search.selectedIndex = 0;
  }
}

var Dropdowns = {
  init: function() {
    Dropdowns.observeTriggers();
  },

  observeTriggers: function() {
    $('.dropdown-trigger').click(function(e) {
      e.preventDefault();
      var panelId = $(this).attr('data-panel-id');
      if ($(this).hasClass('active')) {
        $(this).removeClass('active');
        $('#'+panelId).hide();
      }
      else {
        $(this).addClass('active');
        $('#'+panelId).show();
      }
    });
  }
}

var Forms = {
  init: function() {
    Forms.observeCopyableInputs();
  },

  observeCopyableInputs: function() {
    $('input.copyable').click(function() {
      $(this).select();
    });
  }
}
var Downloads = {
  init: function() {
    Downloads.observeGUIOSFilter();
    Downloads.observePopState();
    Downloads.filterGUIS();
    Downloads.triggerAutoDownload();
  },

  triggerAutoDownload: function() {
    var ref = document.referrer;
    var src = $('#auto-download-link').attr('href');

    if (this.shouldAutoDownload(ref, src)) {
      $('.downloading .hide').show();
      document.location = src;
    }
  },

  shouldAutoDownload: function(ref, src) {
    if (!ref || !src) {
      return false;
    }
    return ref.indexOf(document.location.origin) === 0;
  },

  getOSFilter: function() {
    var os = location.href.substring(location.href.lastIndexOf("/") + 1);
    return os === 'linux' || os === 'mac' || os === 'windows' || os === 'android' || os === 'ios' ? os : '';
  },

  capitalizeOS: function(os) {
    const platforms = {"linux": "Linux", "mac": "Mac", "windows": "Windows", "android": "Android", "ios": "iOS"};
    return platforms[os];
  },

  filterGUIS: function() {
    var osFilter = Downloads.getOSFilter();
    var capitalizedOS = Downloads.capitalizeOS(osFilter);
    $('a.gui-os-filter').not("[data-os='"+osFilter+"']").removeClass('selected');
    $('a.gui-os-filter').filter("[data-os='"+osFilter+"']").addClass('selected');

    if (osFilter === '') {
      $('ul.gui-thumbnails li').removeClass("masked");
      $('#os-filter-count').hide();
    }
    else {
      $('ul.gui-thumbnails li').filter("."+osFilter).removeClass('masked');
      $('ul.gui-thumbnails li').not("."+osFilter).addClass('masked');
      var osCount = $('ul.gui-thumbnails li' + '.' + osFilter).length;
      $('#os-filter-count strong').html(osCount);
      $('#os-filter-count .os').html(capitalizedOS);
      $('#os-filter-count').show();
    }
  },

  observeGUIOSFilter: function() {
    $('a.gui-os-filter').click(function(e) {
      e.preventDefault();
      var os = $(this).attr('data-os');

      if (window.history && window.history.pushState) {
        var url = os === ''
          ? '/downloads/guis/'
          : '/download/gui/'+os;
        history.pushState(null, $(this).html(), url);
      }

      Downloads.filterGUIS();
    });
  },

  observePopState: function() {
    onPopState(function() {
      Downloads.filterGUIS();
    });
  }
}

var AboutContent = {
  defaultSection: "branching-and-merging",

  init: function() {
    if ($('body#about').length === 0) return;
    $('section.about').hide();
    $('section.about .bottom-nav').show();
    AboutContent.observeNav();
    AboutContent.observePopState();
    AboutContent.showSection(AboutContent.getSection());
  },

  observePopState: function() {
    onPopState(function() {
      section = AboutContent.getSection();
      return AboutContent.showSection(section);
    });
  },

  getSection: function(href) {
    var section;
    section = location.href.substring(location.href.lastIndexOf("/") + 1);
    if (section.length === 0 || section == 'about') {
      section = AboutContent.defaultSection;
    }
    return section;
  },

  showSection: function(section) {
    if (section == 'about') section = AboutContent.defaultSection;
    $('ol#about-nav a').removeClass('current');
    $('ol#about-nav a#nav-' + section).addClass('current');
    $('section').hide(0, function(){
      $('section#' + section).show();
    });

    if (section == AboutContent.defaultSection) section = 'about';
    $('.sidebar nav .expanded a').removeClass('active');
    $('.sidebar nav .expanded a[href$=' + section + ']').addClass('active')
  },

  observeNav: function() {
    $('ol#about-nav a, .bottom-nav a').click(function(e) {
      e.preventDefault();
      var section = $(this).attr('data-section-id');

      if (window.history && window.history.pushState) {
        history.pushState(null, $(this).html(), '/about/'+section);
      }
      AboutContent.showSection(section);
    });
  }
}
<commit_msg>FIX : Download Button<commit_after>// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery-1.7.1.min
//= require jquery-ui-1.8.18.custom.min
//= require jquery.defaultvalue
//= require session.min

// Used to detect initial (useless) popstate.
// If history.state exists, assume browser isn't going to fire initial popstate.
popped = 'state' in window.history;
initialURL = location.href;

$(document).ready(function() {
  BrowserFallbacks.init();
  Search.init();
  Dropdowns.init();
  Forms.init();
  Downloads.init();
  DownloadBox.init();
  AboutContent.init();
});

function onPopState(fn) {
  if (window.history && window.history.pushState) {
    return $(window).bind('popstate', function(event) {
      var section;
      initialPop = !popped && location.href === initialURL;
      popped = true;
      if (initialPop) {
        return;
      }
      fn();
    });
  }
}

var DownloadBox = {
  init: function() {
    $('#gui-os-filter').addClass('visible');
    var os = window.session.browser.os; // Mac, Win, Linux
    if(os == "Mac") {
      $(".monitor").addClass("mac");
      $("#download-link").text("Download for Mac").attr("href", "/download/mac");
      $("#gui-link").removeClass('mac').addClass('gui');
      $("#gui-link").text("Mac GUIs").attr("href", "/download/gui/mac");
      $("#gui-os-filter").attr('data-os', 'mac');
      $("#gui-os-filter").text("Only show GUIs for my OS (Mac)")
    } else if (os == "Windows") {
      $(".monitor").addClass("windows");
      $("#download-link").text("Download for Windows").attr("href", "/download/win");
      $("#gui-link").removeClass('mac').addClass('gui');
      $("#gui-link").text("Windows GUIs").attr("href", "/download/gui/windows");
      $("#alt-link").removeClass("windows").addClass("mac");
      $("#alt-link").text("Mac Build").attr("href", "/download/mac");
      $("#gui-os-filter").attr('data-os', 'windows');
      $("#gui-os-filter").text("Only show GUIs for my OS (Windows)")
    } else if (os == "Linux") {
      $(".monitor").addClass("linux");
      $("#download-link").text("Download for Linux").attr("href", "/download/linux");
      $("#gui-link").removeClass('mac').addClass('gui');
      $("#gui-link").text("Linux GUIs").attr("href", "/download/gui/linux");
      $("#alt-link").removeClass("windows").addClass("mac");
      $("#alt-link").text("Mac Build").attr("href", "/download/mac");
      $("#gui-os-filter").attr('data-os', 'linux');
      $("#gui-os-filter").text("Only show GUIs for my OS (Linux)")
    } else {
    }
  }
}

var BrowserFallbacks = {
  init: function() {
    BrowserFallbacks.initPlaceholders();
  },

  initPlaceholders: function() {
    if (!Modernizr.input.placeholder) {
      $('input[placeholder], textarea[placeholder]').each(function(input) {
        $(this).defaultValue($(this).attr('placeholder'), 'active', 'inactive');
      });
    }
  }

}

var Search = {
  searching: false,
  currentSearch: '',
  selectedIndex: 0,

  init: function() {
    Search.observeFocus();
    Search.observeTextEntry();
    Search.observeResultsClicks();
  },

  observeFocus: function() {
    $('form#search input').focus(function() {
      $(this).parent('form#search').switchClass("", "focus", 200);
    });
    $('form#search input').blur(function() {
      Search.resetForm();
    });
  },

  observeTextEntry: function() {
    $('form#search input').keyup(function(e) {
      Search.runSearch();
    });

    $('form#search input').keydown(function(e) {
      if ($('#search-results').not(':visible') && e.which != 27) {
        $('#search-results').fadeIn(0.2);
        Search.highlight(Search.selectedIndex);
      }
      switch(e.which) {
        case 13: // enter
          Search.selectResultOption();
          return false;
          break;
        case 27: // esc
          Search.resetForm();
          break;
        case 38: // up
          e.preventDefault();
          Search.resultsNav("up");
          break;
        case 40: // down
          e.preventDefault();
          Search.resultsNav("down");
          break;
      };
    });
  },

  observeResultsClicks: function() {
    $('#search-results').mousedown(function(e) {
      e.preventDefault();
    });
  },

  runSearch: function() {
    var term = $('#search-text').val();
    if(term.length < 2) { return false };

    if(!Search.searching) {
      Search.searching = true;

      if(term != Search.currentSearch) {
        Search.currentSearch = term;
        $.get("/search", {search: term}, function(results) {
          $("#search-results").html(results);
          Search.searching = false;
        }, 'html');
      };
    }
    else {
      clearTimeout(Search.timeout);
      Search.timeout = setTimeout(function() {
        Search.searching = false;
        Search.runSearch();
      }, 300);
    }
  },

  selectResultOption: function() {
    var link = $('#search-results a')[Search.selectedIndex];
    var url = $(link).attr('href');
    if(!url) {
      var term = $('#search-text').val();
      url = "/search/results?search=" + term;
    }
    window.location.href = url;
    selectedIndex = 0;
  },

  resultsNav: function(direction) {
    Search.selectedIndex += (direction == "down") ? 1 : -1;
    Search.highlight(Search.selectedIndex);
  },

  highlight: function(index) {
    var links = $('#search-results a').removeClass('highlight');
    $(links[index]).addClass('highlight');
  },

  resetForm: function() {
    $('form#search').switchClass("focus", "", 200);
    $('#search-results').fadeOut(0.2);
    Search.selectedIndex = 0;
  }
}

var Dropdowns = {
  init: function() {
    Dropdowns.observeTriggers();
  },

  observeTriggers: function() {
    $('.dropdown-trigger').click(function(e) {
      e.preventDefault();
      var panelId = $(this).attr('data-panel-id');
      if ($(this).hasClass('active')) {
        $(this).removeClass('active');
        $('#'+panelId).hide();
      }
      else {
        $(this).addClass('active');
        $('#'+panelId).show();
      }
    });
  }
}

var Forms = {
  init: function() {
    Forms.observeCopyableInputs();
  },

  observeCopyableInputs: function() {
    $('input.copyable').click(function() {
      $(this).select();
    });
  }
}
var Downloads = {
  init: function() {
    Downloads.observeGUIOSFilter();
    Downloads.observePopState();
    Downloads.filterGUIS();
    Downloads.triggerAutoDownload();
  },

  triggerAutoDownload: function() {
    var ref = document.referrer;
    var src = $('#auto-download-link').attr('href');

    if (this.shouldAutoDownload(ref, src)) {
      $('.downloading .hide').show();
      document.location = src;
    }
  },

  shouldAutoDownload: function(ref, src) {
    if (!ref || !src) {
      return false;
    }
    return ref.indexOf(document.location.origin) === 0;
  },

  getOSFilter: function() {
    var os = location.href.substring(location.href.lastIndexOf("/") + 1);
    return os === 'linux' || os === 'mac' || os === 'windows' || os === 'android' || os === 'ios' ? os : '';
  },

  capitalizeOS: function(os) {
    const platforms = {"linux": "Linux", "mac": "Mac", "windows": "Windows", "android": "Android", "ios": "iOS"};
    return platforms[os];
  },

  filterGUIS: function() {
    var osFilter = Downloads.getOSFilter();
    var capitalizedOS = Downloads.capitalizeOS(osFilter);
    $('a.gui-os-filter').not("[data-os='"+osFilter+"']").removeClass('selected');
    $('a.gui-os-filter').filter("[data-os='"+osFilter+"']").addClass('selected');

    if (osFilter === '') {
      $('ul.gui-thumbnails li').removeClass("masked");
      $('#os-filter-count').hide();
    }
    else {
      $('ul.gui-thumbnails li').filter("."+osFilter).removeClass('masked');
      $('ul.gui-thumbnails li').not("."+osFilter).addClass('masked');
      var osCount = $('ul.gui-thumbnails li' + '.' + osFilter).length;
      $('#os-filter-count strong').html(osCount);
      $('#os-filter-count .os').html(capitalizedOS);
      $('#os-filter-count').show();
    }
  },

  observeGUIOSFilter: function() {
    $('a.gui-os-filter').click(function(e) {
      e.preventDefault();
      var os = $(this).attr('data-os');

      if (window.history && window.history.pushState) {
        var url = os === ''
          ? '/downloads/guis/'
          : '/download/gui/'+os;
        history.pushState(null, $(this).html(), url);
      }

      Downloads.filterGUIS();
    });
  },

  observePopState: function() {
    onPopState(function() {
      Downloads.filterGUIS();
    });
  }
}

var AboutContent = {
  defaultSection: "branching-and-merging",

  init: function() {
    if ($('body#about').length === 0) return;
    $('section.about').hide();
    $('section.about .bottom-nav').show();
    AboutContent.observeNav();
    AboutContent.observePopState();
    AboutContent.showSection(AboutContent.getSection());
  },

  observePopState: function() {
    onPopState(function() {
      section = AboutContent.getSection();
      return AboutContent.showSection(section);
    });
  },

  getSection: function(href) {
    var section;
    section = location.href.substring(location.href.lastIndexOf("/") + 1);
    if (section.length === 0 || section == 'about') {
      section = AboutContent.defaultSection;
    }
    return section;
  },

  showSection: function(section) {
    if (section == 'about') section = AboutContent.defaultSection;
    $('ol#about-nav a').removeClass('current');
    $('ol#about-nav a#nav-' + section).addClass('current');
    $('section').hide(0, function(){
      $('section#' + section).show();
    });

    if (section == AboutContent.defaultSection) section = 'about';
    $('.sidebar nav .expanded a').removeClass('active');
    $('.sidebar nav .expanded a[href$=' + section + ']').addClass('active')
  },

  observeNav: function() {
    $('ol#about-nav a, .bottom-nav a').click(function(e) {
      e.preventDefault();
      var section = $(this).attr('data-section-id');

      if (window.history && window.history.pushState) {
        history.pushState(null, $(this).html(), '/about/'+section);
      }
      AboutContent.showSection(section);
    });
  }
}
<|endoftext|>


<commit_before>var locationsURL = "http://localhost:3000/locations.json";

$(document).ready(function(){
	var plots = [];

	$.getJSON(locationsURL).done(function (chapters) {
		_.each(chapters, function (plot) {
			newobj = {
				value: plot.location,
				latitude: plot.latitude,
				longitude: plot.longitude,
				tooltip: {content: plot.location},
				href: "locations/" + plot.slug
			}
			plots.push(newobj);
		})
		console.log("yey!");
	}).done(function () {
		$(".us_map").mapael({

		map : {
			name : "usa_states",
			cssClass : "map",
			tooltip : {
				cssClass : "mapTooltip"
				},
			defaultArea : {
				attrs : {
					fill : "#282828",
					stroke: "#9a9a9a",
				},
				attrsHover : {
					fill : "#7a7c7c",
					animDuration: 300
				}
			},
			defaultPlot : {
				type : "circle",
				href : "#",
				size : 15,
				attrs: {
					fill : "#f95a61"
				},
				attrsHover: {

				}
			},
		},

		plots : plots,

		})
	})
});
<commit_msg>Respecify request in chapter-map.js<commit_after>var locationsURL = "/locations.json";

$(document).ready(function(){
	var plots = [];

	$.getJSON(locationsURL).done(function (chapters) {
		_.each(chapters, function (plot) {
			newobj = {
				value: plot.location,
				latitude: plot.latitude,
				longitude: plot.longitude,
				tooltip: {content: plot.location},
				href: "locations/" + plot.slug
			}
			plots.push(newobj);
		})
		console.log("yey!");
	}).done(function () {
		$(".us_map").mapael({

		map : {
			name : "usa_states",
			cssClass : "map",
			tooltip : {
				cssClass : "mapTooltip"
				},
			defaultArea : {
				attrs : {
					fill : "#282828",
					stroke: "#9a9a9a",
				},
				attrsHover : {
					fill : "#7a7c7c",
					animDuration: 300
				}
			},
			defaultPlot : {
				type : "circle",
				href : "#",
				size : 15,
				attrs: {
					fill : "#f95a61"
				},
				attrsHover: {

				}
			},
		},

		plots : plots,

		})
	})
});
<|endoftext|>


<commit_before>import _ from 'underscore';
import createFlash from '~/flash';
import { s__ } from '~/locale';
import emojiAliases from 'emojis/aliases.json';
import axios from '../lib/utils/axios_utils';
import csrf from '../lib/utils/csrf';

import AccessorUtilities from '../lib/utils/accessor';

let emojiMap = null;
let validEmojiNames = null;

export const EMOJI_VERSION = '1';
const EMOJI_VERSION_LOCALSTORAGE = `EMOJIS_${EMOJI_VERSION}`;

const isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();

export function initEmojiMap() {
  return new Promise((resolve, reject) => {
    if (emojiMap) {
      resolve(emojiMap);
    } else if (isLocalStorageAvailable && window.localStorage.getItem(EMOJI_VERSION_LOCALSTORAGE)) {
      emojiMap = JSON.parse(window.localStorage.getItem(EMOJI_VERSION_LOCALSTORAGE));
      validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)];
      resolve(emojiMap);
    } else {
      // We load the JSON from server
      const axiosInstance = axios.create();

      // If the static JSON file is on a CDN we don't want to send the default CSRF token
      if (gon.asset_host) {
        delete axiosInstance.defaults.headers.common[csrf.headerKey];
      }

      axiosInstance
        .get(
          `${gon.asset_host || ''}${gon.relative_url_root ||
            ''}/-/emojis/${EMOJI_VERSION}/emojis.json`,
        )
        .then(({ data }) => {
          emojiMap = data;
          validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)];
          resolve(emojiMap);
          if (isLocalStorageAvailable) {
            window.localStorage.setItem(EMOJI_VERSION_LOCALSTORAGE, JSON.stringify(emojiMap));
          }
        })
        .catch(err => {
          createFlash(s__('Emojis|Something went wrong while loading emojis.'));
          reject(err);
        });
    }
  });
}

export function normalizeEmojiName(name) {
  return Object.prototype.hasOwnProperty.call(emojiAliases, name) ? emojiAliases[name] : name;
}

export function getValidEmojiNames() {
  return validEmojiNames;
}

export function isEmojiNameValid(name) {
  return validEmojiNames.indexOf(name) >= 0;
}

export function filterEmojiNames(filter) {
  const match = filter.toLowerCase();
  return validEmojiNames.filter(name => name.indexOf(match) >= 0);
}

export function filterEmojiNamesByAlias(filter) {
  return _.uniq(filterEmojiNames(filter).map(name => normalizeEmojiName(name)));
}

let emojiCategoryMap;
export function getEmojiCategoryMap() {
  if (!emojiCategoryMap) {
    emojiCategoryMap = {
      activity: [],
      people: [],
      nature: [],
      food: [],
      travel: [],
      objects: [],
      symbols: [],
      flags: [],
    };
    Object.keys(emojiMap).forEach(name => {
      const emoji = emojiMap[name];
      if (emojiCategoryMap[emoji.c]) {
        emojiCategoryMap[emoji.c].push(name);
      }
    });
  }
  return emojiCategoryMap;
}

export function getEmojiInfo(query) {
  let name = normalizeEmojiName(query);
  let emojiInfo = emojiMap[name];

  // Fallback to question mark for unknown emojis
  if (!emojiInfo) {
    name = 'grey_question';
    emojiInfo = emojiMap[name];
  }

  return { ...emojiInfo, name };
}

export function emojiFallbackImageSrc(inputName) {
  const { name } = getEmojiInfo(inputName);
  return `${gon.asset_host || ''}${gon.relative_url_root ||
    ''}/-/emojis/${EMOJI_VERSION}/${name}.png`;
}

export function emojiImageTag(name, src) {
  return `<img class="emoji" title=":${name}:" alt=":${name}:" src="${src}" width="20" height="20" align="absmiddle" />`;
}

export function glEmojiTag(inputName, options) {
  const opts = { sprite: false, forceFallback: false, ...options };
  const name = normalizeEmojiName(inputName);

  const fallbackSpriteClass = `emoji-${name}`;

  const classList = [];
  if (opts.forceFallback && opts.sprite) {
    classList.push('emoji-icon');
    classList.push(fallbackSpriteClass);
  }
  const classAttribute = classList.length > 0 ? `class="${classList.join(' ')}"` : '';

  const fallbackSpriteAttribute = opts.sprite
    ? `data-fallback-sprite-class="${fallbackSpriteClass}"`
    : '';
  const forceFallbackAttribute = opts.forceFallback ? 'data-force-fallback="true"' : '';

  return `
    <gl-emoji
      ${classAttribute}
      data-name="${name}"
      ${fallbackSpriteAttribute}
      ${forceFallbackAttribute}
    >
    </gl-emoji>
  `;
}
<commit_msg>Removes the CDN loading for emojis.json<commit_after>import _ from 'underscore';
import createFlash from '~/flash';
import { s__ } from '~/locale';
import emojiAliases from 'emojis/aliases.json';
import axios from '../lib/utils/axios_utils';
import csrf from '../lib/utils/csrf';

import AccessorUtilities from '../lib/utils/accessor';

let emojiMap = null;
let validEmojiNames = null;

export const EMOJI_VERSION = '1';
const EMOJI_VERSION_LOCALSTORAGE = `EMOJIS_${EMOJI_VERSION}`;

const isLocalStorageAvailable = AccessorUtilities.isLocalStorageAccessSafe();

export function initEmojiMap() {
  return new Promise((resolve, reject) => {
    if (emojiMap) {
      resolve(emojiMap);
    } else if (isLocalStorageAvailable && window.localStorage.getItem(EMOJI_VERSION_LOCALSTORAGE)) {
      emojiMap = JSON.parse(window.localStorage.getItem(EMOJI_VERSION_LOCALSTORAGE));
      validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)];
      resolve(emojiMap);
    } else {
      // We load the JSON from server
      const axiosInstance = axios.create();

      // If the static JSON file is on a CDN we don't want to send the default CSRF token
      if (gon.asset_host) {
        delete axiosInstance.defaults.headers.common[csrf.headerKey];
      }

      axiosInstance
        .get(`${gon.relative_url_root || ''}/-/emojis/${EMOJI_VERSION}/emojis.json`)
        .then(({ data }) => {
          emojiMap = data;
          validEmojiNames = [...Object.keys(emojiMap), ...Object.keys(emojiAliases)];
          resolve(emojiMap);
          if (isLocalStorageAvailable) {
            window.localStorage.setItem(EMOJI_VERSION_LOCALSTORAGE, JSON.stringify(emojiMap));
          }
        })
        .catch(err => {
          createFlash(s__('Emojis|Something went wrong while loading emojis.'));
          reject(err);
        });
    }
  });
}

export function normalizeEmojiName(name) {
  return Object.prototype.hasOwnProperty.call(emojiAliases, name) ? emojiAliases[name] : name;
}

export function getValidEmojiNames() {
  return validEmojiNames;
}

export function isEmojiNameValid(name) {
  return validEmojiNames.indexOf(name) >= 0;
}

export function filterEmojiNames(filter) {
  const match = filter.toLowerCase();
  return validEmojiNames.filter(name => name.indexOf(match) >= 0);
}

export function filterEmojiNamesByAlias(filter) {
  return _.uniq(filterEmojiNames(filter).map(name => normalizeEmojiName(name)));
}

let emojiCategoryMap;
export function getEmojiCategoryMap() {
  if (!emojiCategoryMap) {
    emojiCategoryMap = {
      activity: [],
      people: [],
      nature: [],
      food: [],
      travel: [],
      objects: [],
      symbols: [],
      flags: [],
    };
    Object.keys(emojiMap).forEach(name => {
      const emoji = emojiMap[name];
      if (emojiCategoryMap[emoji.c]) {
        emojiCategoryMap[emoji.c].push(name);
      }
    });
  }
  return emojiCategoryMap;
}

export function getEmojiInfo(query) {
  let name = normalizeEmojiName(query);
  let emojiInfo = emojiMap[name];

  // Fallback to question mark for unknown emojis
  if (!emojiInfo) {
    name = 'grey_question';
    emojiInfo = emojiMap[name];
  }

  return { ...emojiInfo, name };
}

export function emojiFallbackImageSrc(inputName) {
  const { name } = getEmojiInfo(inputName);
  return `${gon.asset_host || ''}${gon.relative_url_root ||
    ''}/-/emojis/${EMOJI_VERSION}/${name}.png`;
}

export function emojiImageTag(name, src) {
  return `<img class="emoji" title=":${name}:" alt=":${name}:" src="${src}" width="20" height="20" align="absmiddle" />`;
}

export function glEmojiTag(inputName, options) {
  const opts = { sprite: false, forceFallback: false, ...options };
  const name = normalizeEmojiName(inputName);

  const fallbackSpriteClass = `emoji-${name}`;

  const classList = [];
  if (opts.forceFallback && opts.sprite) {
    classList.push('emoji-icon');
    classList.push(fallbackSpriteClass);
  }
  const classAttribute = classList.length > 0 ? `class="${classList.join(' ')}"` : '';

  const fallbackSpriteAttribute = opts.sprite
    ? `data-fallback-sprite-class="${fallbackSpriteClass}"`
    : '';
  const forceFallbackAttribute = opts.forceFallback ? 'data-force-fallback="true"' : '';

  return `
    <gl-emoji
      ${classAttribute}
      data-name="${name}"
      ${fallbackSpriteAttribute}
      ${forceFallbackAttribute}
    >
    </gl-emoji>
  `;
}
<|endoftext|>


<commit_before>var Jcontroller = {
    controllers_path: 'Jcontroller/controllers/',
    application_controller_path: "application",
    create: function(controller_path, definition) {
        Jcontroller.define_namespace(Jcontroller.controllers_path + controller_path,
            $.extend({
                    parent_path: controller_path === this.application_controller_path ? undefined : "application",
                    parent: function() {
                        if (Jcontroller.blank(this.parent_cache)) { this.parent_cache =  Jcontroller.find(this.parent_path); }
                        return this.parent_cache;
                    },

                    dup: function(state, params) {
                        var dup = $.extend({}, this, state.jaction);
                        dup.state = state;
                        dup.params = params;
                        if (Jcontroller.present(dup.parent())) { dup.parent_cache = dup.parent().dup(state, params); }
                        return dup;
                    },

                    execute_action: function() {
                        if ($.isPlainObject(this.html)) {
                            this.execute_post_order_filter('before');
                            this.execute_post_order_filter(this.action_name);
                            this.execute_pre_order_filter('after');
                        }
                    },
                    execute_post_order_filter: function(filter) {
                        if (Jcontroller.present(this.parent())) this.parent().execute_post_order_filter(filter);
                        this.execute_filter(this[this.format][filter]);
                    },
                    execute_pre_order_filter: function(filter) {
                        this.execute_filter(this[this.format][filter]);
                        if (Jcontroller.present(this.parent())) this.parent().execute_pre_order_filter(filter);
                    },
                    execute_filter: function(filter) {
                        if ($.isFunction(filter)) { $.proxy(filter, this)(); }
                    }
                },
                definition
            )
        );
    },
    execute_jaction: function(state, params) {
        var controller = this.find(state.jaction.controller_path);
        if (this.present(controller)) { controller.dup(state, params).execute_action(); }
    },

    blank: function(o) { return typeof o === "undefined" || o === null; },
    present: function(o) { return !this.blank(o); },

    define_namespace: function(namespace_string, definition) {
        return $.extend(this.get_or_create(namespace_string), definition);
    },
    get_or_create: function(namespace_string) {
        var current_namepace = window;
        $.each(namespace_string.split('/'), function(index, level) {
            if (Jcontroller.blank(current_namepace[level])) { current_namepace[level] = {}; }
            current_namepace = current_namepace[level];
        });

        return current_namepace;
    },
    find: function(controller_path) {
        if (this.blank(controller_path)) { return undefined; }
        var namespace_string = this.controllers_path + controller_path;

        var current_namepace = window;
        $.each(namespace_string.split('/'), function(index, level) {
            if (Jcontroller.blank(current_namepace[level])) {
                current_namepace = undefined;
                return false;
            }
            current_namepace = current_namepace[level];
        });
        return current_namepace;
    }
};<commit_msg>minor javascript refactor<commit_after>var Jcontroller = {
    controllers_path: 'Jcontroller/controllers/',
    application_controller_path: "application",
    create: function(controller_path, definition) {
        Jcontroller.define_namespace(Jcontroller.controllers_path + controller_path,
            $.extend({
                    parent_path: controller_path === this.application_controller_path ? undefined : "application",
                    parent: function() {
                        if (Jcontroller.blank(this.parent_cache)) { this.parent_cache =  Jcontroller.find(this.parent_path); }
                        return this.parent_cache;
                    },

                    dup: function(state, params) {
                        var dup = $.extend({}, this, state.jaction);
                        dup.state = state;
                        dup.params = params;
                        if (Jcontroller.present(dup.parent())) { dup.parent_cache = dup.parent().dup(state, params); }
                        return dup;
                    },

                    execute_action: function() {
                        if ($.isPlainObject(this.html)) {
                            this.execute_post_order_filter('before');
                            this.execute_post_order_filter(this.action_name);
                            this.execute_pre_order_filter('after');
                        }
                    },
                    execute_post_order_filter: function(filter) {
                        if (Jcontroller.present(this.parent())) { this.parent().execute_post_order_filter(filter); }
                        this.execute_filter(this[this.format][filter]);
                    },
                    execute_pre_order_filter: function(filter) {
                        this.execute_filter(this[this.format][filter]);
                        if (Jcontroller.present(this.parent())) { this.parent().execute_pre_order_filter(filter); }
                    },
                    execute_filter: function(filter) {
                        if ($.isFunction(filter)) { $.proxy(filter, this)(); }
                    }
                },
                definition
            )
        );
    },
    execute_jaction: function(state, params) {
        var controller = this.find(state.jaction.controller_path);
        if (this.present(controller)) { controller.dup(state, params).execute_action(); }
    },

    blank: function(o) { return typeof o === "undefined" || o === null; },
    present: function(o) { return !this.blank(o); },

    define_namespace: function(namespace_string, definition) {
        return $.extend(this.get_or_create(namespace_string), definition);
    },
    get_or_create: function(namespace_string) {
        var current_namepace = window;
        $.each(namespace_string.split('/'), function(index, level) {
            if (Jcontroller.blank(current_namepace[level])) { current_namepace[level] = {}; }
            current_namepace = current_namepace[level];
        });

        return current_namepace;
    },
    find: function(controller_path) {
        if (this.blank(controller_path)) { return undefined; }
        var namespace_string = this.controllers_path + controller_path;

        var current_namepace = window;
        $.each(namespace_string.split('/'), function(index, level) {
            if (Jcontroller.blank(current_namepace[level])) {
                current_namepace = undefined;
                return false;
            }
            current_namepace = current_namepace[level];
        });
        return current_namepace;
    }
};<|endoftext|>


<commit_before>var Lang = A.Lang,
	isObject = Lang.isObject,
	isValue = Lang.isValue,

	getCN = A.getClassName,

	CHILDREN = 'children',
	CONTAINER = 'container',
	END = 'end',
	IO = 'io',
	LIMIT = 'limit',
	MORE_RESULTS_LABEL = 'Load more results',
	NODE = 'node',
	OWNER_TREE = 'ownerTree',
	PAGINATOR = 'paginator',
	START = 'start',
	TREE = 'tree',
	TREE_NODE_IO = 'tree-node-io',

	EV_TREE_NODE_PAGINATOR_CLICK = 'paginatorClick',

	CSS_TREE_NODE_PAGINATOR = getCN(TREE, NODE, PAGINATOR),

	TPL_PAGINATOR = '{moreResultsLabel}';

function TreeViewPaginator(config) {
	var instance = this;

	A.after(instance._bindPaginatorUI, this, 'bindUI');

	A.after(instance._syncPaginatorUI, this, 'syncUI');
}

TreeViewPaginator.ATTRS = {
	paginator: {
		setter: function(value) {
			var instance = this;

			var paginatorNode = A.Node.create(
				Lang.sub(
					TPL_PAGINATOR,
					{
						moreResultsLabel: value.moreResultsLabel || MORE_RESULTS_LABEL
					}
				)
			);

			return A.merge(
				{
					alwaysVisible: false,
					autoFocus: true,
					element: paginatorNode,
					endParam: END,
					limitParam: LIMIT,
					start: 0,
					startParam: START
				},
				value
			);
		},
		validator: isObject
	}
};

TreeViewPaginator.prototype = {
	/**
	 * Bind events to the paginator "show more" link.
	 *
	 * @method _bindPaginatorUI
	 * @protected
	 */
	_bindPaginatorUI: function() {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (paginator) {
			paginator.element.on('click', A.bind(instance._handlePaginatorClickEvent, instance));
		}

		instance._createEvents();
	},

	/**
	 * Create custom events.
	 *
	 * @method _createEvents
	 * @private
	 */
	_createEvents: function() {
		var instance = this;

		instance.publish(
			EV_TREE_NODE_PAGINATOR_CLICK,
			{
				defaultFn: instance._defPaginatorClickFn,
				prefix: TREE_NODE_IO
			}
		);
	},

	/**
	 * Default paginatorClick event handler. Increment the
	 * paginator.start to the next paginator.limit.
	 *
	 * @method _defPaginatorClickFn
	 * @param {EventFacade} event The Event object
	 * @protected
	 */
	_defPaginatorClickFn: function(event) {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (isValue(paginator.limit)) {
			paginator.start = instance.childrenLength || 0;
		}

		if (instance.get(IO)) {
			instance.initIO();
		}
	},

	/**
	 * Fires the paginatorClick event.
	 *
	 * @method _handlePaginatorClickEvent
	 * @param {EventFacade} event paginatorClick event facade
	 * @protected
	 */
	_handlePaginatorClickEvent: function(event) {
		var instance = this;

		var output = instance.getEventOutputMap(instance);

		instance.fire(EV_TREE_NODE_PAGINATOR_CLICK, output);

		event.halt();
	},

	/**
	 * Adds two extra IO data parameter to the request to handle the
	 * paginator. By default these parameters are limit and
	 * start.
	 *
	 * @method _syncPaginatorIOData
	 * @protected
	 */
	_syncPaginatorIOData: function(io) {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (paginator && isValue(paginator.limit)) {
			var data = io.cfg.data || {};

			data[ paginator.limitParam ] = paginator.limit;
			data[ paginator.startParam ] = paginator.start;
			data[ paginator.endParam ] = (paginator.start + paginator.limit);

			io.cfg.data = data;
		}
	},

	/**
	 * Sync the paginator link UI.
	 *
	 * @method _syncPaginatorUI
	 * @protected
	 */
	_syncPaginatorUI: function(newNodes) {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (paginator) {
			var hasMoreData = true;

			if (newNodes) {
				hasMoreData = (newNodes.length > 0);
			}

			var childrenLength = instance.getChildrenLength();
			var start = paginator.start;
			var total = paginator.total || childrenLength;

			var showPaginator = childrenLength && hasMoreData && (total > childrenLength);

			if (paginator.alwaysVisible || showPaginator) {
				instance.get(CONTAINER).append(
					paginator.element.show()
				);

				if (paginator.autoFocus) {
					try {
						paginator.element.focus();
					}
					catch(e) {}
				}
			}
			else {
				paginator.element.hide();
			}
		}
	}
};

A.TreeViewPaginator = TreeViewPaginator;<commit_msg>AUI-927 - Source formatting<commit_after>var Lang = A.Lang,
	isObject = Lang.isObject,
	isValue = Lang.isValue,

	getCN = A.getClassName,

	CHILDREN = 'children',
	CONTAINER = 'container',
	END = 'end',
	IO = 'io',
	LIMIT = 'limit',
	MORE_RESULTS_LABEL = 'Load more results',
	NODE = 'node',
	OWNER_TREE = 'ownerTree',
	PAGINATOR = 'paginator',
	START = 'start',
	TREE = 'tree',
	TREE_NODE_IO = 'tree-node-io',

	EV_TREE_NODE_PAGINATOR_CLICK = 'paginatorClick',

	CSS_TREE_NODE_PAGINATOR = getCN(TREE, NODE, PAGINATOR),

	TPL_PAGINATOR = '{moreResultsLabel}';

function TreeViewPaginator(config) {
	var instance = this;

	A.after(instance._bindPaginatorUI, this, 'bindUI');

	A.after(instance._syncPaginatorUI, this, 'syncUI');
}

TreeViewPaginator.ATTRS = {
	paginator: {
		setter: function(value) {
			var instance = this;

			var paginatorNode = A.Node.create(
				Lang.sub(
					TPL_PAGINATOR,
					{
						moreResultsLabel: value.moreResultsLabel || MORE_RESULTS_LABEL
					}
				)
			);

			return A.merge(
				{
					alwaysVisible: false,
					autoFocus: true,
					element: paginatorNode,
					endParam: END,
					limitParam: LIMIT,
					start: 0,
					startParam: START
				},
				value
			);
		},
		validator: isObject
	}
};

TreeViewPaginator.prototype = {
	/**
	 * Bind events to the paginator "show more" link.
	 *
	 * @method _bindPaginatorUI
	 * @protected
	 */
	_bindPaginatorUI: function() {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (paginator) {
			paginator.element.on('click', A.bind(instance._handlePaginatorClickEvent, instance));
		}

		instance._createEvents();
	},

	/**
	 * Create custom events.
	 *
	 * @method _createEvents
	 * @private
	 */
	_createEvents: function() {
		var instance = this;

		instance.publish(
			EV_TREE_NODE_PAGINATOR_CLICK,
			{
				defaultFn: instance._defPaginatorClickFn,
				prefix: TREE_NODE_IO
			}
		);
	},

	/**
	 * Default paginatorClick event handler. Increment the
	 * paginator.start to the next paginator.limit.
	 *
	 * @method _defPaginatorClickFn
	 * @param {EventFacade} event The Event object
	 * @protected
	 */
	_defPaginatorClickFn: function(event) {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (isValue(paginator.limit)) {
			paginator.start = instance.getChildrenLength();
		}

		if (instance.get(IO)) {
			instance.initIO();
		}
	},

	/**
	 * Fires the paginatorClick event.
	 *
	 * @method _handlePaginatorClickEvent
	 * @param {EventFacade} event paginatorClick event facade
	 * @protected
	 */
	_handlePaginatorClickEvent: function(event) {
		var instance = this;

		var output = instance.getEventOutputMap(instance);

		instance.fire(EV_TREE_NODE_PAGINATOR_CLICK, output);

		event.halt();
	},

	/**
	 * Adds two extra IO data parameter to the request to handle the
	 * paginator. By default these parameters are limit and
	 * start.
	 *
	 * @method _syncPaginatorIOData
	 * @protected
	 */
	_syncPaginatorIOData: function(io) {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (paginator && isValue(paginator.limit)) {
			var data = io.cfg.data || {};

			data[ paginator.limitParam ] = paginator.limit;
			data[ paginator.startParam ] = paginator.start;
			data[ paginator.endParam ] = (paginator.start + paginator.limit);

			io.cfg.data = data;
		}
	},

	/**
	 * Sync the paginator link UI.
	 *
	 * @method _syncPaginatorUI
	 * @protected
	 */
	_syncPaginatorUI: function(newNodes) {
		var instance = this;

		var paginator = instance.get(PAGINATOR);

		if (paginator) {
			var hasMoreData = true;

			if (newNodes) {
				hasMoreData = (newNodes.length > 0);
			}

			var childrenLength = instance.getChildrenLength();
			var start = paginator.start;
			var total = paginator.total || childrenLength;

			var showPaginator = childrenLength && hasMoreData && (total > childrenLength);

			if (paginator.alwaysVisible || showPaginator) {
				instance.get(CONTAINER).append(
					paginator.element.show()
				);

				if (paginator.autoFocus) {
					try {
						paginator.element.focus();
					}
					catch(e) {}
				}
			}
			else {
				paginator.element.hide();
			}
		}
	}
};

A.TreeViewPaginator = TreeViewPaginator;<|endoftext|>


<commit_before>var skill_list;
var skill_list_inverted;
var skill_list_special_group;

function clear_cookies() {
  Cookies.remove('drpedia');
}

function pack_state() {
  if (!has_profile) { return; }

  var pack = $('#hp-addition').text() + '|'
           + $('#mp-addition').text() + '|'
           + (selected_strain || '') + '|'
           + (selected_professions || new Array()).join(',') + '|';
  var es = extract_skills();

  pack += es.acquired.join(',') + '|' + es.planned.join(',');
  Cookies.set(current_profile, pack, { expires: 365 });
  console.log('Packing to ' + current_profile + ': ' + pack);
}

function unpack_state() {
  if (!has_profile) { return; }

  var decrypt_psionic_skills = function(a) {
    var prefix = '';
    $.each(skill_groups, function(group_name, skills) {
      if (skills[a] != undefined) {
        switch (group_name) {
          case 'Psionic Skill - Basic': prefix = 'Psi I - '; break;
          case 'Psionic Skill - Intermediate': prefix = 'Psi II - '; break;
          case 'Psionic Skill - Advanced': prefix = 'Psi III - '; break;
        }

        return false;
      }
    });

    return prefix + a;
  }

  var decrypt_skills = function(a) {
    var output = new Array();

    $.each(a, function(i, x) {
      var lookup = skill_list_inverted[x];
      if (lookup != undefined) {
        output.push(lookup);
      }
    })
    return output;
  }

  var relocate = function(target_list_id, skill_list) {
    $.each(skill_list, function(i, x) {
      //console.log('relocating ' + x);
      var target_object = $('[skill-name="' + x + '"]');
      if (target_object.length == 0) {
        target_object = $('[skill-name="' + decrypt_psionic_skills(x) + '"]');
      }

      if (target_object) {
        //console.log(target_object.hasClass('faded') + ' ' + target_object.text());
        //if (!target_object.hasClass('faded')) {
        append_lexicographically(target_list_id, target_object);
        //}
      }
    })
  }

  var reset_all_skills = function(list_id) {
    var entries = new Array();

    $('#' + list_id + ' .list-group-item').each(function() {
      var entry = $(this).attr('skill-name');
      entries.push(entry);
    })

    relocate('#graphical-list', entries);
  }

  var unpack = current_profile == 'dummy' ? '0|0||||' : Cookies.get(current_profile);
  console.log('Unpack from ' + current_profile + ': ' + unpack);

  if (unpack != undefined) {
    var p0 = unpack.split('|');
    var hp = parseInt(p0[0]) || 0;
    var mp = parseInt(p0[1]) || 0;
    var strain = p0[2];

    reset_all_skills('acquired-list');
    reset_all_skills('planned-list');
    set_stat_build($('#hp-addition'), 'hp-total', hp, false);
    set_stat_build($('#mp-addition'), 'mp-total', mp, false);
    initialize_stats_controller('#hp-sub');
    initialize_stats_controller('#mp-sub');
    var professions = p0[3].split(',');
    var acquired_skills = decrypt_skills(p0[4].split(','));
    var planned_skills = decrypt_skills(p0[5].split(','));

    selected_strain = strain || 'Select Strain';

    selected_professions = new Array();
    $.each(professions, function(i, x) {
      if (advanced_profession_struct[x] == undefined) {
        selected_professions.push(x);
      } else {
        selected_advanced_profession = x;
      }
    })

    //selected_professions = professions;
    //$('#strain-selector').val(strain).multiselect('refresh');

    $('#strain-selector').multiselect('select', selected_strain).multiselect('refresh');
    $('#profession-selector')
      .multiselect('deselectAll', false)
      .multiselect('updateButtonText');
    $.each(professions, function(i, x) {
      $('#profession-selector').multiselect('select', x);
    });

    //$('#profession-selector').val(professions).multiselect('refresh');

    apply_strain_restrictions();
    restrict_profession_selector();
    update_profession_cost();
    update_strain_specs();
    update_strain_stats();
    recalculate();
    replan();
    //update_availability();

    relocate('#planned-list', planned_skills);
    relocate('#acquired-list', acquired_skills);
    //pack_state();
    update_xp_count('#planned');
    update_xp_count('#acquired');
    generate_constraints();
    update_selected_skills(0);
    update_beyond_basic();
    check_advanced_profession_constraints();
  } else {
    generate_constraints();
  }
}

function extract_skills() {
  var psion_regex = /^Psi [I]+ - /;

  var extract_skills_from_region = function(id) {
    var s = new Array();
    $(id + ' .skill-draggable').each(function() {
      if ($(this).hasClass('faded')) { return true; }
      var skill_name = $(this).attr('skill-name');

      if (skill_name.match(psion_regex)) {
        skill_name = skill_name.replace(psion_regex, '');
      }
      s.push(skill_list[skill_name]);
    })

    return s;
  }

  var acqs = extract_skills_from_region('#acquired');
  var plans = extract_skills_from_region('#planned');

  return {
    planned: plans,
    acquired: acqs
  }
}

function generate_inverted_skills() {
  return new Promise(
    function(resolve, reject) {
      skill_list_inverted = new Object();
      skill_list_special_group = new Object();

      $.each(skill_list, function(key, val) {
        skill_list_inverted[val] = key;
      })

      $.each(skill_groups, function(group_name, d) {
        $.each(d, function(skill_name, _junk) {
          skill_list_special_group[skill_name] = group_name;
        });
      });

      resolve();
    }
  )
}

$(function() {
  $.when(get_json_strain(),
         get_json_profession(),
         get_json_skill_cat(),
         get_json_strain_stats(),
         get_json_strain_specs(),
         get_json_profession_advanced(),
         get_json_profession_concentration()).done(function() {
    $.when(get_json_strain_restriction()).done(function() {
      $.when(get_json_skill_list()).done(function() {
        $('#init-completed').show();

        resize_graphical();
        generate_professions_select_box();
        generate_inverted_skills().then(function() {
          build_advanced_profession().then(function() {
            load_first_available_profile();

            init_completed = true;
            $('#loading [data-dismissible]').hide(500, function() {
              $('#loading').hide(1000);
            });
          });
        })
      });

    })
  })
  // $.when(get_json_strain(),
  //        get_json_profession(),
  //        get_json_skill_cat(),
  //        get_json_strain_restriction()).done(function() {
  //
  // })

});<commit_msg>Fix profile switching not clearing selected_advanced_profession.<commit_after>var skill_list;
var skill_list_inverted;
var skill_list_special_group;

function clear_cookies() {
  Cookies.remove('drpedia');
}

function pack_state() {
  if (!has_profile) { return; }

  var pack = $('#hp-addition').text() + '|'
           + $('#mp-addition').text() + '|'
           + (selected_strain || '') + '|'
           + (selected_professions || new Array()).join(',') + '|';
  var es = extract_skills();

  pack += es.acquired.join(',') + '|' + es.planned.join(',');
  Cookies.set(current_profile, pack, { expires: 365 });
  console.log('Packing to ' + current_profile + ': ' + pack);
}

function unpack_state() {
  if (!has_profile) { return; }

  var decrypt_psionic_skills = function(a) {
    var prefix = '';
    $.each(skill_groups, function(group_name, skills) {
      if (skills[a] != undefined) {
        switch (group_name) {
          case 'Psionic Skill - Basic': prefix = 'Psi I - '; break;
          case 'Psionic Skill - Intermediate': prefix = 'Psi II - '; break;
          case 'Psionic Skill - Advanced': prefix = 'Psi III - '; break;
        }

        return false;
      }
    });

    return prefix + a;
  }

  var decrypt_skills = function(a) {
    var output = new Array();

    $.each(a, function(i, x) {
      var lookup = skill_list_inverted[x];
      if (lookup != undefined) {
        output.push(lookup);
      }
    })
    return output;
  }

  var relocate = function(target_list_id, skill_list) {
    $.each(skill_list, function(i, x) {
      //console.log('relocating ' + x);
      var target_object = $('[skill-name="' + x + '"]');
      if (target_object.length == 0) {
        target_object = $('[skill-name="' + decrypt_psionic_skills(x) + '"]');
      }

      if (target_object) {
        //console.log(target_object.hasClass('faded') + ' ' + target_object.text());
        //if (!target_object.hasClass('faded')) {
        append_lexicographically(target_list_id, target_object);
        //}
      }
    })
  }

  var reset_all_skills = function(list_id) {
    var entries = new Array();

    $('#' + list_id + ' .list-group-item').each(function() {
      var entry = $(this).attr('skill-name');
      entries.push(entry);
    })

    relocate('#graphical-list', entries);
  }

  var unpack = current_profile == 'dummy' ? '0|0||||' : Cookies.get(current_profile);
  console.log('Unpack from ' + current_profile + ': ' + unpack);

  if (unpack != undefined) {
    var p0 = unpack.split('|');
    var hp = parseInt(p0[0]) || 0;
    var mp = parseInt(p0[1]) || 0;
    var strain = p0[2];

    reset_all_skills('acquired-list');
    reset_all_skills('planned-list');
    set_stat_build($('#hp-addition'), 'hp-total', hp, false);
    set_stat_build($('#mp-addition'), 'mp-total', mp, false);
    initialize_stats_controller('#hp-sub');
    initialize_stats_controller('#mp-sub');
    var professions = p0[3].split(',');
    var acquired_skills = decrypt_skills(p0[4].split(','));
    var planned_skills = decrypt_skills(p0[5].split(','));

    selected_strain = strain || 'Select Strain';

    selected_professions = new Array();
    selected_advanced_profession = undefined;
    $.each(professions, function(i, x) {
      if (advanced_profession_struct[x] == undefined) {
        selected_professions.push(x);
      } else {
        selected_advanced_profession = x;
      }
    })

    //selected_professions = professions;
    //$('#strain-selector').val(strain).multiselect('refresh');

    $('#strain-selector').multiselect('select', selected_strain).multiselect('refresh');
    $('#profession-selector')
      .multiselect('deselectAll', false)
      .multiselect('updateButtonText');
    $.each(professions, function(i, x) {
      $('#profession-selector').multiselect('select', x);
    });

    //$('#profession-selector').val(professions).multiselect('refresh');

    apply_strain_restrictions();
    restrict_profession_selector();
    update_profession_cost();
    update_strain_specs();
    update_strain_stats();
    recalculate();
    replan();
    //update_availability();

    relocate('#planned-list', planned_skills);
    relocate('#acquired-list', acquired_skills);
    //pack_state();
    update_xp_count('#planned');
    update_xp_count('#acquired');
    generate_constraints();
    update_selected_skills(0);
    update_beyond_basic();
    check_advanced_profession_constraints();
  } else {
    generate_constraints();
  }
}

function extract_skills() {
  var psion_regex = /^Psi [I]+ - /;

  var extract_skills_from_region = function(id) {
    var s = new Array();
    $(id + ' .skill-draggable').each(function() {
      if ($(this).hasClass('faded')) { return true; }
      var skill_name = $(this).attr('skill-name');

      if (skill_name.match(psion_regex)) {
        skill_name = skill_name.replace(psion_regex, '');
      }
      s.push(skill_list[skill_name]);
    })

    return s;
  }

  var acqs = extract_skills_from_region('#acquired');
  var plans = extract_skills_from_region('#planned');

  return {
    planned: plans,
    acquired: acqs
  }
}

function generate_inverted_skills() {
  return new Promise(
    function(resolve, reject) {
      skill_list_inverted = new Object();
      skill_list_special_group = new Object();

      $.each(skill_list, function(key, val) {
        skill_list_inverted[val] = key;
      })

      $.each(skill_groups, function(group_name, d) {
        $.each(d, function(skill_name, _junk) {
          skill_list_special_group[skill_name] = group_name;
        });
      });

      resolve();
    }
  )
}

$(function() {
  $.when(get_json_strain(),
         get_json_profession(),
         get_json_skill_cat(),
         get_json_strain_stats(),
         get_json_strain_specs(),
         get_json_profession_advanced(),
         get_json_profession_concentration()).done(function() {
    $.when(get_json_strain_restriction()).done(function() {
      $.when(get_json_skill_list()).done(function() {
        $('#init-completed').show();

        resize_graphical();
        generate_professions_select_box();
        generate_inverted_skills().then(function() {
          build_advanced_profession().then(function() {
            load_first_available_profile();

            init_completed = true;
            $('#loading [data-dismissible]').hide(500, function() {
              $('#loading').hide(1000);
            });
          });
        })
      });

    })
  })
  // $.when(get_json_strain(),
  //        get_json_profession(),
  //        get_json_skill_cat(),
  //        get_json_strain_restriction()).done(function() {
  //
  // })

});<|endoftext|>


<commit_before>$(document).ready(function(){
      $('.image-carousel').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        centerMode: true,
        centerPadding: '500px',
        responsive: [
          {
            breakpoint: 1440,
            settings: {
              slidesToShow: 3,
              slidesToScroll: 1,
              centerMode: false,
            }
          },
          // {
          //   breakpoint: 1024,
          //   settings: {
          //     slidesToShow: 3,
          //     slidesToScroll: 1,
          //     centerMode: false,
          //   }
          // },
          {
            breakpoint: 640,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1,
              fade: true,
              cssEase: 'linear'
            }
          },
        ]
      });
    });
<commit_msg>add 1024 breakpoint back in<commit_after>$(document).ready(function(){
      $('.image-carousel').slick({
        slidesToShow: 1,
        slidesToScroll: 1,
        autoplay: true,
        autoplaySpeed: 2000,
        centerMode: true,
        centerPadding: '500px',
        responsive: [
          {
            breakpoint: 1440,
            settings: {
              slidesToShow: 3,
              slidesToScroll: 1,
              centerMode: false,
            }
          },
          {
            breakpoint: 1024,
            settings: {
              slidesToShow: 3,
              slidesToScroll: 1,
              centerMode: false,
            }
          },
          {
            breakpoint: 640,
            settings: {
              slidesToShow: 1,
              slidesToScroll: 1,
              fade: true,
              cssEase: 'linear'
            }
          },
        ]
      });
    });
<|endoftext|>


<commit_before>define(["app/static", "htmlcomponent", "app/app"], function(static, htmlcomponent, main) {
	htmlcomponent.setStaticLoader(static);
	main.default();
});
<commit_msg>fixed reserved keyword<commit_after>define(["app/static", "htmlcomponent", "app/app"], function(staticComp, htmlcomponent, main) {
	htmlcomponent.setStaticLoader(staticComp);
	main.default();
});
<|endoftext|>


<commit_before><commit_msg>NEON-629 -- Updated table widget, removing OWF references from it.<commit_after><|endoftext|>


<commit_before>'use strict';
/*global $:false, FB:false, console:false, jQuery:false */

angular.module('fbCal').factory('server', function ($log, $http, $wix, api, $window) {
  var compId = $wix.Utils.getCompId();
  var instance = api.getInstance();

  var getSettingsWidgetURL = '/GetSettingsWidget/' + compId;
  var getSettingsSettingsURL = '/GetSettingsSettings/' + compId;
  var getAllEventsURL = '/GetAllEvents/' + compId;
  var saveSettingsURL = '/SaveSettings/' + compId;
  var saveAccessTokenURL = '/SaveAccessToken/' + compId;
  var logoutURL = '/Logout/' + compId;

  var defaultSettingsWidget = {settings : api.defaults, eventIds : [],
                               fb_event_data : {}, active : true};
  var defaultSettingsSettings = {settings : api.defaults, eventIds : [],
                                 active : true, name: ""};

  var getURL = function(requestType, from) {
    if (requestType === 'get') {
      if (from === 'widget') {
        return getSettingsWidgetURL;
      } else {
        return getSettingsSettingsURL;
      }
    } else {
      if (from === 'settings') {
        return saveSettingsURL;
      } else {
        return saveAccessTokenURL;
      }
    }
  };

  var getDefault = function(from) {
    if (from === 'widget') {
      return defaultSettingsWidget;
    } else {
      return defaultSettingsSettings;
    }
  };

  /**
   * This function makes a call to the backend database to get the
   * latest user settings. It's called whenever the widget or settings panal
   * is first loaded. On errors, the default settings are loaded.
   */
  var getUserInfo = function(from) {
    $http({
           method: 'GET',
           url: getURL('get', from),
           headers: {'X-Wix-Instance' : instance},
           timeout: 10000
          }).success(function (status, data) {
            console.log(status, data);
            if (status === 200) {
              console.log(data);
              return jQuery.parseJSON(data);
            } else {
              console.log('The server is returning an incorrect status.');
              return getDefault(from);
              //i don't really know what the fb_event_data looks like
            }
          }).error(function (status, message) {
            $log.warn(status, message);
            return getDefault(from);
          });
  };

  var getAllEvents = function() {
    $http({
           method: 'GET',
           url: getAllEventsURL,
           headers: {'X-Wix-Instance' : instance},
           timeout: 10000
          }).success(function (status, data) {
            console.log(status, data);
            if (status === 200) {
              console.log(data);
              return jQuery.parseJSON(data);
            } else {
              console.log('The server is returning an incorrect status.');
              return {};
              //i don't really know what the fb_event_data looks like
            }
          }).error(function (status, message) {
            $log.warn(status, message);
            return {};
          });
  };

  var saveData = function(data, dataType) {
    $http({
            method: 'PUT',
            url: getURL('post', dataType),
            headers: {'X-Wix-Instance' : instance, 'URL' : $window.location.hostname},
            timeout: 10000,
            data: data
          }).success(function (status, message) {
            console.log(status, message);
            if (status === 200) {
              console.log(dataType + ' saved successfully.');
              return true;
            } else {
              console.log('The server is returning an incorrect status.');
              return false;
            }
          }).error(function (status, message) {
            console.log(dataType + ' failed to save.');
            console.log(status);
            console.log(message);
            return false;
          });
  };

  var logout = function() {
    $http({
            method: 'PUT',
            url: logoutURL,
            headers: {'X-Wix-Instance' : instance, 'URL' : $window.location.hostname},
            timeout: 10000,
            data: {}
          }).success(function (status, message) {
            console.log(status, message);
            if (status === 200) {
              console.log('Logged out successfully.');
              return true;
            } else {
              console.log('The server is returning an incorrect status.');
              return false;
            }
          }).error(function (status, message) {
            console.log('Failed to logout.');
            console.log(status);
            console.log(message);
            return false;
          });
  };

});
<commit_msg>Wrote code for server to handle getting all event data from user and send to client<commit_after>'use strict';
/*global $:false, FB:false, console:false, jQuery:false */

angular.module('fbCal').factory('server', function ($log, $http, $wix, api, $window) {
  var compId = $wix.Utils.getCompId();
  var instance = api.getInstance();

  var getSettingsWidgetURL = '/GetSettingsWidget/' + compId;
  var getSettingsSettingsURL = '/GetSettingsSettings/' + compId;
  var getAllEventsURL = '/GetAllEvents/' + compId;
  var saveSettingsURL = '/SaveSettings/' + compId;
  var saveAccessTokenURL = '/SaveAccessToken/' + compId;
  var logoutURL = '/Logout/' + compId;

  var defaultSettingsWidget = {settings : api.defaults, eventIds : [],
                               fb_event_data : {}, active : true};
  var defaultSettingsSettings = {settings : api.defaults, eventIds : [],
                                 active : true, name: ""};

  var getURL = function(requestType, from) {
    if (requestType === 'get') {
      if (from === 'widget') {
        return getSettingsWidgetURL;
      } else {
        return getSettingsSettingsURL;
      }
    } else {
      if (from === 'settings') {
        return saveSettingsURL;
      } else {
        return saveAccessTokenURL;
      }
    }
  };

  var getDefault = function(from) {
    if (from === 'widget') {
      return defaultSettingsWidget;
    } else {
      return defaultSettingsSettings;
    }
  };

  /**
   * This function makes a call to the backend database to get the
   * latest user settings. It's called whenever the widget or settings panal
   * is first loaded. On errors, the default settings are loaded.
   */
  var getUserInfo = function(from) {
    $http({
           method: 'GET',
           url: getURL('get', from),
           headers: {'X-Wix-Instance' : instance},
           timeout: 10000
          }).success(function (status, data) {
            console.log(status, data);
            if (status === 200) {
              console.log(data);
              return jQuery.parseJSON(data);
            } else {
              console.log('The server is returning an incorrect status.');
              return getDefault(from);
              //i don't really know what the fb_event_data looks like
            }
          }).error(function (status, message) {
            $log.warn(status, message);
            return getDefault(from);
          });
  };

  var getAllEvents = function() {
    $http({
           method: 'GET',
           url: getAllEventsURL,
           headers: {'X-Wix-Instance' : instance},
           timeout: 10000
          }).success(function (status, data) {
            console.log(status, data);
            if (status === 200) {
              console.log(data);
              return jQuery.parseJSON(data);
            } else {
              console.log('The server is returning an incorrect status.');
              return {};
              //i don't really know what the fb_event_data looks like
            }
          }).error(function (status, message) {
            $log.warn(status, message);
            return {};
          });
  };

  var saveData = function(data, dataType) {
    $http({
            method: 'PUT',
            url: getURL('post', dataType),
            headers: {'X-Wix-Instance' : instance, 'URL' : $window.location.hostname},
            timeout: 10000,
            data: data
          }).success(function (status, message) {
            console.log(status, message);
            if (status === 200) {
              console.log(dataType + ' saved successfully.');
              return true;
            } else {
              console.log('The server is returning an incorrect status.');
              return false;
            }
          }).error(function (status, message) {
            console.log(dataType + ' failed to save.');
            console.log(status);
            console.log(message);
            return false;
          });
  };

  var logout = function() {
    $http({
            method: 'PUT',
            url: logoutURL,
            headers: {'X-Wix-Instance' : instance, 'URL' : $window.location.hostname},
            timeout: 10000,
            data: {}
          }).success(function (status, message) {
            console.log(status, message);
            if (status === 200) {
              console.log('Logged out successfully.');
              return true;
            } else {
              console.log('The server is returning an incorrect status.');
              return false;
            }
          }).error(function (status, message) {
            console.log('Failed to logout.');
            console.log(status);
            console.log(message);
            return false;
          });
  };
});
<|endoftext|>


<commit_before>'use strict'
let RequestAsync = require(`../lib/requestasync`)
let Promise = require(`bluebird`)
let { init, reset, RestClient } = require(`../lib/RestService`)

let apiUrl = () => {
  return `http://example.com`
}

describe(`call getOptions method in restFactory`, () => {
  let request
  let path = `/testUrl`
  let method = `post`
  let body = { data: `sadsadsad` }

  beforeEach(() => {
    init({ clients: [{ type: `wongnaiTest`, url: apiUrl() }] })
    request = RestClient.wongnaiTest()
    spyOn(request, `getOptions`).and.callThrough()
  })

  afterEach(() => {
    reset()
  })

  describe(`with path, method, and body parameter`, () => {
    it(`should response object include body property`, () => {
      let result = request.getOptions(path, method, body)
      let expected = {
        url: `${apiUrl()}${path}`,
        method: method,
        json: true,
        body: body,
        timeout: 10000,
      }

      expect(result).toEqual(expected)
    })
  })

  describe(`without body parameter`, () => {
    it(`should response object without body property`, () => {
      let result = request.getOptions(path, method)
      let expected = {
        url: `${apiUrl()}${path}`,
        method: method,
        json: true,
        timeout: 10000,
      }

      expect(result).toEqual(expected)
    })
  })

  describe(`with multipart`, () => {
    it(`should response body which is array`, () => {
      let result = request.getOptions(path, method, { formData: body })
      let expected = {
        url: `${apiUrl()}${path}`,
        method: method,
        timeout: 10000,
        formData: body,
      }

      expect(result).toEqual(expected)
    })
  })
})

describe(`RestClient`, () => {
  let headers = {
    'x-forwarded-for': `HeaderValue`,
    blacklist: `xxxxxxx`,
  }
  let RestConfig = { defaultHeaders: [`x-forwarded-for`], clients: [{ type: `test1`, url: `testUrl1` }, { type: `test2`, url: `testUrl2` }] }

  afterEach(() => {
    reset()
  })

  it(`init() must create a property in RestClient and return object with some headers in whiteList header`, () => {
    init(RestConfig)
    expect(RestClient.test1).toBeDefined()

    const tmp = RestClient.test1({ headers })
    expect(tmp.headers).toEqual({ 'x-forwarded-for': `HeaderValue` })
    expect(tmp.baseApi).toEqual(RestConfig.clients[0].url)
  })
  it(`defaultHeaders should apply to all client`, () => {
    init(RestConfig)
    const test1 = RestClient.test1({ headers })
    const test2 = RestClient.test2({ headers })
    expect(test1.headers).toEqual({ 'x-forwarded-for': `HeaderValue` })
    expect(test2.headers).toEqual({ 'x-forwarded-for': `HeaderValue` })
  })
  it(`set unique header for each client`, () => {
    init({ clients: [{ type: `test`, url: `testHeaderUrl`, headers: [`TEST-HEADER`, { 'X-HEADER': 1 }] }] })
    const tmp = RestClient.test()
    expect(tmp.headers).toEqual({ 'X-HEADER': 1 })
  })
})

describe(`create request with header`, () => {
  let headers = { 'x-forwarded-for': `HeaderValue` }
  let path = `/testUrl`
  let method = `get`
  let baseUrl = apiUrl()
  let request

  beforeEach(() => {
    init({ clients: [{ type: `wongnai`, url: baseUrl, headerCfg: ['x-forwarded-for'] }] })
    request = RestClient.wongnai({ headers })
    spyOn(request, `getOptions`).and.callThrough()
  })

  afterEach(() => {
    reset()
  })

  it(`should response object with headers property when getOptions have been called`, () => {
    let expected = {
      url: `${apiUrl()}${path}`,
      method: method,
      json: true,
      headers: headers,
      timeout: 10000
    }

    let result = request.getOptions(path, method)

    expect(result).toEqual(expected)
  })
  it(`should request to RequestAsync method with headers parameter when get have been called`, () => {
    let response = {
      statusCode: 200,
      body: `res`,
    }
    let option = request.getOptions(path, `get`) // getOptions is call #1
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    request.get(path) // getOptions is call #2

    expect(RequestAsync.request).toHaveBeenCalledWith(option)
    expect(RequestAsync.request).toHaveBeenCalledTimes(1)
    expect(request.getOptions).toHaveBeenCalledTimes(2)
  })
})

describe(`create new request with createRequest factory`, () => {
  let path = `/testUrl`
  let response = {
    statusCode: 200,
    body: `res`,
  }
  let request

  beforeEach(() => {
    init({ clients: [{ type: `wongnai`, url: `testUrl` }] })
    request = RestClient.wongnai()
  })

  afterEach(() => {
    reset()
  })

  it(`should call get method, and RequestAsync with correct options parameter`, () => {
    let option = request.getOptions(path, `get`)
    spyOn(request, `get`).and.callThrough()
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    request.get(path)

    expect(RequestAsync.request).toHaveBeenCalledWith(option)
    expect(RequestAsync.request).toHaveBeenCalledTimes(1)
    expect(request.get).toHaveBeenCalledWith(path)
    expect(request.get).toHaveBeenCalledTimes(1)
  })
  it(`should call post method, and RequestAsync with correct option parameter`, () => {
    let body = { test: `TEXT` }
    let option = request.getOptions(path, `post`, body)
    spyOn(request, `post`).and.callThrough()
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    request.post(path, body)

    expect(RequestAsync.request).toHaveBeenCalledWith(option)
    expect(RequestAsync.request).toHaveBeenCalledTimes(1)
    expect(request.post).toHaveBeenCalledWith(path, body)
    expect(request.post).toHaveBeenCalledTimes(1)
  })
})

describe(`call request method but got bad request response`, () => {
  let restClient

  beforeEach(() => {
    init({ clients: [{ type: `TEST`, url: `URL` }] })
    restClient = RestClient.TEST()
  })

  afterEach(() => {
    reset()
  })

  it(`should create Error element`, (done) => {
    let response = {
      statusCode: 400,
      body: `body`,
    }
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    restClient.post(`/testUrl`, {})
      .error((e) => {
        expect(e.isOperational).toEqual(true)
        expect(e.body).toEqual(response.body)
        expect(e).toEqual(jasmine.any(Error))
        done()
      })
  })
})
<commit_msg>fix bug for node v5<commit_after>'use strict'
let RequestAsync = require(`../lib/requestasync`)
let Promise = require(`bluebird`)
let RestService = require(`../lib/RestService`)
let init = RestService.init
let reset = RestService.reset
let RestClient = RestService.RestClient

let apiUrl = () => {
  return `http://example.com`
}

describe(`call getOptions method in restFactory`, () => {
  let request
  let path = `/testUrl`
  let method = `post`
  let body = { data: `sadsadsad` }

  beforeEach(() => {
    init({ clients: [{ type: `wongnaiTest`, url: apiUrl() }] })
    request = RestClient.wongnaiTest()
    spyOn(request, `getOptions`).and.callThrough()
  })

  afterEach(() => {
    reset()
  })

  describe(`with path, method, and body parameter`, () => {
    it(`should response object include body property`, () => {
      let result = request.getOptions(path, method, body)
      let expected = {
        url: `${apiUrl()}${path}`,
        method: method,
        json: true,
        body: body,
        timeout: 10000,
      }

      expect(result).toEqual(expected)
    })
  })

  describe(`without body parameter`, () => {
    it(`should response object without body property`, () => {
      let result = request.getOptions(path, method)
      let expected = {
        url: `${apiUrl()}${path}`,
        method: method,
        json: true,
        timeout: 10000,
      }

      expect(result).toEqual(expected)
    })
  })

  describe(`with multipart`, () => {
    it(`should response body which is array`, () => {
      let result = request.getOptions(path, method, { formData: body })
      let expected = {
        url: `${apiUrl()}${path}`,
        method: method,
        timeout: 10000,
        formData: body,
      }

      expect(result).toEqual(expected)
    })
  })
})

describe(`RestClient`, () => {
  let headers = {
    'x-forwarded-for': `HeaderValue`,
    blacklist: `xxxxxxx`,
  }
  let RestConfig = { defaultHeaders: [`x-forwarded-for`], clients: [{ type: `test1`, url: `testUrl1` }, { type: `test2`, url: `testUrl2` }] }

  afterEach(() => {
    reset()
  })

  it(`init() must create a property in RestClient and return object with some headers in whiteList header`, () => {
    init(RestConfig)
    expect(RestClient.test1).toBeDefined()

    const tmp = RestClient.test1({ headers })
    expect(tmp.headers).toEqual({ 'x-forwarded-for': `HeaderValue` })
    expect(tmp.baseApi).toEqual(RestConfig.clients[0].url)
  })
  it(`defaultHeaders should apply to all client`, () => {
    init(RestConfig)
    const test1 = RestClient.test1({ headers })
    const test2 = RestClient.test2({ headers })
    expect(test1.headers).toEqual({ 'x-forwarded-for': `HeaderValue` })
    expect(test2.headers).toEqual({ 'x-forwarded-for': `HeaderValue` })
  })
  it(`set unique header for each client`, () => {
    init({ clients: [{ type: `test`, url: `testHeaderUrl`, headers: [`TEST-HEADER`, { 'X-HEADER': 1 }] }] })
    const tmp = RestClient.test()
    expect(tmp.headers).toEqual({ 'X-HEADER': 1 })
  })
})

describe(`create request with header`, () => {
  let headers = { 'x-forwarded-for': `HeaderValue` }
  let path = `/testUrl`
  let method = `get`
  let baseUrl = apiUrl()
  let request

  beforeEach(() => {
    init({ clients: [{ type: `wongnai`, url: baseUrl, headerCfg: ['x-forwarded-for'] }] })
    request = RestClient.wongnai({ headers })
    spyOn(request, `getOptions`).and.callThrough()
  })

  afterEach(() => {
    reset()
  })

  it(`should response object with headers property when getOptions have been called`, () => {
    let expected = {
      url: `${apiUrl()}${path}`,
      method: method,
      json: true,
      headers: headers,
      timeout: 10000
    }

    let result = request.getOptions(path, method)

    expect(result).toEqual(expected)
  })
  it(`should request to RequestAsync method with headers parameter when get have been called`, () => {
    let response = {
      statusCode: 200,
      body: `res`,
    }
    let option = request.getOptions(path, `get`) // getOptions is call #1
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    request.get(path) // getOptions is call #2

    expect(RequestAsync.request).toHaveBeenCalledWith(option)
    expect(RequestAsync.request).toHaveBeenCalledTimes(1)
    expect(request.getOptions).toHaveBeenCalledTimes(2)
  })
})

describe(`create new request with createRequest factory`, () => {
  let path = `/testUrl`
  let response = {
    statusCode: 200,
    body: `res`,
  }
  let request

  beforeEach(() => {
    init({ clients: [{ type: `wongnai`, url: `testUrl` }] })
    request = RestClient.wongnai()
  })

  afterEach(() => {
    reset()
  })

  it(`should call get method, and RequestAsync with correct options parameter`, () => {
    let option = request.getOptions(path, `get`)
    spyOn(request, `get`).and.callThrough()
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    request.get(path)

    expect(RequestAsync.request).toHaveBeenCalledWith(option)
    expect(RequestAsync.request).toHaveBeenCalledTimes(1)
    expect(request.get).toHaveBeenCalledWith(path)
    expect(request.get).toHaveBeenCalledTimes(1)
  })
  it(`should call post method, and RequestAsync with correct option parameter`, () => {
    let body = { test: `TEXT` }
    let option = request.getOptions(path, `post`, body)
    spyOn(request, `post`).and.callThrough()
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    request.post(path, body)

    expect(RequestAsync.request).toHaveBeenCalledWith(option)
    expect(RequestAsync.request).toHaveBeenCalledTimes(1)
    expect(request.post).toHaveBeenCalledWith(path, body)
    expect(request.post).toHaveBeenCalledTimes(1)
  })
})

describe(`call request method but got bad request response`, () => {
  let restClient

  beforeEach(() => {
    init({ clients: [{ type: `TEST`, url: `URL` }] })
    restClient = RestClient.TEST()
  })

  afterEach(() => {
    reset()
  })

  it(`should create Error element`, (done) => {
    let response = {
      statusCode: 400,
      body: `body`,
    }
    spyOn(RequestAsync, `request`).and.returnValue(Promise.resolve(response))

    restClient.post(`/testUrl`, {})
      .error((e) => {
        expect(e.isOperational).toEqual(true)
        expect(e.body).toEqual(response.body)
        expect(e).toEqual(jasmine.any(Error))
        done()
      })
  })
})
<|endoftext|>


<commit_before>import AutoComplete from "ember-cli-auto-complete/components/auto-complete";
import config from '../config/environment';
import Ember from 'ember';

export default AutoComplete.extend({
    valueProperty: "id",

    suggestions: function() {
        return this.get("options");
    }.property("options.@each"),

    loadMatches: function() {
        var self = this;
        var inputVal = this.get("inputVal");
        if (!inputVal || inputVal.length < 3) {
            return;
        }
        var esSearchBody = {
            "name-suggest": {
                "text": inputVal,
                "completion": {
                    "field": "suggest",
                    "size": 10,
                    "fuzzy": {
                        "fuzziness": 2
                    }
                }
            }
        };
        var ops = [];
        Ember.$.ajax({
            type: "POST",
            url: config.elasticsearchPath + '/orgs/_suggest',
            data: JSON.stringify(esSearchBody),
            success: function(data) {
                self.set('options', []);
                var store = self.get('container').lookup('store:main');
                var dedup = {};
                Ember.$.each(data["name-suggest"][0].options, function(i, obj) {
                    var id = obj.payload.orgId;
                    if (id && !(id in dedup)) {
                        //dedup
                        dedup[id] = true;
                        store.find('organizations/org', id).then(function(org) {
                            ops.pushObject(org.get('profile'));
                        });
                    } else {
                        console.debug("duplicate ignored: " + id);
                    }
                    self.set('options', ops);
                });
            },
            error: function(e) {
                console.error("Unable to search." + e);
                self.set('options', []);
            },
            dataType: 'json'
        });
    }.observes("inputVal"),

    optionsToMatch: function() {
        return this.get("options");
    }.property("options.@each"),

    actions: {
        selectItem: function(item) {
            this.setProperties({
                'parentView.controller.selectSuggestion': item,
                'options': [],
                'inputVal': ""
            });
            this.focusOut();
        }
    }
});<commit_msg>Attempt to improve the autocomplete to avoid strange race condition<commit_after>import AutoComplete from "ember-cli-auto-complete/components/auto-complete";
import config from '../config/environment';
import Ember from 'ember';

export default AutoComplete.extend({
    valueProperty: "id",

    init: function() {
        this.store = this.get('container').lookup('store:main');
        this._super(arguments);
    },

    suggestions: Ember.computed.mapBy('organizations', 'profile'),
    options: Ember.computed.mapBy('organizations', 'profile'),

    loadMatches: function() {
        // var self = this;
        var inputVal = this.get("inputVal");
        if (!inputVal || inputVal.length < 3) {
            return;
        }

        var query = Ember.$.ajax({
            type: "POST",
            url: config.elasticsearchPath + '/orgs/_suggest',
            data: JSON.stringify({
                "name-suggest": {
                    "text": inputVal,
                    "completion": {
                        "field": "suggest",
                        "size": 10,
                        "fuzzy": {
                            "fuzziness": 2
                        }
                    }
                }
            })
        });

        query.then(function(data) {
            Ember.run.later(this, function() {
                var ids = Ember.Set.create();
                var organizations = Ember.EnumerableUtils.filter(data['name-suggest'][0].options, function(option) {
                    var id = option.payload.orgId;
                    var isDuplicate = ids.contains(id);
                    ids.add(id);
                    return !isDuplicate;
                }).map(function(option) {
                    return this.store.find('organizations/org', option.payload.orgId);
                }, this);

                this.set('organizations', organizations);
            });
        }.bind(this), function(error) {
            console.error('Search failed', error);
            Ember.run.later(this, function() {
                this.set('organizations', Ember.A);
            });
        });
    }.observes("inputVal"),

    optionsToMatch: function() {
        return this.get("options");
    }.property("options.@each"),

    actions: {
        selectItem: function(item) {
            this.setProperties({
                'parentView.controller.selectSuggestion': item,
                'options': [],
                'inputVal': ""
            });
            this.focusOut();
        }
    }
});<|endoftext|>