<commit_before>// remap jQuery to $
(function($) {

  $(function() {

    /*** MAIN CODE ***/

    // Resize iframe with window
    $(window).resize(function () {
      $('#source').height($(document).height() - $('#main').height());
    });

    // Empty iframe if cached
    $('#source').removeAttr("src");

    /*** HOME ***/
    if ($('body').is('.home')) {
      // Update URL and project values
      var locale = ($('#server').data('locale') || $('#server').data('accept-language')).toLowerCase();
      if ($('.locale .menu .language.' + locale).length === 0) { // Locale not on the list
        locale = $('.locale .menu .language').attr('class').split(' ')[1];
      }
      $('.url').val($('#server').data('url'));
      $('.locale .button .language').addClass(locale).html($('.locale .menu .language.' + locale).html());

      $('#project-load').hide();
      $('#intro').css('display', 'table').hide().fadeIn();

      // Authentication and profile menu
      $("#browserid").click(function(e) {
        $('#loading').toggleClass('loader').html(' ');
        e.preventDefault();
        navigator.id.get(function(assertion) {
          if (assertion) {
            $.ajax({
              url: 'browserid/',
              type: 'POST',
              data: {
                assertion: assertion,
                csrfmiddlewaretoken: $('#server').data('csrf')
              },
              success: function(data) {
                if (data !== 'error') {
                  $('#action').remove();
                  $('#signout').removeClass('hidden').find('a').attr('title', data.browserid.email);
                  if (data.manager) {
                    $('#admin').removeClass('hidden');
                  }
                  if (data.localizer) {
                    $('form').removeClass('hidden');
                    $('.notification').addClass('hidden').removeClass('center');
                  } else {
                    $('.notification').html('
You don\'t have permission to localize.
').removeClass('hidden');
                  }
                } else {
                  $('.notification').html('
Oops, something went wrong.
').removeClass('hidden');
                  $('#loading').toggleClass('loader').html('or');
                }
              },
              error: function() {
                $('.notification').html('
Oops, something went wrong.
').removeClass('hidden');
                $('#loading').toggleClass('loader').html('or');
              }
            });
          } else {
            $('#loading').toggleClass('loader').html('or');
          }
        });
      });

    /*** TRANSLATE ***/
    } else if ($('body').is('.translate')) {
      var url = $('#server').data('url'),
          locale = $('#server').data('locale'),
          escapedLocale = locale.replace(".", "\\.").replace("@", "\\@"),
          projectWindow = null;

      // Initialize Pontoon only if project code supports it
      function receiveMessage(e) {
        // TODO: Check origin - hardcode Pontoon domain name
        if (JSON.parse(e.data).type === "SUPPORTED") {
          $('#main').slideDown(function() {
            $('#source').show().height($(document).height() - $(this).height());
            $('#project-load').hide();
          });
          Pontoon.init(window, projectWindow, locale);
          window.removeEventListener("message", receiveMessage, false);
        }
      }
      window.addEventListener("message", receiveMessage, false);

      $('.url').val(url);
      $('.locale .button .language').addClass(escapedLocale).html($('.locale .menu .language.' + escapedLocale).html());
      if ($('#server').data('external') !== true) {
        $('#source').attr('src', url);
        projectWindow = $('#source')[0].contentWindow;
      } else {
        $('#switch, #drag').remove();
        $('#main').prepend($('#entitylist').remove()).toggleClass('opened');
        $(window).resize(function () {
          $('#entitylist').height($(document).height() - $('#main > header').outerHeight());
        });
        $("#entitylist").height($(document).height() - $('#main > header').outerHeight());
        projectWindow = window.open(url, 'project', 'width=320,height=480,toolbar=1,resizable=1,scrollbars=1');
      }

      // Show error message if no callback for 30 seconds: Pontoon/iframe not supported, 404…
      var i = 0,
          interval = setInterval(function() {
            if (i < 300) {
              i++;
              if (Pontoon.app) { // Set in Pontoon.init() which is called on "supported"
                clearInterval(interval);
              }
            } else {
              clearInterval(interval);
              var lang = $('html').attr('lang'),
                  errorLink = (lang ? '/' + lang : '') + '/translate/error/?locale=' + escapedLocale + '&url=' + url + (url[url.length-1] !== '/' ? '/' : '');
              if (projectWindow) {
                window.location = errorLink + '&error=' + "Oops, website is not supported by Pontoon.";
                projectWindow.close();
              } else {
                window.location = errorLink + '&error=' + 'Oops, looks like pop-ups are blocked.';
              }
            }
          }, 100);

      // Resizable
      var mouseMoveHandler = function(e) {
        var initial = e.data.initial,
            u = Math.min(Math.max(initial.uHeight + (e.pageY - initial.offTop), initial.min), initial.max),
            b = Math.min(Math.max(initial.bHeight - (e.pageY - initial.offTop), initial.min), initial.max);
        initial.up.height(u);
        initial.below.height(b);

        $('#iframe-cover').height(initial.up.height()); // iframe fix
      };
      var mouseUpHandler = function(e) {
        $(document)
          .unbind('mousemove', mouseMoveHandler)
          .unbind('mouseup', mouseUpHandler);

        $('#iframe-cover').hide(); // iframe fix
        if (e.data.initial.below.height() === 0) {
          $('#main').removeClass('opened');
          Pontoon.common.postMessage("MODE", "Advanced");
        } else {
          $('#main').addClass('opened');
          Pontoon.common.postMessage("MODE", "Basic");
        }
      };
      $('#drag').bind('mousedown', function(e) {
        e.preventDefault();

        var up = $('#source'),
            below = $('#entitylist'),
            data = {
              up: up,
              below: below,
              uHeight: up.height(),
              bHeight: below.height(),
              offTop: e.pageY,
              min: 0,
              max: $(document).height() - $("#main header").outerHeight()
            };

        // iframe fix: Prevent iframes from capturing the mousemove events during a drag
        $('#iframe-cover').show().height(up.height());

        $(document)
          .bind('mousemove', { initial: data }, mouseMoveHandler)
          .bind('mouseup', { initial: data }, mouseUpHandler);
      });

    /*** ADMIN */
    } else if ($('body').is('.admin')) {
      // Unhover on add hover
      $('.project .menu .add').hover(function() {
        $('.project .menu ul li').removeClass('hover');
      }, function() {});

      // Edit project if selected from the menu
      $('.project .menu li').live("click.pontoon", function (e) {
        e.preventDefault();
        $('.url').val($(this).find('.project-name').html());
        window.location = 'admin/project/' + $(this).find('.project-name').html();
      });

      // Edit or add project if URL typed and Enter pressed
      $('.url').unbind("keydown.pontoon").bind("keydown.pontoon", function (e) {
        var key = e.keyCode || e.which;
        if (key === 13) { // Enter
          window.location = 'admin/project/' + $(this).val();
          return false;
        }
      });

    /*** ADMIN PROJECT ***/
    } else if ($('body').is('.admin-form')) {
      // Before submitting the form
      $('form').submit(function (e) {
        // Update locales
        var arr = [];
        $("#selected").siblings('ul').find('li:not(".no-match")').each(function() {
          arr.push($(this).data('id'));
        });
        $('#id_locales').val(arr);

        // Append slash to the URL field
        var url = $('#id_url').val();
        if (url.length > 0 && url[url.length-1] !== '/') {
          $('#id_url').val(url + '/');
        }

        // Update form action
        var name = $('#id_name').val();
        if (name.length > 0) {
          name += '/';
        }
        $('form').attr('action', $('form').attr('action').split('/project/')[0] + '/project/' + name);
      });

      // Submit form with Enter
      $('html').unbind("keydown.pontoon").bind("keydown.pontoon", function (e) {
        if ($('input[type=text]:not(".search, #id_transifex_username, #id_transifex_password"):focus').length > 0) {
          var key = e.keyCode || e.which;
          if (key === 13) { // Enter
            // A short delay to allow digest of autocomplete before submit
            setTimeout(function() {
              $('form').submit();
            }, 1);
            return false;
          }
        }
      });

      // Choose locales
      $('.locale.select li').live('click.pontoon', function (e) {
        var target = $(this).parents('.locale.select').siblings('.locale.select').find('ul'),
            clone = $(this).remove();
        target.prepend(clone);
      });

      // Choose/remove all locales
      $('.choose-all, .remove-all').live('click.pontoon', function (e) {
        e.preventDefault();
        var ls = $(this).parents('.locale.select'),
            target = ls.siblings('.locale.select').find('ul'),
            items = ls.find('li:visible:not(".no-match")').remove();
        target.prepend(items);
      });

      // Select repository type
      $('body').live("click.pontoon", function () {
        $('.repository .menu').hide();
        $('.select').removeClass('opened');
      });
      $('.repository .type li').live("click.pontoon", function () {
        var selected = $(this).html(),
            selected_lower = selected.toLowerCase();
        $(this).parents('.select').find('.title').html(selected);
        $('#id_repository_type').val(selected_lower);
        $('.details-wrapper').attr('data-repository-type', selected_lower);
      });
      // Show human-readable value
      $('.repository .type li[data-type=' + $('#id_repository_type').val() + ']').click();

      // Update from repository
      $('.repository .update:not(".disabled"), .transifex .update:not(".disabled")').unbind('click.pontoon').bind('click.pontoon', function (e) {
        e.preventDefault();
        $(this).addClass('disabled');
        var source = $(this).data('source'),
            img = $(this).find('img');

        function updateIcon(filename) {
          img.attr('src', '/static/img/' + filename);
        }
        updateIcon('loader-light.gif');

        params = {
          pk: $('input[name=pk]').val(),
          csrfmiddlewaretoken: $('#server').data('csrf')
        }
        if (source === 'repository') {
          params.repository_url = $('input[name=repository_url]').val();
          params.repository_type = $('select[name=repository_type]').val();
        } else if (source === 'transifex') {
          if ($(this).parents('.popup').length === 0) {
            project = $('.transifex input#id_transifex_project');
            resource = $('.transifex input#id_transifex_resource');
            params[project.attr('name')] = project.val();
            params[resource.attr('name')] = resource.val();
          } else {
            $('.transifex input').each(function() {
              var val = $(this).val();
              if (val) {
                if ($(this).attr('name') === 'remember') {
                  params[$(this).attr('name')] = ($(this).is(':checked')) ? "on" : "off";
                } else {
                  params[$(this).attr('name')] = val;
                }
              }
            });
          }
        }

        $.ajax({
          url: '/admin/' + source + '/',
          type: 'POST',
          data: params,
          success: function(data) {
            if (data === "200") {
              updateIcon('ok.png');
              $('.repository').removeClass('authenticate');
              $('.warning').fadeOut();
            } else if (data === "authenticate") {
              updateIcon('update.png');
              $('.repository').addClass('authenticate');
            } else if (data === "error"){
              updateIcon('error.png');
            }
          },
          error: function() {
            updateIcon('error.png');
          }
        }).complete(function() {
          img.parent().removeClass('disabled');
          setTimeout(function() {
            updateIcon('update.png');
          }, 5000);
        });
      });

      // Delete subpage
      $('.delete-subpage').live('click.pontoon', function (e) {
        e.preventDefault();
        $(this).toggleClass('active');
        $(this).next().prop('checked', !$(this).next().prop('checked'));
      });
      $('.subpages [checked]').click().prev().click();

      // Add subpage
      var count = $('.subpages:last').data('count');
      $('.add-subpage').click(function(e) {
        e.preventDefault();
        var form = $('.subpages:last').html().replace(/__prefix__/g, count);
        $('.subpages:last').before('
' + form + '
');
        count++;
        $('#id_subpage_set-TOTAL_FORMS').val(count);
      });

      // Delete project
      $('.delete-project').live('click.pontoon', function (e) {
        e.preventDefault();
        if ($(this).is('.clicked')) {
          window.location = '/admin/delete/' + $('input[name=pk]').val();
        } else {
          $(this).addClass('clicked').html('Are you sure?');
        }
      });
    }
  });

}(this.jQuery));

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if (this.console) {
    console.log(Array.prototype.slice.call(arguments));
  }
};

// catch all document.write() calls
(function(doc) {
  var write = doc.write;
  doc.write = function(q) {
    log('document.write(): ', arguments);
    if (/docwriteregexwhitelist/.test(q)) {
      write.apply(doc,arguments);
    }
  };
}(document));
<commit_msg>Move site-specific JS to site-specific block<commit_after>// remap jQuery to $
(function($) {

  $(function() {

    /*** HOME ***/
    if ($('body').is('.home')) {
      // Update URL and project values
      var locale = ($('#server').data('locale') || $('#server').data('accept-language')).toLowerCase();
      if ($('.locale .menu .language.' + locale).length === 0) { // Locale not on the list
        locale = $('.locale .menu .language').attr('class').split(' ')[1];
      }
      $('.url').val($('#server').data('url'));
      $('.locale .button .language').addClass(locale).html($('.locale .menu .language.' + locale).html());

      $('#project-load').hide();
      $('#intro').css('display', 'table').hide().fadeIn();

      // Authentication and profile menu
      $("#browserid").click(function(e) {
        $('#loading').toggleClass('loader').html(' ');
        e.preventDefault();
        navigator.id.get(function(assertion) {
          if (assertion) {
            $.ajax({
              url: 'browserid/',
              type: 'POST',
              data: {
                assertion: assertion,
                csrfmiddlewaretoken: $('#server').data('csrf')
              },
              success: function(data) {
                if (data !== 'error') {
                  $('#action').remove();
                  $('#signout').removeClass('hidden').find('a').attr('title', data.browserid.email);
                  if (data.manager) {
                    $('#admin').removeClass('hidden');
                  }
                  if (data.localizer) {
                    $('form').removeClass('hidden');
                    $('.notification').addClass('hidden').removeClass('center');
                  } else {
                    $('.notification').html('
You don\'t have permission to localize.
').removeClass('hidden');
                  }
                } else {
                  $('.notification').html('
Oops, something went wrong.
').removeClass('hidden');
                  $('#loading').toggleClass('loader').html('or');
                }
              },
              error: function() {
                $('.notification').html('
Oops, something went wrong.
').removeClass('hidden');
                $('#loading').toggleClass('loader').html('or');
              }
            });
          } else {
            $('#loading').toggleClass('loader').html('or');
          }
        });
      });

    /*** TRANSLATE ***/
    } else if ($('body').is('.translate')) {
      var url = $('#server').data('url'),
          locale = $('#server').data('locale'),
          escapedLocale = locale.replace(".", "\\.").replace("@", "\\@"),
          projectWindow = null;

      // Resize iframe with window
      $(window).resize(function () {
        $('#source').height($(document).height() - $('#main').height());
      });

      // Empty iframe if cached
      $('#source').removeAttr("src");

      // Initialize Pontoon only if project code supports it
      function receiveMessage(e) {
        // TODO: Check origin - hardcode Pontoon domain name
        if (JSON.parse(e.data).type === "SUPPORTED") {
          $('#main').slideDown(function() {
            $('#source').show().height($(document).height() - $(this).height());
            $('#project-load').hide();
          });
          Pontoon.init(window, projectWindow, locale);
          window.removeEventListener("message", receiveMessage, false);
        }
      }
      window.addEventListener("message", receiveMessage, false);

      $('.url').val(url);
      $('.locale .button .language').addClass(escapedLocale).html($('.locale .menu .language.' + escapedLocale).html());
      if ($('#server').data('external') !== true) {
        $('#source').attr('src', url);
        projectWindow = $('#source')[0].contentWindow;
      } else {
        $('#switch, #drag').remove();
        $('#main').prepend($('#entitylist').remove()).toggleClass('opened');
        $(window).resize(function () {
          $('#entitylist').height($(document).height() - $('#main > header').outerHeight());
        });
        $("#entitylist").height($(document).height() - $('#main > header').outerHeight());
        projectWindow = window.open(url, 'project', 'width=320,height=480,toolbar=1,resizable=1,scrollbars=1');
      }

      // Show error message if no callback for 30 seconds: Pontoon/iframe not supported, 404…
      var i = 0,
          interval = setInterval(function() {
            if (i < 300) {
              i++;
              if (Pontoon.app) { // Set in Pontoon.init() which is called on "supported"
                clearInterval(interval);
              }
            } else {
              clearInterval(interval);
              var lang = $('html').attr('lang'),
                  errorLink = (lang ? '/' + lang : '') + '/translate/error/?locale=' + escapedLocale + '&url=' + url + (url[url.length-1] !== '/' ? '/' : '');
              if (projectWindow) {
                window.location = errorLink + '&error=' + "Oops, website is not supported by Pontoon.";
                projectWindow.close();
              } else {
                window.location = errorLink + '&error=' + 'Oops, looks like pop-ups are blocked.';
              }
            }
          }, 100);

      // Resizable
      var mouseMoveHandler = function(e) {
        var initial = e.data.initial,
            u = Math.min(Math.max(initial.uHeight + (e.pageY - initial.offTop), initial.min), initial.max),
            b = Math.min(Math.max(initial.bHeight - (e.pageY - initial.offTop), initial.min), initial.max);
        initial.up.height(u);
        initial.below.height(b);

        $('#iframe-cover').height(initial.up.height()); // iframe fix
      };
      var mouseUpHandler = function(e) {
        $(document)
          .unbind('mousemove', mouseMoveHandler)
          .unbind('mouseup', mouseUpHandler);

        $('#iframe-cover').hide(); // iframe fix
        if (e.data.initial.below.height() === 0) {
          $('#main').removeClass('opened');
          Pontoon.common.postMessage("MODE", "Advanced");
        } else {
          $('#main').addClass('opened');
          Pontoon.common.postMessage("MODE", "Basic");
        }
      };
      $('#drag').bind('mousedown', function(e) {
        e.preventDefault();

        var up = $('#source'),
            below = $('#entitylist'),
            data = {
              up: up,
              below: below,
              uHeight: up.height(),
              bHeight: below.height(),
              offTop: e.pageY,
              min: 0,
              max: $(document).height() - $("#main header").outerHeight()
            };

        // iframe fix: Prevent iframes from capturing the mousemove events during a drag
        $('#iframe-cover').show().height(up.height());

        $(document)
          .bind('mousemove', { initial: data }, mouseMoveHandler)
          .bind('mouseup', { initial: data }, mouseUpHandler);
      });

    /*** ADMIN */
    } else if ($('body').is('.admin')) {
      // Unhover on add hover
      $('.project .menu .add').hover(function() {
        $('.project .menu ul li').removeClass('hover');
      }, function() {});

      // Edit project if selected from the menu
      $('.project .menu li').live("click.pontoon", function (e) {
        e.preventDefault();
        $('.url').val($(this).find('.project-name').html());
        window.location = 'admin/project/' + $(this).find('.project-name').html();
      });

      // Edit or add project if URL typed and Enter pressed
      $('.url').unbind("keydown.pontoon").bind("keydown.pontoon", function (e) {
        var key = e.keyCode || e.which;
        if (key === 13) { // Enter
          window.location = 'admin/project/' + $(this).val();
          return false;
        }
      });

    /*** ADMIN PROJECT ***/
    } else if ($('body').is('.admin-form')) {
      // Before submitting the form
      $('form').submit(function (e) {
        // Update locales
        var arr = [];
        $("#selected").siblings('ul').find('li:not(".no-match")').each(function() {
          arr.push($(this).data('id'));
        });
        $('#id_locales').val(arr);

        // Append slash to the URL field
        var url = $('#id_url').val();
        if (url.length > 0 && url[url.length-1] !== '/') {
          $('#id_url').val(url + '/');
        }

        // Update form action
        var name = $('#id_name').val();
        if (name.length > 0) {
          name += '/';
        }
        $('form').attr('action', $('form').attr('action').split('/project/')[0] + '/project/' + name);
      });

      // Submit form with Enter
      $('html').unbind("keydown.pontoon").bind("keydown.pontoon", function (e) {
        if ($('input[type=text]:not(".search, #id_transifex_username, #id_transifex_password"):focus').length > 0) {
          var key = e.keyCode || e.which;
          if (key === 13) { // Enter
            // A short delay to allow digest of autocomplete before submit
            setTimeout(function() {
              $('form').submit();
            }, 1);
            return false;
          }
        }
      });

      // Choose locales
      $('.locale.select li').live('click.pontoon', function (e) {
        var target = $(this).parents('.locale.select').siblings('.locale.select').find('ul'),
            clone = $(this).remove();
        target.prepend(clone);
      });

      // Choose/remove all locales
      $('.choose-all, .remove-all').live('click.pontoon', function (e) {
        e.preventDefault();
        var ls = $(this).parents('.locale.select'),
            target = ls.siblings('.locale.select').find('ul'),
            items = ls.find('li:visible:not(".no-match")').remove();
        target.prepend(items);
      });

      // Select repository type
      $('body').live("click.pontoon", function () {
        $('.repository .menu').hide();
        $('.select').removeClass('opened');
      });
      $('.repository .type li').live("click.pontoon", function () {
        var selected = $(this).html(),
            selected_lower = selected.toLowerCase();
        $(this).parents('.select').find('.title').html(selected);
        $('#id_repository_type').val(selected_lower);
        $('.details-wrapper').attr('data-repository-type', selected_lower);
      });
      // Show human-readable value
      $('.repository .type li[data-type=' + $('#id_repository_type').val() + ']').click();

      // Update from repository
      $('.repository .update:not(".disabled"), .transifex .update:not(".disabled")').unbind('click.pontoon').bind('click.pontoon', function (e) {
        e.preventDefault();
        $(this).addClass('disabled');
        var source = $(this).data('source'),
            img = $(this).find('img');

        function updateIcon(filename) {
          img.attr('src', '/static/img/' + filename);
        }
        updateIcon('loader-light.gif');

        params = {
          pk: $('input[name=pk]').val(),
          csrfmiddlewaretoken: $('#server').data('csrf')
        }
        if (source === 'repository') {
          params.repository_url = $('input[name=repository_url]').val();
          params.repository_type = $('select[name=repository_type]').val();
        } else if (source === 'transifex') {
          if ($(this).parents('.popup').length === 0) {
            project = $('.transifex input#id_transifex_project');
            resource = $('.transifex input#id_transifex_resource');
            params[project.attr('name')] = project.val();
            params[resource.attr('name')] = resource.val();
          } else {
            $('.transifex input').each(function() {
              var val = $(this).val();
              if (val) {
                if ($(this).attr('name') === 'remember') {
                  params[$(this).attr('name')] = ($(this).is(':checked')) ? "on" : "off";
                } else {
                  params[$(this).attr('name')] = val;
                }
              }
            });
          }
        }

        $.ajax({
          url: '/admin/' + source + '/',
          type: 'POST',
          data: params,
          success: function(data) {
            if (data === "200") {
              updateIcon('ok.png');
              $('.repository').removeClass('authenticate');
              $('.warning').fadeOut();
            } else if (data === "authenticate") {
              updateIcon('update.png');
              $('.repository').addClass('authenticate');
            } else if (data === "error"){
              updateIcon('error.png');
            }
          },
          error: function() {
            updateIcon('error.png');
          }
        }).complete(function() {
          img.parent().removeClass('disabled');
          setTimeout(function() {
            updateIcon('update.png');
          }, 5000);
        });
      });

      // Delete subpage
      $('.delete-subpage').live('click.pontoon', function (e) {
        e.preventDefault();
        $(this).toggleClass('active');
        $(this).next().prop('checked', !$(this).next().prop('checked'));
      });
      $('.subpages [checked]').click().prev().click();

      // Add subpage
      var count = $('.subpages:last').data('count');
      $('.add-subpage').click(function(e) {
        e.preventDefault();
        var form = $('.subpages:last').html().replace(/__prefix__/g, count);
        $('.subpages:last').before('
' + form + '
');
        count++;
        $('#id_subpage_set-TOTAL_FORMS').val(count);
      });

      // Delete project
      $('.delete-project').live('click.pontoon', function (e) {
        e.preventDefault();
        if ($(this).is('.clicked')) {
          window.location = '/admin/delete/' + $('input[name=pk]').val();
        } else {
          $(this).addClass('clicked').html('Are you sure?');
        }
      });
    }
  });

}(this.jQuery));

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function() {
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if (this.console) {
    console.log(Array.prototype.slice.call(arguments));
  }
};

// catch all document.write() calls
(function(doc) {
  var write = doc.write;
  doc.write = function(q) {
    log('document.write(): ', arguments);
    if (/docwriteregexwhitelist/.test(q)) {
      write.apply(doc,arguments);
    }
  };
}(document));
<|endoftext|>


<commit_before>describe("LocalDate", function() {
    it("can calculate days since hypothetical Day 0.", function() {
        expect(new LocalDate(1, 1, 1).sinceDayZero()).toBe(1);
        expect(new LocalDate(1, 1, 2).sinceDayZero()).toBe(2);
        expect(new LocalDate(1, 2, 2).sinceDayZero()).toBe(33);
        expect(new LocalDate(1, 3, 3).sinceDayZero()).toBe(62);
        expect(new LocalDate(4, 3, 3).sinceDayZero()).toBe(1158);
    });
    it("can check if a given year is a leap year.", function() {
        expect(LocalDate.isLeapYear(1)).toBe(false);
        expect(LocalDate.isLeapYear(4)).toBe(true);
        expect(LocalDate.isLeapYear(100)).toBe(false);
        expect(LocalDate.isLeapYear(400)).toBe(true);
        expect(LocalDate.isLeapYear(1900)).toBe(false);
        expect(LocalDate.isLeapYear(2000)).toBe(true);
    });
});

describe("Period", function() {
    it("can calculate the days between the start and the end dates.", function() {
        expect(new Period(new LocalDate(1, 1, 1),
            new LocalDate(1, 1, 2)).getDays()).toBe(1);
        expect(new Period(new LocalDate(1, 1, 1),
            new LocalDate(1, 3, 1)).getDays()).toBe(59);
        expect(new Period(new LocalDate(2000, 1, 1),
            new LocalDate(2001, 1, 1)).getDays()).toBe(366);
    });
})
<commit_msg>Add more unit tests.<commit_after>describe("LocalDate", function() {
    it("can calculate days since hypothetical Day 0.", function() {
        expect(new LocalDate(1, 1, 1).sinceDayZero()).toBe(1);
        expect(new LocalDate(1, 1, 2).sinceDayZero()).toBe(2);
        expect(new LocalDate(1, 2, 2).sinceDayZero()).toBe(33);
        expect(new LocalDate(1, 3, 3).sinceDayZero()).toBe(62);
        expect(new LocalDate(4, 3, 3).sinceDayZero()).toBe(1158);
    });
    it("can check if a given year is a leap year.", function() {
        expect(LocalDate.isLeapYear(1)).toBe(false);
        expect(LocalDate.isLeapYear(4)).toBe(true);
        expect(LocalDate.isLeapYear(100)).toBe(false);
        expect(LocalDate.isLeapYear(400)).toBe(true);
        expect(LocalDate.isLeapYear(1900)).toBe(false);
        expect(LocalDate.isLeapYear(2000)).toBe(true);
    });
    it("can parse a string to get a LocalDate object.", function() {
        expect(LocalDate.parse("2017-01-01") instanceof LocalDate).toBe(true);
        expect(LocalDate.parse("2017/01/01") instanceof LocalDate).toBe(true);
        expect(LocalDate.parse("01/01/2017") instanceof LocalDate).toBe(true);
        expect(LocalDate.parse("Jan 1, 2017") instanceof LocalDate).toBe(true);
    })
});

describe("Period", function() {
    it("can calculate the days between the start and the end dates.",
        function() {
            expect(new Period(new LocalDate(1, 1, 1),
                new LocalDate(1, 1, 2)).getDays()).toBe(1);
            expect(new Period(new LocalDate(1, 1, 1),
                new LocalDate(1, 3, 1)).getDays()).toBe(59);
            expect(new Period(new LocalDate(2000, 1, 1),
                new LocalDate(2001, 1, 1)).getDays()).toBe(366);
        });
    it("can be shown in a string representation.", function() {
        expect(new Period(new LocalDate(1, 1, 1),
            new LocalDate(1, 1, 2)).toString()).toBe("1 day");
        expect(new Period(new LocalDate(1, 1, 1),
            new LocalDate(1, 3, 1)).toString()).toBe("2 months");
        expect(new Period(new LocalDate(2000, 1, 1),
            new LocalDate(2001, 1, 1)).toString()).toBe("1 year");
        expect(new Period(new LocalDate(2000, 1, 1),
            new LocalDate(2001, 1, 2)).toString()).toBe("1 year 1 day");
        expect(new Period(new LocalDate(2000, 1, 1),
            new LocalDate(2001, 2, 2)).toString()).toBe("1 year 1 month 1 day");
        expect(new Period(new LocalDate(2000, 1, 1),
            new LocalDate(2002, 3, 3)).toString()).toBe(
            "2 years 2 months 2 days");
    });
})
<|endoftext|>


<commit_before>module.exports = function(grunt) {

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		jshint: {
			files: ['Gruntfile.js', 'src/*.js', 'spec/*.js', 'spec/helpers/*.js'],
			options: {
				globals: {
					jQuery: true,
					angular: true
				}
			}
		},

		uglify: {
			options: {
				banner: '/*! <%= pkg.name %> <%= pkg.version %> */\n'
			},
			build: {
				src: 'src/<%= pkg.name %>.js',
				dest: 'dist/<%= pkg.name %>.min.js'
			}
		},

		jasmine: {
			src: {
				src: 'src/*.js',
				options: {
					helpers: 'spec/helpers/*.js',
					specs: 'spec/*.js',
					vendor: [
						'node_modules/angular/angular.js',
						'node_modules/angular-mocks/angular-mocks.js',
						'node_modules/angular-filter/dist/angular-filter.js',
						'node_modules/jasmine-jquery/vendor/jquery/jquery.js',
						'node_modules/jasmine-jquery/lib/jasmine-jquery.js'
					]
				}
			}
		},

		watch: {
			files: ['<%= jshint.files %>'],
			tasks: ['clear', 'jshint', 'jasmine'],
			options: {
				debounceDelay: 1000
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-jasmine');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-clear');

	grunt.registerTask('default', ['jshint', 'uglify', 'jasmine']);

};
<commit_msg>Use correct files in Grunt<commit_after>module.exports = function(grunt) {

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		jshint: {
			files: ['Gruntfile.js', 'src/*.js', 'spec/*.js', 'spec/helpers/*.js'],
			options: {
				globals: {
					jQuery: true,
					angular: true
				}
			}
		},

		uglify: {
			options: {
				banner: '/*! <%= pkg.name %> <%= pkg.version %> */\n'
			},
			build: {
				src: 'src/<%= pkg.name %>.js',
				dest: 'dist/<%= pkg.name %>.min.js'
			}
		},

		jasmine: {
			src: {
				src: 'src/*.js',
				options: {
					helpers: 'spec/helpers/*.js',
					specs: 'spec/*.js',
					vendor: [
						'node_modules/jquery/dist/jquery.js',
						'bower_components/jasmine-jquery/lib/jasmine-jquery.js',
						'node_modules/angular/angular.js',
						'node_modules/angular-mocks/angular-mocks.js',
						'node_modules/angular-filter/dist/angular-filter.js'
					]
				}
			}
		},

		watch: {
			files: ['<%= jshint.files %>'],
			tasks: ['clear', 'jshint', 'jasmine'],
			options: {
				debounceDelay: 1000
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-jshint');
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-jasmine');
	grunt.loadNpmTasks('grunt-contrib-watch');
	grunt.loadNpmTasks('grunt-clear');

	grunt.registerTask('default', ['jshint', 'uglify', 'jasmine']);

};
<|endoftext|>


<commit_before>/*
 * Copyright © 2016-2019 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 export default angular.module('thingsboard.locale', [])
                       .factory('tbMissingTranslationHandler', ThingsboardMissingTranslateHandler)
                       .name;

/*@ngInject*/
function ThingsboardMissingTranslateHandler(/*$log, types*/) {

    return function (translationId) {
        /*if (translationId && !translationId.startsWith(types.translate.customTranslationsPrefix)) {
            $log.warn('Translation for ' + translationId + ' doesn\'t exist');
        }*/
    };

}<commit_msg>Update missing translation handler.<commit_after>/*
 * Copyright © 2016-2019 The Thingsboard Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 export default angular.module('thingsboard.locale', [])
                       .factory('tbMissingTranslationHandler', ThingsboardMissingTranslateHandler)
                       .name;

/*@ngInject*/
function ThingsboardMissingTranslateHandler(/*$log, types*/) {

    return function (/*translationId*/) {
        /*if (translationId && !translationId.startsWith(types.translate.customTranslationsPrefix)) {
            $log.warn('Translation for ' + translationId + ' doesn\'t exist');
        }*/
    };

}<|endoftext|>


<commit_before>// based on: http://www.playfuljs.com/realistic-terrain-in-130-lines/

document.body.onload = main;

var rand = require('./random')();

function main() {
  var canvas = document.getElementById('scene');
  var width = canvas.width = window.innerWidth;
  var height = canvas.height = window.innerHeight;
  var ctx = canvas.getContext('2d');
  var map = heightMap(9, 0.7);
  var size = map.size;
  var plot;

  frame();

  function frame() {
    //requestAnimationFrame(frame);
    var t = (+ new Date()) * 0.005;
    t = (1 + Math.sin(t))/2;

    ctx.clearRect(0, 0, width, height);
    plot = ctx.getImageData(0, 0, width, height);
    for (var y = 0; y < size; ++y) {
      for (var x = 0; x < size; ++x) {
        var val = map.get(x, y);
        var val1 = map.get(x + 1, y);
//        val *= t;
//        val1 *= t;
        var c = brightness(x, y, val1 - val);
        var x1 = project(x, y, val);
        var y1 = project(x, y, val, 1);
        pixel(x1, y1, c, c, c);
      }
    }
    ctx.putImageData(plot, 0, 0);
  }

  function brightness(x, y, slope) {
    if (x === size || y === size) return 0;
    return Math.floor(slope * 50) + 128;
  }

  function project(flatX, flatY, flatZ, isY) {
    // use flatX/flatY for demo
    var pointX = isoX(flatX, flatY);
    var pointY = isoY(flatX, flatY);
    var x0 = width * 0.5;
    var y0 = height * 0.2;
    var z = size * 0.5 - flatZ + pointY * 0.75;
    var x = (pointX - size * 0.5) * 6;
    var y = (size - pointY) * 0.005 + 2;

    // explain
    return isY ?
      y0 + z / y :
      x0 + x / y;
  }

  function isoX(x, y) { return 0.5 * (size + x - y); }
  function isoY(x, y) { return 0.5 * (x + y); }

  function pixel(x, y, r, g, b) {
    x = Math.floor(x);
    y = Math.floor(y);
    if (x < 0 || x > width || y < 0 || y > height) return;
    var idx = (x + width * y) * 4;
    plot.data[idx] = r;
    plot.data[idx + 1] = g;
    plot.data[idx + 2] = b;
    plot.data[idx + 3] = 255;
  }
}

function heightMap(detail, roughness) {
  var size = Math.pow(2, detail) + 1,
      max = size - 1,
      map = new Float32Array(size * size);

  set(0, 0, max / 2);
  set(max, 0, max / 2);
  set(max, max, max / 2);
  set(0, max, max / 2);

  divide(max);

  return {
    map: map,
    get: get,
    size: max
  };

  function divide(size) {
    var x, y, half = size / 2;
    var scale = roughness * size;
    if (half < 1) return;

    for (y = half; y < max; y += size) {
      for (x = half; x < max; x += size) {
        square(x, y, half, rand() * scale * 2 - scale);
      }
    }
    for (y = 0; y <= max; y += half) {
      for (x = (y + half) % size; x <= max; x += size) {
        diamond(x, y, half, rand() * scale * 2 - scale);
      }
    }
    divide(size / 2);
  }

  function diamond(x, y, size, offset) {
    var avg = average(
      get(x, y - size),      // top
      get(x + size, y),      // right
      get(x, y + size),      // bottom
      get(x - size, y)       // left
    );

    set(x, y, avg + offset);
  }

  function square(x, y, size, offset) {
    var avg = average(
      get(x - size, y - size),      // left, top
      get(x + size, y - size),      // right, top
      get(x + size, y + size),      // right, bottom
      get(x - size, y + size)       // left, bottom
    );
    set(x, y, avg + offset);
  }

  function average(w, x, y, z) {
    return (w + x + y + z) / 4;
  }

  function get(x, y) {
    if (x < 0 || x > max || y < 0 || y > max) return -1;
    return map[x + size * y];
  }

  function set(x, y, value) { map[x + size * y] = value; }
}
<commit_msg>Use rectangles instead of pixels<commit_after>// based on: http://www.playfuljs.com/realistic-terrain-in-130-lines/

document.body.onload = main;

var rand = require('./random')();

function main() {
  var canvas = document.getElementById('scene');
  var width = canvas.width = window.innerWidth;
  var height = canvas.height = window.innerHeight;
  var ctx = canvas.getContext('2d');
  var map = heightMap(9, 0.7);
  var size = map.size;
  var plot;

  frame();

  function frame() {
    ctx.clearRect(0, 0, width, height);
    for (var y = 0; y < size-1; ++y) {
      for (var x = 0; x < size-1; ++x) {
        var z = map.get(x, y);
        var z1 = map.get(x + 1, y);
        var c = brightness(x, y, z1 - z);

        var left = project(x, y, z);
        var top = project(x, y, z, 1);
        var right = project(x + 1, y, 0);
        var bottom = project(x + 1, y, 0, 1);
        var color = 'rgba(' + c+ ',' +  c+ ',' +  c+ ', 1)';
        rect(left, top, right, bottom, color);
        var waterLeft = project(x, y, size * 0.2);
        var waterTop = project(x, y, size * 0.2, 1);
        rect(waterLeft, waterTop, right, bottom, 'rgba(50, 150,200, 0.15)');
      }
    }
  }

  function rect(left, top, right, bottom, color) {
    if (bottom < top) return;
    ctx.fillStyle = color;
    ctx.fillRect(left, top, right-left, bottom-top);
  }

  function brightness(x, y, slope) {
    if (x === size || y === size) return 0;
    return Math.floor(slope * 50) + 128;
  }

  function project(flatX, flatY, flatZ, isY) {
    var pointX = isoX(flatX, flatY);
    var pointY = isoY(flatX, flatY);
    var x0 = width * 0.5;
    var y0 = height * 0.2;
    var z = size * 0.5 - flatZ + pointY * 0.75;
    var x = (pointX - size * 0.5) * 6;
    var y = (size - pointY) * 0.005 + 1;

    return isY ?
      y0 + z / y :
      x0 + x / y;
  }

  function isoX(x, y) { return 0.5 * (size + x - y); }
  function isoY(x, y) { return 0.5 * (x + y); }

  function pixel(x, y, r, g, b) {
    x = Math.floor(x);
    y = Math.floor(y);
    if (x < 0 || x > width || y < 0 || y > height) return;
    var idx = (x + width * y) * 4;
    plot.data[idx] = r;
    plot.data[idx + 1] = g;
    plot.data[idx + 2] = b;
    plot.data[idx + 3] = 255;
  }
}

function heightMap(detail, roughness) {
  var size = Math.pow(2, detail) + 1,
      max = size - 1,
      map = new Float32Array(size * size);

  set(0, 0, max / 2);
  set(max, 0, max / 2);
  set(max, max, max / 2);
  set(0, max, max / 2);

  divide(max);

  return {
    map: map,
    get: get,
    size: max
  };

  function divide(size) {
    var x, y, half = size / 2;
    var scale = roughness * size;
    if (half < 1) return;

    for (y = half; y < max; y += size) {
      for (x = half; x < max; x += size) {
        square(x, y, half, rand() * scale * 2 - scale);
      }
    }
    for (y = 0; y <= max; y += half) {
      for (x = (y + half) % size; x <= max; x += size) {
        diamond(x, y, half, rand() * scale * 2 - scale);
      }
    }
    divide(size / 2);
  }

  function diamond(x, y, size, offset) {
    var avg = average(
      get(x, y - size),      // top
      get(x + size, y),      // right
      get(x, y + size),      // bottom
      get(x - size, y)       // left
    );

    set(x, y, avg + offset);
  }

  function square(x, y, size, offset) {
    var avg = average(
      get(x - size, y - size),      // left, top
      get(x + size, y - size),      // right, top
      get(x + size, y + size),      // right, bottom
      get(x - size, y + size)       // left, bottom
    );
    set(x, y, avg + offset);
  }

  function average(w, x, y, z) {
    return (w + x + y + z) / 4;
  }

  function get(x, y) {
    if (x < 0 || x > max || y < 0 || y > max) return -1;
    return map[x + size * y];
  }

  function set(x, y, value) { map[x + size * y] = value; }
}
<|endoftext|>


<commit_before>
(function (){
"use strict";
var LexToken = require("./LexToken.js");

var STREX = {
 WS : "[ \\t\\u2000-\\u200d\\u205f\\u1680\\u237d\\u2420\\u2422\\u2423\\u3000]",
 NL : "[\\v\\f\\n]|$|\\r\\n?"
};

var RULES = (function (){
return [
 {
  pattern : "\\\\.",
  name : "ESCAPE"
 },
 {
  pattern : "!!" + STREX.WS,
  name : "TH"
 },
 {
  pattern : "\\|\\|" + STREX.WS,
  name : "TD"
 },
 {
  pattern : "\\|[=]+" + "(?=" + STREX.NL + ")",
  name : "TRSEP"
 },
 {
  pattern : "=+" + "(?=" + STREX.NL + ")",
  name : "ATX_END" //Also used as Setext H1
 },
 {
  pattern : "=+",
  name : "ATX"
 },
 {
  pattern : "---[\\-]+" + "(?=" + STREX.NL + ")",
  name : "HR" //Also used as Setext H2
 },
 {
  pattern : "///[/]+" + "(?=" + STREX.NL + ")",
  name : "COMMENT"
 },
 {
  pattern : "\\.\\." + STREX.WS,
  name : "CLASS"
 },
 {
  pattern : "\\." + STREX.WS,
  name : "ID"
 },
 {
  pattern : ">",
  name : "GT"
 },
 {
  pattern : ":{",
  name : "REF"
 },
 {
  pattern : "}:",
  name : "REF_END"
 },
 {
  pattern : ":" + STREX.WS,
  name : "DD"
 },
 {
  pattern : ";" + STREX.WS,
  name : "DT"
 },
 {
  pattern : "#\\." + STREX.WS + "|" + "[0-9]+\\." + STREX.WS,
  name : "OL"
 },
 {
  pattern : "\\*\\*\\*[*]+" + "(?=" + STREX.NL + ")",
  name : "DIV"
 },
 {
  pattern : "[\\-\\+\\*\\u2022\\u2043]" + STREX.WS,
  name : "UL"
 },
 {
  pattern : "\\\"\\\"[\\\"]+" + "(?=" + STREX.NL + ")",
  name : "PRE"
 },
 {
  pattern : "\\\"\\\"[\\\"]+",
  name : "CODE"
 },
 {
  pattern : "{--",
  name : "DEL"
 },
 {
  pattern : "--}",
  name : "DEL_END"
 },
 {
  pattern : "\\*\\*",
  name : "BOLD"
 },
 {
  pattern : "\\{\\+\\+",
  name : "INS"
 },
 {
  pattern : "\\+\\+\\}",
  name : "INS_END"
 },
 {
  pattern : "\\^\\^",
  name : "SUP"
 },
 {
  pattern : ",,",
  name : "SUB"
 },
 {
  pattern : "__",
  name : "UNDER"
 },
 {
  pattern : "''",
  name : "EM"
 },
 {
  pattern : "\\?<",
  name : "LINK_EXT"
 },
 {
  pattern : "!<",
  name : "LINK_IMG"
 },
 {
  pattern : "#<",
  name : "LINK_WIKI"
 },
 {
  pattern : "#\\[",
  name : "LINK_INT"
 },
 {
  pattern : "\\-\\[",
  name : "LINK_CONT"
 },
 {
  pattern : "\\]",
  name : "BRACKET_R"
 },
 {
  pattern : "[\\v\\f\\n]|\\r\\n?",
  name : "NL"
 },
 {
  pattern : STREX.WS + "+",
  name : "WS"
 }
];
}());

var TYPES = RULES.reduce(function (acc, rule){
 acc[rule.name] = rule.name;
 return acc;
}, {TEXT : "TEXT"});

function makeRegex()
{
 var regexStrList = RULES.map(function (rule){
  return "(" + rule.pattern + ")";
 });

 return new RegExp(regexStrList.join("|"), "g");
}

function Lexer()
{
 this.regex = makeRegex();
}

function create()
{
 return new Lexer();
}

function parse(strInput)
{
 var res = null,
  ruleObj = null,
  regex = this.regex,
  tokens = [],
  lastPos = 0;

 regex.lastIndex = 0;
 while ((res = regex.exec(strInput)) instanceof Array)
 {
  ruleObj = RULES[res.indexOf(res[0], 1) - 1];

  if (lastPos < res.index)
  {
   tokens.push(LexToken.create(
    strInput.slice(lastPos, res.index),
    TYPES.TEXT
   ));
  }

  tokens.push(LexToken.create(
   res[0],
   ruleObj ? ruleObj.name : TYPES.TEXT
  ));

  if (lastPos > regex.lastIndex)
  {
   regex.lastIndex += 1;
  }
  lastPos = regex.lastIndex;
 }

 if (lastPos < strInput.length)
 {
  tokens.push(LexToken.create(
   strInput.slice(lastPos),
   TYPES.TEXT
  ));
 }

 tokens.forEach(updateEscape);
 tokens.forEach(updateLinesCols);

 return tokens;
}

function updateLinesCols(token, index, tokens)
{
 if (index === 0)
 {
  token.line = 0;
  token.col = 0;
  return;
 }
 var prevTok = tokens[index - 1],
  reNL = /[\v\f\n]|\r\n?/,
  nlCount = prevTok.lexeme.split(reNL).length - 1;

 token.line = prevTok.line + nlCount;
 token.col = nlCount > 0 ? 0 : prevTok.col + prevTok.lexeme.length;
}

function updateEscape(token, index)
{
 token.lexeme = token.lexeme.replace(/\\(.)/g, "$1");
}

Lexer.create = create;
Lexer.types = TYPES;
Lexer.prototype.parse = parse;

if (typeof module === "object" && module.exports)
{
 module.exports = Lexer;
}
}());
<commit_msg>Lexer Lookahead Condense<commit_after>
(function (){
"use strict";
var LexToken = require("./LexToken.js");

var STREX = {
 WS : "[ \\t\\u2000-\\u200d\\u205f\\u1680\\u237d\\u2420\\u2422\\u2423\\u3000]",
 EOL : "(?=[\\v\\f\\n]|\\r\\n?|$)"
};

var RULES = (function (){
return [
 {
  pattern : "\\\\.",
  name : "ESCAPE"
 },
 {
  pattern : "!!" + STREX.WS,
  name : "TH"
 },
 {
  pattern : "\\|\\|" + STREX.WS,
  name : "TD"
 },
 {
  pattern : "\\|[=]+" + STREX.EOL,
  name : "TRSEP"
 },
 {
  pattern : "=+" + STREX.EOL,
  name : "ATX_END" //Also used as Setext H1
 },
 {
  pattern : "=+",
  name : "ATX"
 },
 {
  pattern : "---[\\-]+" + STREX.EOL,
  name : "HR" //Also used as Setext H2
 },
 {
  pattern : "///[/]+" + STREX.EOL,
  name : "COMMENT"
 },
 {
  pattern : "\\.\\." + STREX.WS,
  name : "CLASS"
 },
 {
  pattern : "\\." + STREX.WS,
  name : "ID"
 },
 {
  pattern : ">",
  name : "GT"
 },
 {
  pattern : ":{",
  name : "REF"
 },
 {
  pattern : "}:",
  name : "REF_END"
 },
 {
  pattern : ":" + STREX.WS,
  name : "DD"
 },
 {
  pattern : ";" + STREX.WS,
  name : "DT"
 },
 {
  pattern : "#\\." + STREX.WS + "|" + "[0-9]+\\." + STREX.WS,
  name : "OL"
 },
 {
  pattern : "\\*\\*\\*[*]+" + STREX.EOL,
  name : "DIV"
 },
 {
  pattern : "[\\-\\+\\*\\u2022\\u2043]" + STREX.WS,
  name : "UL"
 },
 {
  pattern : "\\\"\\\"[\\\"]+" + STREX.EOL,
  name : "PRE"
 },
 {
  pattern : "\\\"\\\"[\\\"]+",
  name : "CODE"
 },
 {
  pattern : "{--",
  name : "DEL"
 },
 {
  pattern : "--}",
  name : "DEL_END"
 },
 {
  pattern : "\\*\\*",
  name : "BOLD"
 },
 {
  pattern : "\\{\\+\\+",
  name : "INS"
 },
 {
  pattern : "\\+\\+\\}",
  name : "INS_END"
 },
 {
  pattern : "\\^\\^",
  name : "SUP"
 },
 {
  pattern : ",,",
  name : "SUB"
 },
 {
  pattern : "__",
  name : "UNDER"
 },
 {
  pattern : "''",
  name : "EM"
 },
 {
  pattern : "\\?<",
  name : "LINK_EXT"
 },
 {
  pattern : "!<",
  name : "LINK_IMG"
 },
 {
  pattern : "#<",
  name : "LINK_WIKI"
 },
 {
  pattern : "#\\[",
  name : "LINK_INT"
 },
 {
  pattern : "\\-\\[",
  name : "LINK_CONT"
 },
 {
  pattern : "\\]",
  name : "BRACKET_R"
 },
 {
  pattern : "[\\v\\f\\n]|\\r\\n?",
  name : "NL"
 },
 {
  pattern : STREX.WS + "+",
  name : "WS"
 }
];
}());

var TYPES = RULES.reduce(function (acc, rule){
 acc[rule.name] = rule.name;
 return acc;
}, {TEXT : "TEXT"});

function makeRegex()
{
 var regexStrList = RULES.map(function (rule){
  return "(" + rule.pattern + ")";
 });

 return new RegExp(regexStrList.join("|"), "g");
}

function Lexer()
{
 this.regex = makeRegex();
}

function create()
{
 return new Lexer();
}

function parse(strInput)
{
 var res = null,
  ruleObj = null,
  regex = this.regex,
  tokens = [],
  lastPos = 0;

 regex.lastIndex = 0;
 while ((res = regex.exec(strInput)) instanceof Array)
 {
  ruleObj = RULES[res.indexOf(res[0], 1) - 1];

  if (lastPos < res.index)
  {
   tokens.push(LexToken.create(
    strInput.slice(lastPos, res.index),
    TYPES.TEXT
   ));
  }

  tokens.push(LexToken.create(
   res[0],
   ruleObj ? ruleObj.name : TYPES.TEXT
  ));

  if (lastPos > regex.lastIndex)
  {
   regex.lastIndex += 1;
  }
  lastPos = regex.lastIndex;
 }

 if (lastPos < strInput.length)
 {
  tokens.push(LexToken.create(
   strInput.slice(lastPos),
   TYPES.TEXT
  ));
 }

 tokens.forEach(updateEscape);
 tokens.forEach(updateLinesCols);

 return tokens;
}

function updateLinesCols(token, index, tokens)
{
 if (index === 0)
 {
  token.line = 0;
  token.col = 0;
  return;
 }
 var prevTok = tokens[index - 1],
  reNL = /[\v\f\n]|\r\n?/,
  nlCount = prevTok.lexeme.split(reNL).length - 1;

 token.line = prevTok.line + nlCount;
 token.col = nlCount > 0 ? 0 : prevTok.col + prevTok.lexeme.length;
}

function updateEscape(token, index)
{
 token.lexeme = token.lexeme.replace(/\\(.)/g, "$1");
}

Lexer.create = create;
Lexer.types = TYPES;
Lexer.prototype.parse = parse;

if (typeof module === "object" && module.exports)
{
 module.exports = Lexer;
}
}());
<|endoftext|>


<commit_before>function newClickBehavior() {
  $("a").click(function(e) {
    e.preventDefault();
    // More on history object on:
    // https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
    history.pushState({}, "", e.currentTarget.href);
    $("main").load("contents" + e.currentTarget.href, newClickBehavior);
  });
}

$(document).ready(function() {
  var path = window.location.pathname;
  path.replace(/^(website\/)/,"");
  if (path == "") {
      path = "index.html";
  }
  $("nav").load("navbar.html");
  $("footer").load("footer.html");
  $("main").load("contents/" + path, newClickBehavior);
});
<commit_msg>wanna sleep<commit_after>function newClickBehavior() {
  $("a").click(function(e) {
    e.preventDefault();
    // More on history object on:
    // https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
    history.pushState({}, "", e.currentTarget.href);
    $("main").load("contents" + e.currentTarget.href, newClickBehavior);
  });
}

$(document).ready(function() {
  var path = window.location.pathname;
  path.replace(/^(\/website\/)/,"");
  if (path == "") {
      path = "index.html";
  }
  $("nav").load("navbar.html");
  $("footer").load("footer.html");
  $("main").load("contents/" + path, newClickBehavior);
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import withAsyncFetch from '../../hocs/AsyncContainer';
import ActionMenu from '../../ActionMenu';
import { EditButton, ReadItNowButton, DownloadButton } from '../../IconButton';
import { fetchStory } from '../../../../actions/storyActions';
import DataCard from '../../DataCard';
import TagListContainer from './TagListContainer';
import StoryEntitiesContainer from '../../story/StoryEntitiesContainer';
import StoryNytThemesContainer from '../../story/StoryNytThemesContainer';
import messages from '../../../../resources/messages';
import { urlToTools } from '../../../../lib/urlUtil';
import { TAG_SET_NYT_THEMES } from '../../../../lib/tagUtil';
import { trimToMaxLength } from '../../../../lib/stringUtil';
import { storyPubDateToTimestamp } from '../../../../lib/dateUtil';
import Permissioned from '../../Permissioned';
import { PERMISSION_ADMIN } from '../../../../lib/auth';
import StatBar from '../../statbar/StatBar';

const localMessages = {
  title: { id: 'admin.story.title', defaultMessage: 'Story Info: ' },
  close: { id: 'admin.story.inContext.close', defaultMessage: 'Close' },
  readThisStory: { id: 'admin.story.readThisStory', defaultMessage: 'Read This Story' },
  editThisStory: { id: 'admin.story.editThisStory', defaultMessage: 'Edit This Story' },
  fullDescription: { id: 'admin.story.fullDescription', defaultMessage: 'Published in {media} on {publishDate} in {language}' },
  published: { id: 'admin.story.published', defaultMessage: 'Published in {media}' },
  readCachedCopy: { id: 'admin.story.details.readCached', defaultMessage: 'Read Cached Text (admin only)' },
  viewCachedHtml: { id: 'admin.story.details.viewCachedHtml', defaultMessage: 'View Cached HTML (admin only)' },
  downloadAllTagsCsv: { id: 'admin.story.details.downloadTagsCsv', defaultMessage: 'Download all story tags' },
  storyOptions: { id: 'admin.story.details.storyOptions', defaultMessage: 'Story Options' },
};

class SelectedStoryContainer extends React.Component {
  goToUpdateUrl = (storyId) => {
    window.location = `admin/story/${storyId}/update`;
  }

  goToCachedUrl = (storyId) => {
    window.location = `/admin/story/${storyId}/cached`;
  }

  downloadCsv = (storyId) => {
    window.location = `/api/admin/story/${storyId}/storytags.csv`;
  }

  render() {
    const { selectedStory, selectedStoryId, handleStoryEditClick, handleStoryCachedTextClick } = this.props;
    const { formatDate, formatMessage } = this.props.intl;

    let content = null;
    if (selectedStoryId) {
      content = (

          <DataCard className="admin-story-view">
            <Row>
              <Col lg={12}>
                <ActionMenu>
                  <MenuItem onClick={() => window.open(selectedStory.url, '_blank')}>
                    <ListItemText><FormattedMessage {...localMessages.readThisStory} /></ListItemText>
                    <ListItemIcon><ReadItNowButton /></ListItemIcon>
                  </MenuItem>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryCachedTextClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.readCachedCopy} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => window.open(`/api/stories/${selectedStoryId}/raw.html`, '_blank')}>
                      <ListItemText><FormattedMessage {...localMessages.viewCachedHtml} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => handleStoryEditClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.editThisStory} /></ListItemText>
                      <ListItemIcon><EditButton tooltip={formatMessage(localMessages.editThisStory)} /></ListItemIcon>
                    </MenuItem>
                    <MenuItem onClick={() => this.downloadCsv(selectedStoryId)}>
                      <ListItemText>
                        <FormattedMessage {...localMessages.downloadAllTagsCsv} />
                      </ListItemText>
                      <ListItemIcon>
                        <DownloadButton />
                      </ListItemIcon>
                    </MenuItem>
                  </Permissioned>
                </ActionMenu>

                  <FormattedMessage {...localMessages.title} />
                  {trimToMaxLength(selectedStory.title, 80)}

              </Col>
            </Row>
            <Row>
              <Col lg={12}>
                <StatBar
                  columnWidth={2}
                  stats={[
                    { message: messages.sourceName,
                      data: (

                          {selectedStory.media_name || selectedStory.media.name}

                      ),
                    },
                    { message: messages.storyDate,
                      data: formatDate(storyPubDateToTimestamp(selectedStory.publish_date)),
                    },
                    { message: messages.language,
                      data: selectedStory.language ? selectedStory.language : '?',
                    },
                    { message: messages.mediaType,
                      data: selectedStory.media.metadata.media_type ? selectedStory.media.metadata.media_type.label : '?',
                      helpTitleMsg: messages.mediaTypeHelpTitle,
                      helpContentMsg: messages.mediaTypeHelpContent,
                    },
                    { message: messages.pubCountry,
                      data: selectedStory.media.metadata.pub_country ? selectedStory.media.metadata.pub_country.label : '?',
                    },
                    { message: messages.pubState,
                      data: selectedStory.media.metadata.pub_state ? selectedStory.media.metadata.pub_state.label : '?' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <StoryEntitiesContainer storyId={selectedStoryId} />
              </Col>
              <Col lg={3}>
                <StoryNytThemesContainer
                  storyId={selectedStoryId}
                  tags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id === TAG_SET_NYT_THEMES) : []}
                  hideFullListOption
                />
              </Col>
            </Row>
            <Row>
              <Col lg={4}>
                <TagListContainer story={selectedStory} />
              </Col>
            </Row>
          </DataCard>

      );
    }
    return content;
  }
}

SelectedStoryContainer.propTypes = {
  // from parent
  asyncFetch: PropTypes.func.isRequired,
  // from store
  fetchStatus: PropTypes.string.isRequired,
  selectedStory: PropTypes.object.isRequired,
  selectedStoryId: PropTypes.number,
  // from context
  intl: PropTypes.object.isRequired,
  handleStoryCachedTextClick: PropTypes.func.isRequired,
  handleStoryEditClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.story.info.fetchStatus,
  selectedStory: state.story.info,
  selectedStoryId: parseInt(state.story.info.stories_id, 10),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  asyncFetch: () => {
    if (ownProps.params && ownProps.params.id !== undefined) {
      dispatch(fetchStory(parseInt(ownProps.params.id, 10)));
    }
  },
  handleStoryCachedTextClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/cached`));
  },
  handleStoryEditClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/update`));
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    withAsyncFetch(
      SelectedStoryContainer
    )
  )
);
<commit_msg>#1369 extend datacard col<commit_after>import PropTypes from 'prop-types';
import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { Row, Col } from 'react-flexbox-grid/lib';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import withAsyncFetch from '../../hocs/AsyncContainer';
import ActionMenu from '../../ActionMenu';
import { EditButton, ReadItNowButton, DownloadButton } from '../../IconButton';
import { fetchStory } from '../../../../actions/storyActions';
import DataCard from '../../DataCard';
import TagListContainer from './TagListContainer';
import StoryEntitiesContainer from '../../story/StoryEntitiesContainer';
import StoryNytThemesContainer from '../../story/StoryNytThemesContainer';
import messages from '../../../../resources/messages';
import { urlToTools } from '../../../../lib/urlUtil';
import { TAG_SET_NYT_THEMES } from '../../../../lib/tagUtil';
import { trimToMaxLength } from '../../../../lib/stringUtil';
import { storyPubDateToTimestamp } from '../../../../lib/dateUtil';
import Permissioned from '../../Permissioned';
import { PERMISSION_ADMIN } from '../../../../lib/auth';
import StatBar from '../../statbar/StatBar';

const localMessages = {
  title: { id: 'admin.story.title', defaultMessage: 'Story Info: ' },
  close: { id: 'admin.story.inContext.close', defaultMessage: 'Close' },
  readThisStory: { id: 'admin.story.readThisStory', defaultMessage: 'Read This Story' },
  editThisStory: { id: 'admin.story.editThisStory', defaultMessage: 'Edit This Story' },
  fullDescription: { id: 'admin.story.fullDescription', defaultMessage: 'Published in {media} on {publishDate} in {language}' },
  published: { id: 'admin.story.published', defaultMessage: 'Published in {media}' },
  readCachedCopy: { id: 'admin.story.details.readCached', defaultMessage: 'Read Cached Text (admin only)' },
  viewCachedHtml: { id: 'admin.story.details.viewCachedHtml', defaultMessage: 'View Cached HTML (admin only)' },
  downloadAllTagsCsv: { id: 'admin.story.details.downloadTagsCsv', defaultMessage: 'Download all story tags' },
  storyOptions: { id: 'admin.story.details.storyOptions', defaultMessage: 'Story Options' },
};

class SelectedStoryContainer extends React.Component {
  goToUpdateUrl = (storyId) => {
    window.location = `admin/story/${storyId}/update`;
  }

  goToCachedUrl = (storyId) => {
    window.location = `/admin/story/${storyId}/cached`;
  }

  downloadCsv = (storyId) => {
    window.location = `/api/admin/story/${storyId}/storytags.csv`;
  }

  render() {
    const { selectedStory, selectedStoryId, handleStoryEditClick, handleStoryCachedTextClick } = this.props;
    const { formatDate, formatMessage } = this.props.intl;

    let content = null;
    if (selectedStoryId) {
      content = (

          <DataCard className="admin-story-view">
            <Row>
              <Col lg={12}>
                <ActionMenu>
                  <MenuItem onClick={() => window.open(selectedStory.url, '_blank')}>
                    <ListItemText><FormattedMessage {...localMessages.readThisStory} /></ListItemText>
                    <ListItemIcon><ReadItNowButton /></ListItemIcon>
                  </MenuItem>
                  <Permissioned onlyRole={PERMISSION_ADMIN}>
                    <MenuItem onClick={() => handleStoryCachedTextClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.readCachedCopy} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => window.open(`/api/stories/${selectedStoryId}/raw.html`, '_blank')}>
                      <ListItemText><FormattedMessage {...localMessages.viewCachedHtml} /></ListItemText>
                    </MenuItem>
                    <MenuItem onClick={() => handleStoryEditClick(selectedStoryId)}>
                      <ListItemText><FormattedMessage {...localMessages.editThisStory} /></ListItemText>
                      <ListItemIcon><EditButton tooltip={formatMessage(localMessages.editThisStory)} /></ListItemIcon>
                    </MenuItem>
                    <MenuItem onClick={() => this.downloadCsv(selectedStoryId)}>
                      <ListItemText>
                        <FormattedMessage {...localMessages.downloadAllTagsCsv} />
                      </ListItemText>
                      <ListItemIcon>
                        <DownloadButton />
                      </ListItemIcon>
                    </MenuItem>
                  </Permissioned>
                </ActionMenu>

                  <FormattedMessage {...localMessages.title} />
                  {trimToMaxLength(selectedStory.title, 80)}

              </Col>
            </Row>
            <Row>
              <Col lg={12}>
                <StatBar
                  columnWidth={2}
                  stats={[
                    { message: messages.sourceName,
                      data: (

                          {selectedStory.media_name || selectedStory.media.name}

                      ),
                    },
                    { message: messages.storyDate,
                      data: formatDate(storyPubDateToTimestamp(selectedStory.publish_date)),
                    },
                    { message: messages.language,
                      data: selectedStory.language ? selectedStory.language : '?',
                    },
                    { message: messages.mediaType,
                      data: selectedStory.media.metadata.media_type ? selectedStory.media.metadata.media_type.label : '?',
                      helpTitleMsg: messages.mediaTypeHelpTitle,
                      helpContentMsg: messages.mediaTypeHelpContent,
                    },
                    { message: messages.pubCountry,
                      data: selectedStory.media.metadata.pub_country ? selectedStory.media.metadata.pub_country.label : '?',
                    },
                    { message: messages.pubState,
                      data: selectedStory.media.metadata.pub_state ? selectedStory.media.metadata.pub_state.label : '?' },
                  ]}
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <StoryEntitiesContainer storyId={selectedStoryId} />
              </Col>
              <Col lg={3}>
                <StoryNytThemesContainer
                  storyId={selectedStoryId}
                  tags={selectedStory.story_tags ? selectedStory.story_tags.filter(t => t.tag_sets_id === TAG_SET_NYT_THEMES) : []}
                  hideFullListOption
                />
              </Col>
            </Row>
            <Row>
              <Col lg={9}>
                <TagListContainer story={selectedStory} />
              </Col>
            </Row>
          </DataCard>

      );
    }
    return content;
  }
}

SelectedStoryContainer.propTypes = {
  // from parent
  asyncFetch: PropTypes.func.isRequired,
  // from store
  fetchStatus: PropTypes.string.isRequired,
  selectedStory: PropTypes.object.isRequired,
  selectedStoryId: PropTypes.number,
  // from context
  intl: PropTypes.object.isRequired,
  handleStoryCachedTextClick: PropTypes.func.isRequired,
  handleStoryEditClick: PropTypes.func.isRequired,
};

const mapStateToProps = state => ({
  fetchStatus: state.story.info.fetchStatus,
  selectedStory: state.story.info,
  selectedStoryId: parseInt(state.story.info.stories_id, 10),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
  asyncFetch: () => {
    if (ownProps.params && ownProps.params.id !== undefined) {
      dispatch(fetchStory(parseInt(ownProps.params.id, 10)));
    }
  },
  handleStoryCachedTextClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/cached`));
  },
  handleStoryEditClick: (storiesId) => {
    dispatch(push(`admin/story/${storiesId}/update`));
  },
});

export default
injectIntl(
  connect(mapStateToProps, mapDispatchToProps)(
    withAsyncFetch(
      SelectedStoryContainer
    )
  )
);
<|endoftext|>


<commit_before>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    releasePath: 'release/<%= pkg.name %>-<%= pkg.version %>',

    clean: ['<%= releasePath %>', '<%= releasePath %>.zip'],

    auto_install: {
      local: {}
    },

    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      scripts: {
        files: ['dev/*.html', 'src/main/javascript/**/*.js', 'proj4_defs.js'],
        tasks: ['jshint:js'],
        options: {
          spawn: false,
          livereload: true
        }
      }
    },

    jshint: {
      gruntfile: {
        src: 'Gruntfile.js',
        options: {
            node: true,
            es3: true
        }
      },
      js: {
        src: ['src/main/javascript/**/*.js'],
        options: {
            browser: true,
            es3: true,
            '-W069': false, // do not require dot notation
            '-W065': false, // do not require parseInt radix
            '-W030': false, // allow bla && func() expressions
            // TODO: enable these to be even stricter about source code linting
            /*curly: true,
            eqeqeq: true,
            immed: true,
            latedef: true,
            newcap: true,
            noarg: true,
            sub: true,
            undef: true,
            unused: true,
            boss: true,
            eqnull: true,*/
            globals: {
                'Ext': true,
                'OpenLayers': true,
                'GeoExt': true,
                'OpenEMap': true
            }
        }
      }
    },

    sencha: {
      release: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=src/main/javascript,bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace OpenEMap', 'and',
            'concat --closure <%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-min.js']
      },
      debug: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=src/main/javascript,bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace OpenEMap', 'and',
            'concat <%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-debug.js']
      },
      geoext_release: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace GeoExt', 'and',
            'concat --closure bower_components/geoext2/release/geoext-all.js']
      },
      geoext_debug: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace GeoExt', 'and',
            'concat --closure bower_components/geoext2/release/geoext-debug.js']
      }
    },

    copy: {
        dist: {
            files: [
            { expand: true, src: ['index*.html'], dest: '<%= releasePath %>' },
            { expand: true, src: ['proj4_defs.js'], dest: '<%= releasePath %>' },
            { expand: true, src: ['resources/**'], dest: '<%= releasePath %>' },
            { expand: true, src: ['examples/**'], dest: '<%= releasePath %>' },
            { expand: true, cwd: 'bower_components/ext-theme-oep/build/resources/', src: ['**'], dest: '<%= releasePath %>/lib/ext-theme-oep' },
            { expand: false, src: ['bower_components/ext-4.2.1/ext-all.js'], dest: '<%= releasePath %>/lib/ext/ext-all.js' },
            { expand: false, src: ['bower_components/ext-4.2.1/ext-all-debug.js'], dest: '<%= releasePath %>/lib/ext/ext-all-debug.js' },
            { expand: false, src: ['bower_components/ext-4.2.1/ext-theme-neptune.js'], dest: '<%= releasePath %>/lib/ext/ext-theme-neptune.js' },
            { expand: false, src: ['bower_components/ext-4.2.1/locale/ext-lang-sv_SE.js'], dest: '<%= releasePath %>/lib/ext/locale/ext-lang-sv_SE.js' },
            { expand: false, src: ['bower_components/OpenLayers-2.13.1/OpenLayers.js'], dest: '<%= releasePath %>/lib/OpenLayers/OpenLayers.js' },
            { expand: false, src: ['bower_components/OpenLayers-2.13.1/OpenLayers.debug.js'], dest: '<%= releasePath %>/lib/OpenLayers/OpenLayers.debug.js' },
            { expand: true, cwd: 'bower_components/OpenLayers-2.13.1/', src: ['theme/**'], dest: '<%= releasePath %>/lib/OpenLayers/'},
            { expand: false, src: ['bower_components/proj4/dist/proj4-compressed.js'], dest: '<%= releasePath %>/lib/proj4js/proj4-compressed.js' },
            { expand: false, src: ['bower_components/es5-shim/es5-shim.min.js'], dest: '<%= releasePath %>/lib/es5-shim/es5-shim.min.js' },
            { expand: false, src: ['bower_components/es5-shim/es5-shim.map'], dest: '<%= releasePath %>/lib/es5-shim/es5-shim.map' },
            { expand: false, src: ['bower_components/geoext2/release/geoext-all.js'], dest: '<%= releasePath %>/lib/geoext/geoext-all.js'},
            { expand: false, src: ['bower_components/geoext2/release/geoext-debug.js'], dest: '<%= releasePath %>/lib/geoext/geoext-debug.js'},
            { expand: true, flatten: true, src: ['dev/config/**'], dest: '<%= releasePath %>/config' },
            { expand: false, src: ['<%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-min.js'], dest: '<%= releasePath %>/<%= pkg.name %>-min.js' },
            { expand: false, src: ['<%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-debug.js'], dest: '<%= releasePath %>/<%= pkg.name %>-debug.js' },
            { expand: false, src: ['src/main/javascript/OpenEMap.js'], dest: '<%= releasePath %>/OpenEMap.js' }
            ]
        }
    },

    connect: {
        options: {
            base: ['./'],
            middleware: function (connect, options) {
             var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
             return [
                proxy,
                connect['static'](options.base[0]),
                connect.directory(options.base[0])
             ];
          }
        },
        proxies: [{
            context: '/search/lm',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/search/es',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/geoserver/wms',
            host: 'extmaptest.sundsvall.se',
            https: true,
            port: 443
        }, {
            context: '/print',
            host: 'localhost',
            https: false,
            port: 8080
        }, {
            context: '/openemap-permalink',
            host: 'localhost',
            https: false,
            port: 8080
        }, {
            context: '/mapfishprint-2.1.0',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/openemapadmin',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/openemapadmin-1.5.0-rc.2',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/cgi-bin/proxy.py?url=',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }]
    },

    compress: {
      main: {
        options: {
          archive: 'release/<%= pkg.name %>-<%= pkg.version %>.zip'
        },
        files: [
          { expand: true, cwd: '<%= releasePath %>', src: ['**'] }
        ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-auto-install');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-sencha-build');
  grunt.loadNpmTasks('grunt-connect-proxy');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-compress');

  grunt.registerTask('default', ['auto_install', 'jshint']);
  grunt.registerTask('build', ['default', 'sencha:release', 'sencha:debug', 'sencha:geoext_release', 'sencha:geoext_debug'] );
//  grunt.registerTask('dist', ['clean', 'copy', 'compress']);
  grunt.registerTask('dist', ['clean', 'build', 'copy', 'compress']);
  grunt.registerTask('devserver', ['default', 'configureProxies', 'connect', 'watch']);
};
<commit_msg>Copying dist to local Admin repo<commit_after>module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    releasePath: 'release/<%= pkg.name %>-<%= pkg.version %>',

    clean: ['<%= releasePath %>', '<%= releasePath %>.zip'],

    auto_install: {
      local: {}
    },

    watch: {
      gruntfile: {
        files: '<%= jshint.gruntfile.src %>',
        tasks: ['jshint:gruntfile']
      },
      scripts: {
        files: ['dev/*.html', 'src/main/javascript/**/*.js', 'proj4_defs.js'],
        tasks: ['jshint:js'],
        options: {
          spawn: false,
          livereload: true
        }
      }
    },

    jshint: {
      gruntfile: {
        src: 'Gruntfile.js',
        options: {
            node: true,
            es3: true
        }
      },
      js: {
        src: ['src/main/javascript/**/*.js'],
        options: {
            browser: true,
            es3: true,
            '-W069': false, // do not require dot notation
            '-W065': false, // do not require parseInt radix
            '-W030': false, // allow bla && func() expressions
            // TODO: enable these to be even stricter about source code linting
            /*curly: true,
            eqeqeq: true,
            immed: true,
            latedef: true,
            newcap: true,
            noarg: true,
            sub: true,
            undef: true,
            unused: true,
            boss: true,
            eqnull: true,*/
            globals: {
                'Ext': true,
                'OpenLayers': true,
                'GeoExt': true,
                'OpenEMap': true
            }
        }
      }
    },

    sencha: {
      release: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=src/main/javascript,bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace OpenEMap', 'and',
            'concat --closure <%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-min.js']
      },
      debug: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=src/main/javascript,bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace OpenEMap', 'and',
            'concat <%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-debug.js']
      },
      geoext_release: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace GeoExt', 'and',
            'concat --closure bower_components/geoext2/release/geoext-all.js']
      },
      geoext_debug: {
        command: [
            '-sdk bower_components/ext-4.2.1',
            'compile',
            '--classpath=bower_components/geoext2/src',
            'exclude -all', 'and',
            'include -namespace GeoExt', 'and',
            'concat bower_components/geoext2/release/geoext-debug.js']
      }
    },

    copy: {
        dist: {
            files: [
            { expand: true, src: ['index*.html'], dest: '<%= releasePath %>' },
            { expand: true, src: ['proj4_defs.js'], dest: '<%= releasePath %>' },
            { expand: true, src: ['resources/**'], dest: '<%= releasePath %>' },
            { expand: true, src: ['examples/**'], dest: '<%= releasePath %>' },
            { expand: true, cwd: 'bower_components/ext-theme-oep/build/resources/', src: ['**'], dest: '<%= releasePath %>/lib/ext-theme-oep' },
            { expand: false, src: ['bower_components/ext-4.2.1/ext-all.js'], dest: '<%= releasePath %>/lib/ext/ext-all.js' },
            { expand: false, src: ['bower_components/ext-4.2.1/ext-all-debug.js'], dest: '<%= releasePath %>/lib/ext/ext-all-debug.js' },
            { expand: false, src: ['bower_components/ext-4.2.1/ext-theme-neptune.js'], dest: '<%= releasePath %>/lib/ext/ext-theme-neptune.js' },
            { expand: false, src: ['bower_components/ext-4.2.1/locale/ext-lang-sv_SE.js'], dest: '<%= releasePath %>/lib/ext/locale/ext-lang-sv_SE.js' },
            { expand: false, src: ['bower_components/OpenLayers-2.13.1/OpenLayers.js'], dest: '<%= releasePath %>/lib/OpenLayers/OpenLayers.js' },
            { expand: false, src: ['bower_components/OpenLayers-2.13.1/OpenLayers.debug.js'], dest: '<%= releasePath %>/lib/OpenLayers/OpenLayers.debug.js' },
            { expand: true, cwd: 'bower_components/OpenLayers-2.13.1/', src: ['theme/**'], dest: '<%= releasePath %>/lib/OpenLayers/'},
            { expand: false, src: ['bower_components/proj4/dist/proj4-compressed.js'], dest: '<%= releasePath %>/lib/proj4js/proj4-compressed.js' },
            { expand: false, src: ['bower_components/es5-shim/es5-shim.min.js'], dest: '<%= releasePath %>/lib/es5-shim/es5-shim.min.js' },
            { expand: false, src: ['bower_components/es5-shim/es5-shim.map'], dest: '<%= releasePath %>/lib/es5-shim/es5-shim.map' },
            { expand: false, src: ['bower_components/geoext2/release/geoext-all.js'], dest: '<%= releasePath %>/lib/geoext/geoext-all.js'},
            { expand: false, src: ['bower_components/geoext2/release/geoext-debug.js'], dest: '<%= releasePath %>/lib/geoext/geoext-debug.js'},
            { expand: true, flatten: true, src: ['dev/config/**'], dest: '<%= releasePath %>/config' },
            { expand: false, src: ['<%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-min.js'], dest: '<%= releasePath %>/<%= pkg.name %>-min.js' },
            { expand: false, src: ['<%= releasePath %>/<%= pkg.name %>-<%= pkg.version %>-debug.js'], dest: '<%= releasePath %>/<%= pkg.name %>-debug.js' },
            { expand: false, src: ['src/main/javascript/OpenEMap.js'], dest: '<%= releasePath %>/OpenEMap.js' },
            { expand: true, cwd: '<%= releasePath %>/', src: ['**'], dest: '/workspaces/openhierarchy/OpenEMap-Admin-Services/src/org/oemap/services/modules/staticcontent/OpenEMap' }
            ]
        }
    },

    connect: {
        options: {
            base: ['./'],
            middleware: function (connect, options) {
             var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
             return [
                proxy,
                connect['static'](options.base[0]),
                connect.directory(options.base[0])
             ];
          }
        },
        proxies: [{
            context: '/search/lm',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/search/es',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/geoserver/wms',
            host: 'extmaptest.sundsvall.se',
            https: true,
            port: 443
        }, {
            context: '/print',
            host: 'localhost',
            https: false,
            port: 8080
        }, {
            context: '/openemap-permalink',
            host: 'localhost',
            https: false,
            port: 8080
        }, {
            context: '/mapfishprint-2.1.0',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/openemapadmin',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/openemapadmin-1.5.0-rc.2',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }, {
            context: '/cgi-bin/proxy.py?url=',
            host: 'kartatest.e-tjansteportalen.se',
            https: true,
            port: 443
        }]
    },

    compress: {
      main: {
        options: {
          archive: 'release/<%= pkg.name %>-<%= pkg.version %>.zip'
        },
        files: [
          { expand: true, cwd: '<%= releasePath %>', src: ['**'] }
        ]
      }
    }
  });

  grunt.loadNpmTasks('grunt-auto-install');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-sencha-build');
  grunt.loadNpmTasks('grunt-connect-proxy');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-compress');

  grunt.registerTask('default', ['auto_install', 'jshint']);
  grunt.registerTask('build', ['default', 'sencha:release', 'sencha:debug', 'sencha:geoext_release', 'sencha:geoext_debug'] );
  grunt.registerTask('distcopy', ['copy']);
  grunt.registerTask('dist', ['clean', 'build', 'copy', 'compress']);
  grunt.registerTask('devserver', ['default', 'configureProxies', 'connect', 'watch']);
};
<|endoftext|>