<commit_before>//abstract base class
function InboxStateObject(elem) {
    this.baseUrl = $("input[name='baseUrl']").val();
    this.elem = elem;
    this.currentUrl = window.location.pathname;
    this.message = "Feedback is broadcasted and moved to " + "Published Folder";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}

InboxStateObject.prototype.undo = function() {

    var me = this;
    /*
    $(document).bind("a.undo", "click", function(e) {
        var undo_type = $(this).attr('undo-type');
        var undo_mode = $('.inbox-state').val();

        var current_catid = me.elem.attr('catid');
        var state_data = {"mode": undo_mode, "feed_ids": [me.feeds], "cat_id": current_catid, "href": me.href}
        var sec = 350;

        $("#" + me.feeds.feedid).fadeIn(sec);

        //$(this).parents("."+undo_type).fadeOut(sec, function() { $(this).remove(); });
        console.log($(this).attr('feedid'));
        //change_state(state_data);
        e.preventDefault();
    });
    */
    $("a.undo").bind("click", function(e) {
        var undo_type = $(this).attr('undo-type');
        var undo_mode = $('.inbox-state').val();

        var current_catid = me.elem.attr('catid');
        var state_data = {"mode": undo_mode, "feed_ids": [me.feeds], "cat_id": current_catid, "href": me.href}
        var sec = 350;

        $("#" + me.feeds.feedid).fadeIn(sec);

        $(this).parents("."+undo_type).fadeOut(sec, function() { $(this).remove(); });
        console.log(me.feeds.feedid);
        console.log(state_data);
        //change_state(state_data);
        e.preventDefault();
    });
}

InboxStateObject.prototype.process = function() {

    var me = this;
    var is_single = $(me).attr('feedid');
    var mode = (me.state == 1) ? "inbox" : me.mode;
    var state_data = { "mode": mode, "feed_ids": [me.feeds], "cat_id": me.catid, "href": me.href }
    var state_view_data;

    if(is_single) {
        if(me.currentUrl.match(/published|contacts/g)) {

            //HTML view transforms
            if(mode == 'feature') { featured_feed_view_change(me); }
            if(mode == 'publish') { published_feed_view_change(me); }

            //these modes will fadeout feeds in the publish and contact modules
            if(mode == 'inbox' || mode == 'delete') {
                $(me.elem).parents('.feedback').fadeOut(350);
                if(mode == 'inbox') {
                    me.message = "feedback returned to inbox";
                }
                checky_bar_message(me);
            }

            //change_state(state_data);

        } else {
            $(me.elem).parents('.feedback').fadeOut(350);
            checky_bar_message(me);

            //change_state(state_data);

        }
    }

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    });
}

//child implementation classes
function PublishStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been published.";
    this.mode    = "publish";
}
PublishStateObject.prototype = new InboxStateObject();

function FeatureStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been featured.";
    this.mode    = "feature";
}
FeatureStateObject.prototype = new InboxStateObject();

function RemoveStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been " + "deleted";
    this.mode    = "delete";
}
RemoveStateObject.prototype = new InboxStateObject();

function CatPickObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been sent to " + "Filed Feedback";
    this.mode    = "fileas";
    $(elem).parents('div.category-picker-holder').hide();
}

CatPickObject.prototype = new InboxStateObject();
CatPickObject.prototype.process = function() {

    var me = this;
    var is_single = $(me).attr('feedid');
    var mode = me.mode;
    var state_data = { "mode": mode, "feed_ids": [me.feeds], "cat_id": me.catid, "href": me.href }
    //console.log(state_data);
    if(is_single) {
        if(me.currentUrl.match(/filed|modifyfeedback/g)) {
            change_state(state_data);
        } else {
            $(me.elem).parents('.feedback').fadeOut(350);
            checky_bar_message(me);
            change_state(state_data);
        }
    }

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    })
}

//Factory
function InboxStatusChange(opts)  {
    this.inbox_controls = opts;
}

InboxStatusChange.prototype.initialize = function() {
    var me = this;
    $(document).delegate(me.inbox_controls, 'click', function(e) {
        var identifier = $(this).attr('class');
        var us = $(this);

        $.ajax({url: "/feedback/bust_hostfeed_data"});

        if(identifier == 'check') {
            var check = new PublishStateObject(us);
            check.process();
            check.undo();
        }

        if(identifier == 'feature') {
            var feature = new FeatureStateObject(us);
            feature.process();
            feature.undo();
        }

        if(identifier == 'remove' || identifier == 'popup-delete') {
            var remove = new RemoveStateObject(us);
            remove.process();
            remove.undo();
        }
    })
}

function checky_bar_message(opts, undo_msg) {

    var undo_msg = typeof undo_msg !== 'undefined' ? undo_msg : false;

    var check_message = $('.checky-bar');
    var undo = "  Undo";
    var close_checky = "  Close";

    var notify_msg = opts.message + undo + close_checky;

    if(undo_msg) {
        var notify_msg = opts.message;
    }

    var notify  = $('
').addClass(opts.identifier).css({'text-align': 'center'}).html(notify_msg);

    check_message.html(notify).show();
}

function change_view(opts) {
    $(opts.elem).parents('.feedback').css({'background-color': opts.color});
    $(opts.elem).css({'background-position': opts.position});
    $(opts.elem).attr('state', 1);
    $(opts.elem).siblings(opts.sibling).removeAttr('style');
    $(opts.elem).siblings(opts.sibling).attr('state', 0);
}

function featured_feed_view_change(me) {
    state_view_data = {
        'elem': me.elem
      , 'color': '#FFFFE0'
      , 'position': '-60px -34px'
      , 'sibling': '.check'
    };
    checky_bar_message(me, true);
    change_view(state_view_data);
}

function published_feed_view_change(me) {
    state_view_data = {
        'elem': me.elem
      , 'color': '#FFFFFF'
      , 'position': '0px -34px'
      , 'sibling': '.feature'
    };
    checky_bar_message(me, true);
    change_view(state_view_data);
}

//server side processing
function change_state(state_data) {
    $.ajax({
        type: "POST"
      , url: state_data.href
      , data: state_data
      , success: function() {
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        }
    });
}

<commit_msg>Let us eat<commit_after>//abstract base class
function InboxStateObject(elem) {
    this.baseUrl = $("input[name='baseUrl']").val();
    this.elem = elem;
    this.currentUrl = window.location.pathname;
    this.message = "Feedback is broadcasted and moved to " + "Published Folder";
    this.feedid = $(elem).attr('feedid');
    this.href   = $(elem).attr('hrefaction');
    this.catid  = $(elem).attr('catid');
    this.catstate = $(elem).attr('cat-state');
    this.state  = $(elem).attr('state');
    this.feeds = {feedid: this.feedid};
    this.identifier = $(elem).attr('class');
}

InboxStateObject.prototype.undo = function() {

    var me = this;
    $("a.undo").bind("click", function(e) {
        var undo_type = $(this).attr('undo-type');
        var undo_mode = $('.inbox-state').val();

        var current_catid = me.elem.attr('catid');
        var state_data = {"mode": undo_mode, "feed_ids": [me.feeds], "cat_id": current_catid, "href": me.href}
        var sec = 350;

        $("#" + me.feeds.feedid).fadeIn(sec);

        $(this).parents("."+undo_type).fadeOut(sec, function() { $(this).remove(); });
        console.log(me.feeds.feedid);
        console.log(state_data);
        console.log($(this).parents("."+undo_type));
        //change_state(state_data);
        e.preventDefault();
    });
}

InboxStateObject.prototype.process = function() {

    var me = this;
    var is_single = $(me).attr('feedid');
    var mode = (me.state == 1) ? "inbox" : me.mode;
    var state_data = { "mode": mode, "feed_ids": [me.feeds], "cat_id": me.catid, "href": me.href }
    var state_view_data;

    if(is_single) {
        if(me.currentUrl.match(/published|contacts/g)) {

            //HTML view transforms
            if(mode == 'feature') { featured_feed_view_change(me); }
            if(mode == 'publish') { published_feed_view_change(me); }

            //these modes will fadeout feeds in the publish and contact modules
            if(mode == 'inbox' || mode == 'delete') {
                $(me.elem).parents('.feedback').fadeOut(350);
                if(mode == 'inbox') {
                    me.message = "feedback returned to inbox";
                }
                checky_bar_message(me);
            }

            //change_state(state_data);

        } else {
            $(me.elem).parents('.feedback').fadeOut(350);
            checky_bar_message(me);

            //change_state(state_data);

        }
    }

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    });
}

//child implementation classes
function PublishStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been published.";
    this.mode    = "publish";
}
PublishStateObject.prototype = new InboxStateObject();

function FeatureStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been featured.";
    this.mode    = "feature";
}
FeatureStateObject.prototype = new InboxStateObject();

function RemoveStateObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been " + "deleted";
    this.mode    = "delete";
}
RemoveStateObject.prototype = new InboxStateObject();

function CatPickObject(elem) {
    InboxStateObject.apply(this, arguments);
    this.message = "Feedback has been sent to " + "Filed Feedback";
    this.mode    = "fileas";
    $(elem).parents('div.category-picker-holder').hide();
}

CatPickObject.prototype = new InboxStateObject();
CatPickObject.prototype.process = function() {

    var me = this;
    var is_single = $(me).attr('feedid');
    var mode = me.mode;
    var state_data = { "mode": mode, "feed_ids": [me.feeds], "cat_id": me.catid, "href": me.href }
    //console.log(state_data);
    if(is_single) {
        if(me.currentUrl.match(/filed|modifyfeedback/g)) {
            change_state(state_data);
        } else {
            $(me.elem).parents('.feedback').fadeOut(350);
            checky_bar_message(me);
            change_state(state_data);
        }
    }

    $(document).delegate('a.close-checky', 'click', function(e) {
        $(this).parents('.check').remove();
        e.preventDefault();
    })
}

//Factory
function InboxStatusChange(opts)  {
    this.inbox_controls = opts;
}

InboxStatusChange.prototype.initialize = function() {
    var me = this;
    $(document).delegate(me.inbox_controls, 'click', function(e) {
        var identifier = $(this).attr('class');
        var us = $(this);

        $.ajax({url: "/feedback/bust_hostfeed_data"});

        if(identifier == 'check') {
            var check = new PublishStateObject(us);
            check.process();
            check.undo();
        }

        if(identifier == 'feature') {
            var feature = new FeatureStateObject(us);
            feature.process();
            feature.undo();
        }

        if(identifier == 'remove' || identifier == 'popup-delete') {
            var remove = new RemoveStateObject(us);
            remove.process();
            remove.undo();
        }
    })
}

function checky_bar_message(opts, undo_msg) {

    var undo_msg = typeof undo_msg !== 'undefined' ? undo_msg : false;

    var check_message = $('.checky-bar');
    var undo = "  Undo";
    var close_checky = "  Close";

    var notify_msg = opts.message + undo + close_checky;

    if(undo_msg) {
        var notify_msg = opts.message;
    }

    var notify  = $('
').addClass(opts.identifier).css({'text-align': 'center'}).html(notify_msg);

    check_message.html(notify).show();
}

function change_view(opts) {
    $(opts.elem).parents('.feedback').css({'background-color': opts.color});
    $(opts.elem).css({'background-position': opts.position});
    $(opts.elem).attr('state', 1);
    $(opts.elem).siblings(opts.sibling).removeAttr('style');
    $(opts.elem).siblings(opts.sibling).attr('state', 0);
}

function featured_feed_view_change(me) {
    state_view_data = {
        'elem': me.elem
      , 'color': '#FFFFE0'
      , 'position': '-60px -34px'
      , 'sibling': '.check'
    };
    checky_bar_message(me, true);
    change_view(state_view_data);
}

function published_feed_view_change(me) {
    state_view_data = {
        'elem': me.elem
      , 'color': '#FFFFFF'
      , 'position': '0px -34px'
      , 'sibling': '.feature'
    };
    checky_bar_message(me, true);
    change_view(state_view_data);
}

//server side processing
function change_state(state_data) {
    $.ajax({
        type: "POST"
      , url: state_data.href
      , data: state_data
      , success: function() {
            var myStatus = new Status();
            myStatus.notify("Processing...", 1000);
        }
    });
}

<|endoftext|>


<commit_before>$(function() {
  var s = $('#tools');
  var t = $('.redtop .row');
  if (s.length > 0 && t.length > 0) {
    var originalTop = $('.redtop .row').offset().top,
        currentTop = originalTop,
        topSpacing = 10,
        bottomSpacing = 200,
        $window = $(window),
        $document = $(document),
        windowHeight = $window.height();

    function scroller() {
      var scrollTop = $window.scrollTop(),
          documentHeight = $document.height(),
          dwh = documentHeight - windowHeight,
          extra = (scrollTop > dwh) ? dwh - scrollTop : 0;

      var etse = t.offset().top + topSpacing - extra;

      s.parent().css('height', s.height());
      if (s.css('position') !== 'fixed') {
        s.css('top', '');
        s.parent().css('height', 'auto');
      } else if (scrollTop <= etse || windowHeight < s.find('.tool').first().outerHeight()) {
        var newTop = etse - scrollTop;
      } else {
        var newTop = documentHeight - s.outerHeight() - topSpacing - bottomSpacing - scrollTop - extra;
        if (newTop < 0) {
          newTop = newTop + topSpacing;
        } else {
          newTop = topSpacing;
        }
      }
      if (newTop && currentTop != newTop) {
        s.css('top', newTop);
        currentTop = newTop;
      }
    }

    function resizer() {
      windowHeight = $window.height();
    }

    window.scroller = scroller;
    window.resizer = resizer;

    if (window.addEventListener) {
      window.addEventListener('scroll', scroller, false);
      window.addEventListener('resize', resizer, false);
    } else if (window.attachEvent) {
      window.attachEvent('onscroll', scroller);
      window.attachEvent('onresize', resizer);
    }
    scroller();
  }
});

// Bootstrap Affix.js
+function(e){"use strict";function n(n){return this.each(function(){var r=e(this);var i=r.data("bs.affix");var s=typeof n=="object"&&n;if(!i)r.data("bs.affix",i=new t(this,s));if(typeof n=="string")i[n]()})}var t=function(n,r){this.options=e.extend({},t.DEFAULTS,r);this.$target=e(this.options.target).on("scroll.bs.affix.data-api",e.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",e.proxy(this.checkPositionWithEventLoop,this));this.$element=e(n);this.affixed=this.unpin=this.pinnedOffset=null;this.checkPosition()};t.VERSION="3.1.1";t.RESET="affix affix-top affix-bottom";t.DEFAULTS={offset:0,target:window};t.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(t.RESET).addClass("affix");var e=this.$target.scrollTop();var n=this.$element.offset();return this.pinnedOffset=n.top-e};t.prototype.checkPositionWithEventLoop=function(){setTimeout(e.proxy(this.checkPosition,this),1)};t.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var n=e(document).height();var r=this.$target.scrollTop();var i=this.$element.offset();var s=this.options.offset;var o=s.top;var u=s.bottom;if(typeof s!="object")u=o=s;if(typeof o=="function")o=s.top(this.$element);if(typeof u=="function")u=s.bottom(this.$element);var a=this.unpin!=null&&r+this.unpin<=i.top?false:u!=null&&i.top+this.$element.height()>=n-u?"bottom":o!=null&&r<=o?"top":false;if(this.affixed===a)return;if(this.unpin!=null)this.$element.css("top","");var f="affix"+(a?"-"+a:"");var l=e.Event(f+".bs.affix");this.$element.trigger(l);if(l.isDefaultPrevented())return;this.affixed=a;this.unpin=a=="bottom"?this.getPinnedOffset():null;this.$element.removeClass(t.RESET).addClass(f).trigger(e.Event(f.replace("affix","affixed")));if(a=="bottom"){this.$element.offset({top:n-this.$element.height()-u})}};var r=e.fn.affix;e.fn.affix=n;e.fn.affix.Constructor=t;e.fn.affix.noConflict=function(){e.fn.affix=r;return this};e(window).on("load",function(){e('[data-spy="affix"]').each(function(){var t=e(this);var r=t.data();r.offset=r.offset||{};if(r.offsetBottom)r.offset.bottom=r.offsetBottom;if(r.offsetTop)r.offset.top=r.offsetTop;n.call(t,r)})})}(jQuery)
<commit_msg>Use bundled affix.js<commit_after>//= require bootstrap-sass/bootstrap/affix

$(function() {
  var s = $('#tools');
  var t = $('.redtop .row');
  if (s.length > 0 && t.length > 0) {
    var originalTop = $('.redtop .row').offset().top,
        currentTop = originalTop,
        topSpacing = 10,
        bottomSpacing = 200,
        $window = $(window),
        $document = $(document),
        windowHeight = $window.height();

    function scroller() {
      var scrollTop = $window.scrollTop(),
          documentHeight = $document.height(),
          dwh = documentHeight - windowHeight,
          extra = (scrollTop > dwh) ? dwh - scrollTop : 0;

      var etse = t.offset().top + topSpacing - extra;

      s.parent().css('height', s.height());
      if (s.css('position') !== 'fixed') {
        s.css('top', '');
        s.parent().css('height', 'auto');
      } else if (scrollTop <= etse || windowHeight < s.find('.tool').first().outerHeight()) {
        var newTop = etse - scrollTop;
      } else {
        var newTop = documentHeight - s.outerHeight() - topSpacing - bottomSpacing - scrollTop - extra;
        if (newTop < 0) {
          newTop = newTop + topSpacing;
        } else {
          newTop = topSpacing;
        }
      }
      if (newTop && currentTop != newTop) {
        s.css('top', newTop);
        currentTop = newTop;
      }
    }

    function resizer() {
      windowHeight = $window.height();
    }

    window.scroller = scroller;
    window.resizer = resizer;

    if (window.addEventListener) {
      window.addEventListener('scroll', scroller, false);
      window.addEventListener('resize', resizer, false);
    } else if (window.attachEvent) {
      window.attachEvent('onscroll', scroller);
      window.attachEvent('onresize', resizer);
    }
    scroller();
  }
});
<|endoftext|>


<commit_before>// components/Plot.js
var React = require('react');

var Plot = React.createClass({
  componentDidMount: function() {
    Plotly.newPlot('plot', [{
      x: this.props.xData,
      y: this.props.yData,
      type: this.props.type
    }]);
  },
  render: function() {
    return (

    );
  }
});

module.exports = Plot;
<commit_msg>Fix redrawing plot<commit_after>// components/Plot.js
var React = require('react');

var Plot = React.createClass({
  drawPlot: function() {
    Plotly.newPlot('plot', [{
      x: this.props.xData,
      y: this.props.yData,
      type: this.props.type
    }]);
  },
  componentDidMount: function() {
    this.drawPlot();
  },
  componentDidUpdate: function() {
    this.drawPlot();
  },
  render: function() {
    return (

    );
  }
});

module.exports = Plot;
<|endoftext|>


<commit_before>var App_post = {};
var $form = null;
function init_post(obj) {
    $form = $('#form-post');

    if (obj.recover_draft == "true") {
        $form.css('opacity', 0).before('
' + I18n("msg.recover") + '
');
    }

    var _draft_inited = false;
    var class_translate = ".translate-item";

    var post_id = obj.post_id;
    var post_draft_id = obj.post_draft_id;
    var post_status = obj.post_status;
    var _drafts_path = obj._drafts_path;
    var _posts_path = obj._posts_path;
    var _ajax_path = obj._ajax_path;
    var _post_tags_path = obj._post_tags_path;

    App_post.save_draft_ajax = function (callback, called_from_interval) {
        _draft_inited = true;
        var data = $form.serializeObject();
        data._method = post_draft_id ? 'patch' : 'post';
        data.post_id = post_id;
        if ($form.data("hash") != get_hash_form() || !called_from_interval) {
            $.ajax({
                type: 'POST',
                url: _drafts_path,
                data: data,
                success: function (res) {
                    if (res.error) {
                        $.fn.alert({type: 'error', title: res.error.join(", "), icon: "times"})
                    } else {
                        if (res._drafts_path) _drafts_path = res._drafts_path
                        post_draft_id = res.draft.id
                        $("#post_draft_id").val(post_draft_id);
                    }
                    if (callback) callback(res);
                },
                dataType: 'json',
                async: false
            });
        }

    };

    App_post.save_draft = function () {
        App_post.save_draft_ajax(function () {
            $form.data("submitted", 1);
            location.href = _posts_path + '?flash[notice]=' + I18n("msg.draft")
        });

    }
    if(window["post_editor_draft_intrval"]) clearInterval(window["post_editor_draft_intrval"]);
    window["post_editor_draft_intrval"] = setInterval(function () { if($form.length == 0){ clearInterval(window["post_editor_draft_intrval"]); } else{ App_post.save_draft_ajax(null, true); } }, 3 * 60 * 1000);
    window.save_draft = App_post.save_draft_ajax;

    if($form.find(".title-post" + class_translate).size() == 0) class_translate = '';
    $form.find(".title-post" + class_translate).each(function () {
        var $this = $(this);
        if (!$this.hasClass('sluged')) {
            if (class_translate) {
                var lng = $this.attr("data-translation_l");
                var $input_slug = $form.find('.slug-post' + class_translate + '[data-translation_l="' + lng + '"]');
                var post_path = obj._post_urls[lng];
            } else {
                var $input_slug = $form.find('.slug-post');
                var post_path = obj._post_urls[Object.keys(obj._post_urls)[0]];
            }

            var $link = $('
' +
                '' + I18n("msg.permalink") + ':     ' +
                '' + I18n("button.edit") + '    ' +
                '' + I18n("msg.preview") + '    ' +
                '' + I18n("msg.view_page") + '' +
                '
').hide();
            $this.addClass('sluged');
            $this.after($link)

            function set_slug(slug) {
                $link.show().find('.sl-link').html(post_path.replace('__-__', '' + slug + ''))
                $link.find('.btn-preview').attr('href', post_path.replace('__-__', slug) + '?draft_id=' + post_draft_id)
                $input_slug.trigger('change_in');
                set_meta_slug();
            }

            var xhr = null;

            function ajax_set_slug(slug) {
                if (xhr) xhr.abort();
                xhr = $.ajax({
                    type: "POST",
                    url: _ajax_path,
                    data: {method: 'exist_slug', slug: slug, post_id: post_id},
                    success: function (res) {
                        if (res.index > 0) {
                            $input_slug.addClass('slugify-locked').val(res.slug);
                            set_slug(res.slug)
                        }

                    }
                });
            }

            function set_meta_slug() {
                $('#meta_slug').val($form.find('.slug-post' + class_translate).map(function () { return this.value; }).get().join(","));
            }

            var slug_tmp = null;
            $input_slug.slugify($this, {
                    change: function (slug) {
                        slug_tmp = slug;
                        set_slug(slug);
                    }
                }
            );

            $this.change(function () {
                if (slug_tmp) ajax_set_slug(slug_tmp);
            });
            if ($input_slug.val()) {
                set_slug($input_slug.val());
                if (post_status == "published") $link.find('.btn-view').show().attr('href', post_path.replace('__-__', $input_slug.val()))
            }
            $link.find('.btn-preview').click(function () { // preview button
                var link = $(this);
                showLoading();
                App_post.save_draft_ajax(function(){
                    hideLoading();
                    var ar = link.attr("href").split("draft_id=");
                    ar[1] = post_draft_id;
                    var clone = link.clone().hide();
                    clone.insertAfter(link).attr('href', ar.join("draft_id="))[0].click();
                    clone.remove();
                });
                return false;
            });
            $link.find('.btn-edit').click(function () {
                var $btn = $(this);
                var $btn_edit = $('' + I18n("button.accept") + '   ' + I18n("button.cancel") + '');
                var $label = $link.find('.sl-url');
                var $input = $("<input type='text' />");
                $label.hide().after($input);
                $btn.hide().after($btn_edit);
                $input.val($label.text());

                function set_delete() {
                    $label.show();
                    $btn.show();
                    $input.remove();
                    $btn_edit.remove();
                }

                $btn_edit.filter('.btn-cancel').click(function () {
                    set_delete();
                    set_meta_slug()
                    return false;
                });
                $btn_edit.filter('.btn-edit').click(function () {
                    var value_new_slug = slugFunc($input.val());
                    if (value_new_slug) {
                        $input_slug.addClass('slugify-locked').val(value_new_slug);
                        ajax_set_slug(value_new_slug)
                        set_slug(value_new_slug)
                        set_delete();
                    }
                    return false;
                });
                return false;
            });
        }
    });

    try{$(".tinymce_textarea:not(.translated-item)", $form).tinymce().destroy();}catch(e){}
    tinymce.init(cama_get_tinymce_settings({
        selector: '.tinymce_textarea:not(.translated-item)',
        height: '480px',
        onPostRender: onEditorPostRender,
        base_path: obj.base_path
    }));

    $form.validate();
    $("#post_status").change(function () {
        $('#post-actions .btn[data-type]').hide();
        $('#post-actions .btn[data-type="' + $(this).val() + '"]').show();
    });

    // here all later actions
    var form_later_actions = function () {
        /*********** scroller (fix buttons position) ***************/
        var panel_scroll = $("#form-post > #post_right_bar");
        var fixed_position = panel_scroll.children(":first");
        var fixed_offset_top = panel_scroll.offset().top;
        $(window).scroll(function () {
            if ($(window).width() < 1024) {
                fixed_position.css({position: "", width: ""});
                panel_scroll.css("padding-top", "");
                return;
            }
            if ($(window).scrollTop() >= fixed_offset_top + 10) {
                fixed_position.css({position: "fixed", width: "279px", top: 0, "z-index": 4});
                panel_scroll.css("padding-top", fixed_position.height() + 20)
            } else {
                fixed_position.css({position: "", width: "auto"});
                panel_scroll.css("padding-top", "")
            }
        }).resize(function () {
            if ($(window).width() >= 1024) {
                panel_scroll.show();
            }
        }).scroll();
        /*********** end scroller buttons ***************/

        /********** post tagEditor ******************/
        var post_tags = $.ajax({
            type: 'GET',
            url: _post_tags_path,
            dataType: "json",
            async: false
        }).responseText;

        $form.find(".tagsinput").tagEditor({
            autocomplete: {delay: 0, position: {collision: 'flip'}, source: $.parseJSON(post_tags)},
            forceLowercase: false,
            placeholder: I18n("button.add_tag") + '...'
        });
        /********** end post tagEditor **************/
            ////// thumbnail
        $form.on("click", ".gallery-item-remove", function () {
            $('#feature-image').hide();
            $('#feature-image input').val('');
            return false;
        });

        // sidebar toggle
        //$("#admin_content #post_right_bar-toggle").on("click", function () {
        //    $("#post_right_bar").is(":visible") ? $("#post_right_bar").hide() : $("#post_right_bar").show();
        //});

        /*********** control save changes before unload form. ***************/
        $form.submit(function () {
            if ($(this).valid()) $form.data("submitted", 1);
        });
        window.onbeforeunload = function () {
            if ($form.data("submitted"))
                return;
            if ($form.data("hash") != get_hash_form()) {
                return "You sure to leave the page without saving changes?";
            }
            if (!$form.data("submitted"))
                return;
            return "You sure to leave the page without saving changes?";
        };

        /*********** link to create categories *************/
        $form.find("#post_add_new_category").ajax_modal({modal_size: 'modal-lg', mode: 'iframe', callback: function(modal){
            modal.find('iframe').on('load', function(){
                $(this).contents().find("#main-header, #sidebar-menu, #main-footer").hide();
                $(this).contents().find('#admin_content').parent().css("margin-left", 0);
            });
        }, on_close: function(modal){
            var panel_cats = $form.find("#post_right_bar .list-categories");
            $.get($form.find("#post_add_new_category").data('reload-url'), {categories: panel_cats.find("input:checkbox:checked").map(function(i, el){ return $(this).val(); }).get()}, function(res){ panel_cats.html(res); });
        }});
        /*********** end *************/
    }
    setTimeout(form_later_actions, 1000);
    setTimeout(function(){ $form.data("hash", get_hash_form()); }, 4000);

    function get_hash_form() {
        for (editor in tinymce.editors) {
            editor = tinymce.editors[editor];
            var i = $("#" + editor.id).val(tinymce.get(editor.id).getContent()).trigger("change");
        }
        return $form.serialize();
    }

    if (obj.recover_draft == "true") {
        $form.data("validator").cancelSubmit = true;
        $('#post_status').val('published');
        $form.submit();
    }
}

// thumbnail updloader
function upload_feature_image(data) {
    $.fn.upload_filemanager($.extend({
        formats: "image",
        selected: function (image) {
            var image_url = image.url;
            $('#feature-image img').attr('src', image_url);
            $('#feature-image input').val(image_url);
            $('#feature-image .meta strong').html(image.name);
            $('#feature-image').show();
        }
    }, data));
}<commit_msg>modified the time for post editor of changed content verification<commit_after>var App_post = {};
var $form = null;
function init_post(obj) {
    $form = $('#form-post');

    if (obj.recover_draft == "true") {
        $form.css('opacity', 0).before('
' + I18n("msg.recover") + '
');
    }

    var _draft_inited = false;
    var class_translate = ".translate-item";

    var post_id = obj.post_id;
    var post_draft_id = obj.post_draft_id;
    var post_status = obj.post_status;
    var _drafts_path = obj._drafts_path;
    var _posts_path = obj._posts_path;
    var _ajax_path = obj._ajax_path;
    var _post_tags_path = obj._post_tags_path;

    App_post.save_draft_ajax = function (callback, called_from_interval) {
        _draft_inited = true;
        var data = $form.serializeObject();
        data._method = post_draft_id ? 'patch' : 'post';
        data.post_id = post_id;
        if ($form.data("hash") != get_hash_form() || !called_from_interval) {
            $.ajax({
                type: 'POST',
                url: _drafts_path,
                data: data,
                success: function (res) {
                    if (res.error) {
                        $.fn.alert({type: 'error', title: res.error.join(", "), icon: "times"})
                    } else {
                        if (res._drafts_path) _drafts_path = res._drafts_path
                        post_draft_id = res.draft.id
                        $("#post_draft_id").val(post_draft_id);
                    }
                    if (callback) callback(res);
                },
                dataType: 'json',
                async: false
            });
        }

    };

    App_post.save_draft = function () {
        App_post.save_draft_ajax(function () {
            $form.data("submitted", 1);
            location.href = _posts_path + '?flash[notice]=' + I18n("msg.draft")
        });

    }
    if(window["post_editor_draft_intrval"]) clearInterval(window["post_editor_draft_intrval"]);
    window["post_editor_draft_intrval"] = setInterval(function () { if($form.length == 0){ clearInterval(window["post_editor_draft_intrval"]); } else{ App_post.save_draft_ajax(null, true); } }, 3 * 60 * 1000);
    window.save_draft = App_post.save_draft_ajax;

    if($form.find(".title-post" + class_translate).size() == 0) class_translate = '';
    $form.find(".title-post" + class_translate).each(function () {
        var $this = $(this);
        if (!$this.hasClass('sluged')) {
            if (class_translate) {
                var lng = $this.attr("data-translation_l");
                var $input_slug = $form.find('.slug-post' + class_translate + '[data-translation_l="' + lng + '"]');
                var post_path = obj._post_urls[lng];
            } else {
                var $input_slug = $form.find('.slug-post');
                var post_path = obj._post_urls[Object.keys(obj._post_urls)[0]];
            }

            var $link = $('
' +
                '' + I18n("msg.permalink") + ':     ' +
                '' + I18n("button.edit") + '    ' +
                '' + I18n("msg.preview") + '    ' +
                '' + I18n("msg.view_page") + '' +
                '
').hide();
            $this.addClass('sluged');
            $this.after($link)

            function set_slug(slug) {
                $link.show().find('.sl-link').html(post_path.replace('__-__', '' + slug + ''))
                $link.find('.btn-preview').attr('href', post_path.replace('__-__', slug) + '?draft_id=' + post_draft_id)
                $input_slug.trigger('change_in');
                set_meta_slug();
            }

            var xhr = null;

            function ajax_set_slug(slug) {
                if (xhr) xhr.abort();
                xhr = $.ajax({
                    type: "POST",
                    url: _ajax_path,
                    data: {method: 'exist_slug', slug: slug, post_id: post_id},
                    success: function (res) {
                        if (res.index > 0) {
                            $input_slug.addClass('slugify-locked').val(res.slug);
                            set_slug(res.slug)
                        }

                    }
                });
            }

            function set_meta_slug() {
                $('#meta_slug').val($form.find('.slug-post' + class_translate).map(function () { return this.value; }).get().join(","));
            }

            var slug_tmp = null;
            $input_slug.slugify($this, {
                    change: function (slug) {
                        slug_tmp = slug;
                        set_slug(slug);
                    }
                }
            );

            $this.change(function () {
                if (slug_tmp) ajax_set_slug(slug_tmp);
            });
            if ($input_slug.val()) {
                set_slug($input_slug.val());
                if (post_status == "published") $link.find('.btn-view').show().attr('href', post_path.replace('__-__', $input_slug.val()))
            }
            $link.find('.btn-preview').click(function () { // preview button
                var link = $(this);
                showLoading();
                App_post.save_draft_ajax(function(){
                    hideLoading();
                    var ar = link.attr("href").split("draft_id=");
                    ar[1] = post_draft_id;
                    var clone = link.clone().hide();
                    clone.insertAfter(link).attr('href', ar.join("draft_id="))[0].click();
                    clone.remove();
                });
                return false;
            });
            $link.find('.btn-edit').click(function () {
                var $btn = $(this);
                var $btn_edit = $('' + I18n("button.accept") + '   ' + I18n("button.cancel") + '');
                var $label = $link.find('.sl-url');
                var $input = $("<input type='text' />");
                $label.hide().after($input);
                $btn.hide().after($btn_edit);
                $input.val($label.text());

                function set_delete() {
                    $label.show();
                    $btn.show();
                    $input.remove();
                    $btn_edit.remove();
                }

                $btn_edit.filter('.btn-cancel').click(function () {
                    set_delete();
                    set_meta_slug()
                    return false;
                });
                $btn_edit.filter('.btn-edit').click(function () {
                    var value_new_slug = slugFunc($input.val());
                    if (value_new_slug) {
                        $input_slug.addClass('slugify-locked').val(value_new_slug);
                        ajax_set_slug(value_new_slug)
                        set_slug(value_new_slug)
                        set_delete();
                    }
                    return false;
                });
                return false;
            });
        }
    });

    try{$(".tinymce_textarea:not(.translated-item)", $form).tinymce().destroy();}catch(e){}
    tinymce.init(cama_get_tinymce_settings({
        selector: '.tinymce_textarea:not(.translated-item)',
        height: '480px',
        base_path: obj.base_path
    }));

    $form.validate();
    $("#post_status").change(function () {
        $('#post-actions .btn[data-type]').hide();
        $('#post-actions .btn[data-type="' + $(this).val() + '"]').show();
    });

    // here all later actions
    var form_later_actions = function () {
        /*********** scroller (fix buttons position) ***************/
        var panel_scroll = $("#form-post > #post_right_bar");
        var fixed_position = panel_scroll.children(":first");
        var fixed_offset_top = panel_scroll.offset().top;
        $(window).scroll(function () {
            if ($(window).width() < 1024) {
                fixed_position.css({position: "", width: ""});
                panel_scroll.css("padding-top", "");
                return;
            }
            if ($(window).scrollTop() >= fixed_offset_top + 10) {
                fixed_position.css({position: "fixed", width: "279px", top: 0, "z-index": 4});
                panel_scroll.css("padding-top", fixed_position.height() + 20)
            } else {
                fixed_position.css({position: "", width: "auto"});
                panel_scroll.css("padding-top", "")
            }
        }).resize(function () {
            if ($(window).width() >= 1024) {
                panel_scroll.show();
            }
        }).scroll();
        /*********** end scroller buttons ***************/

        /********** post tagEditor ******************/
        var post_tags = $.ajax({
            type: 'GET',
            url: _post_tags_path,
            dataType: "json",
            async: false
        }).responseText;

        $form.find(".tagsinput").tagEditor({
            autocomplete: {delay: 0, position: {collision: 'flip'}, source: $.parseJSON(post_tags)},
            forceLowercase: false,
            placeholder: I18n("button.add_tag") + '...'
        });
        /********** end post tagEditor **************/
            ////// thumbnail
        $form.on("click", ".gallery-item-remove", function () {
            $('#feature-image').hide();
            $('#feature-image input').val('');
            return false;
        });

        // sidebar toggle
        //$("#admin_content #post_right_bar-toggle").on("click", function () {
        //    $("#post_right_bar").is(":visible") ? $("#post_right_bar").hide() : $("#post_right_bar").show();
        //});

        /*********** control save changes before unload form. ***************/
        $form.submit(function () {
            if ($(this).valid()) $form.data("submitted", 1);
        });
        window.onbeforeunload = function () {
            if ($form.data("submitted"))
                return;
            if ($form.data("hash") != get_hash_form()) {
                return "You sure to leave the page without saving changes?";
            }
            if (!$form.data("submitted"))
                return;
            return "You sure to leave the page without saving changes?";
        };

        /*********** link to create categories *************/
        $form.find("#post_add_new_category").ajax_modal({modal_size: 'modal-lg', mode: 'iframe', callback: function(modal){
            modal.find('iframe').on('load', function(){
                $(this).contents().find("#main-header, #sidebar-menu, #main-footer").hide();
                $(this).contents().find('#admin_content').parent().css("margin-left", 0);
            });
        }, on_close: function(modal){
            var panel_cats = $form.find("#post_right_bar .list-categories");
            $.get($form.find("#post_add_new_category").data('reload-url'), {categories: panel_cats.find("input:checkbox:checked").map(function(i, el){ return $(this).val(); }).get()}, function(res){ panel_cats.html(res); });
        }});
        /*********** end *************/
    }
    setTimeout(form_later_actions, 1000);
    setTimeout(function(){ $form.data("hash", get_hash_form()); }, 4000);

    function get_hash_form() {
        for (editor in tinymce.editors) {
            editor = tinymce.editors[editor];
            var i = $("#" + editor.id).val(tinymce.get(editor.id).getContent()).trigger("change");
        }
        return $form.serialize();
    }

    if (obj.recover_draft == "true") {
        $form.data("validator").cancelSubmit = true;
        $('#post_status').val('published');
        $form.submit();
    }
}

// thumbnail updloader
function upload_feature_image(data) {
    $.fn.upload_filemanager($.extend({
        formats: "image",
        selected: function (image) {
            var image_url = image.url;
            $('#feature-image img').attr('src', image_url);
            $('#feature-image input').val(image_url);
            $('#feature-image .meta strong').html(image.name);
            $('#feature-image').show();
        }
    }, data));
}<|endoftext|>


<commit_before><commit_msg>First working version of ADV Io register read by MtxI2cTool<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 1998-2015 Linux.org.ru
 *    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.
 */

$script.ready('jquery', function() {
  $(document).ready(function() {
    var commentForm = $("#commentForm");
    commentForm.append($("
").hide());
    var commentPreview = $('#commentPreview');

    var commentFormContainer = commentForm.parent();

    var csrf = '';

    if (document.cookie.match(/CSRF_TOKEN\=(\w+)\;?/)) {
      csrf = document.cookie.match(/CSRF_TOKEN\=(\w+)\;?/);
      csrf = csrf[1];
    }

    function sh(type, id) {
      if (csrf.length>0) {
        $("input[name='csrf']").attr('value', csrf);
      }

      if (type == 1) {
        var reply_to = $("input[name='replyto']", commentFormContainer);
        if (reply_to.attr('value') != id) {
          commentFormContainer.hide();
        }

        if (commentFormContainer.is(':hidden')) {
          var reply = $('div.reply', $('div.msg_body', $('#comment-' + id)));
          reply.append(commentFormContainer);
          reply_to.attr('value', id);
          commentFormContainer.slideDown('slow', function() { $("#msg").focus(); });
        } else {
          commentFormContainer.slideUp('slow');
        }
      } else if (type == 0) {
        var topic_id = $("input[name='topic']", commentFormContainer).attr('value');

        reply_to = $("input[name='replyto']", commentFormContainer);
        if (reply_to.attr('value') != 0) {
          commentFormContainer.hide();
        }

        if (commentFormContainer.is(':hidden')) {
          var reply = $('div.reply', $('div.msg_body', $('#topic-' + topic_id)));
          reply.append(commentFormContainer);
          reply_to.attr('value', '0');
          commentFormContainer.slideDown('slow', function() { $("#msg").focus(); });
        } else {
          commentFormContainer.slideUp('slow');
        }
      }
    }

    $('div.reply').each(function() {
      $('a[href^="comment-message.jsp"]', this).bind("click", function() {
        sh(0, 0);
        return false;
      });

      var lnk = $('a[href^="add_comment.jsp"]', this);
      if (lnk.length>0) {
        var buff = lnk.attr('href').match(/\d+/g);
        var idr = buff[1];
        lnk.bind("click", function() {
          sh(1, idr);
          return false;
        });
      }
    });

    window.onbeforeunload = function() {
      if ($("#msg").val()!='' && ! $("#commentForm").parent().is(":hidden")) {
        return "Вы что-то напечатали в форме. Все введенные данные будут потеряны при закрытии страницы.";
      }
    };

    commentForm.bind("submit", function() {
      window.onbeforeunload = null;
    });

    commentForm.bind("reset", function() {
      commentFormContainer.slideUp('slow');
      commentPreview.hide();
      commentPreview.html('');
    });

    var previewButton = commentForm.find("button[name=preview]");
    previewButton.attr("type", "button");
    previewButton.click(function() {
      var form = commentForm.serialize();
      form = form+"&preview=preview";
      $.post("/add_comment_ajax", form).done(function(data) {
        var title = "Предпросмотр";

        if (data['preview']['title']) {
          title = data['preview']['title'];
        }

        $("div[error]").remove();

        commentPreview.html("
"+title+"
"+data['preview']['processedMessage']);

        if (data['errors']) {
          var errors = $("
");
          $.each(data['errors'], function(idx, v) {
            errors.append($("").text(v));
            errors.append($("
"));
          });

          commentPreview.prepend(errors);
        }

        commentPreview.show();

        var visible_area_start = $(window).scrollTop();
        var visible_area_end = visible_area_start + window.innerHeight;

        var offset = commentPreview.offset().top;

        if(offset < visible_area_start || offset > visible_area_end) {
          // Not in view so scroll to it
          $('html,body').animate({scrollTop: offset - window.innerHeight/3}, 500);
          return false;
        }
      });
    })
  });
});

<commit_msg>отключаем кнопку на время выполнения запроса<commit_after>/*
 * Copyright 1998-2015 Linux.org.ru
 *    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.
 */

$script.ready('jquery', function() {
  $(document).ready(function() {
    var commentForm = $("#commentForm");
    commentForm.append($("
").hide());
    var commentPreview = $('#commentPreview');

    var commentFormContainer = commentForm.parent();

    var csrf = '';

    if (document.cookie.match(/CSRF_TOKEN\=(\w+)\;?/)) {
      csrf = document.cookie.match(/CSRF_TOKEN\=(\w+)\;?/);
      csrf = csrf[1];
    }

    function sh(type, id) {
      if (csrf.length>0) {
        $("input[name='csrf']").attr('value', csrf);
      }

      if (type == 1) {
        var reply_to = $("input[name='replyto']", commentFormContainer);
        if (reply_to.attr('value') != id) {
          commentFormContainer.hide();
        }

        if (commentFormContainer.is(':hidden')) {
          var reply = $('div.reply', $('div.msg_body', $('#comment-' + id)));
          reply.append(commentFormContainer);
          reply_to.attr('value', id);
          commentFormContainer.slideDown('slow', function() { $("#msg").focus(); });
        } else {
          commentFormContainer.slideUp('slow');
        }
      } else if (type == 0) {
        var topic_id = $("input[name='topic']", commentFormContainer).attr('value');

        reply_to = $("input[name='replyto']", commentFormContainer);
        if (reply_to.attr('value') != 0) {
          commentFormContainer.hide();
        }

        if (commentFormContainer.is(':hidden')) {
          var reply = $('div.reply', $('div.msg_body', $('#topic-' + topic_id)));
          reply.append(commentFormContainer);
          reply_to.attr('value', '0');
          commentFormContainer.slideDown('slow', function() { $("#msg").focus(); });
        } else {
          commentFormContainer.slideUp('slow');
        }
      }
    }

    $('div.reply').each(function() {
      $('a[href^="comment-message.jsp"]', this).bind("click", function() {
        sh(0, 0);
        return false;
      });

      var lnk = $('a[href^="add_comment.jsp"]', this);
      if (lnk.length>0) {
        var buff = lnk.attr('href').match(/\d+/g);
        var idr = buff[1];
        lnk.bind("click", function() {
          sh(1, idr);
          return false;
        });
      }
    });

    window.onbeforeunload = function() {
      if ($("#msg").val()!='' && ! $("#commentForm").parent().is(":hidden")) {
        return "Вы что-то напечатали в форме. Все введенные данные будут потеряны при закрытии страницы.";
      }
    };

    commentForm.bind("submit", function() {
      window.onbeforeunload = null;
    });

    commentForm.bind("reset", function() {
      commentFormContainer.slideUp('slow');
      commentPreview.hide();
      commentPreview.html('');
    });

    var previewButton = commentForm.find("button[name=preview]");
    previewButton.attr("type", "button");
    previewButton.click(function() {
      previewButton.prop("disabled", true);
      var form = commentForm.serialize();
      form = form+"&preview=preview";
      $.post("/add_comment_ajax", form)
              .always(function() {
                previewButton.prop("disabled", false);
              })
              .done(function(data) {
        var title = "Предпросмотр";

        if (data['preview']['title']) {
          title = data['preview']['title'];
        }

        $("div[error]").remove();

        commentPreview.html("
"+title+"
"+data['preview']['processedMessage']);

        if (data['errors']) {
          var errors = $("
");
          $.each(data['errors'], function(idx, v) {
            errors.append($("").text(v));
            errors.append($("
"));
          });

          commentPreview.prepend(errors);
        }

        commentPreview.show();

        var visible_area_start = $(window).scrollTop();
        var visible_area_end = visible_area_start + window.innerHeight;

        var offset = commentPreview.offset().top;

        if(offset < visible_area_start || offset > visible_area_end) {
          // Not in view so scroll to it
          $('html,body').animate({scrollTop: offset - window.innerHeight/3}, 500);
          return false;
        }
      });
    })
  });
});

<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "./TabViewerBase", "dojo/on", "dojo/topic",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"../formatter", "../TabContainer", "../GenomeOverview",
	"dojo/request", "dojo/_base/lang", "../FeatureGridContainer", "../SpecialtyGeneGridContainer",
	"../ActionBar", "../ContainerActionBar", "../PathwaysContainer", "../ProteinFamiliesContainer",
	"../DiseaseContainer", "../PublicationGridContainer", "../CircularViewerContainer",
	"../TranscriptomicsContainer"/*,"JBrowse/Browser"*/, "../InteractionsContainer"
], function(declare, TabViewerBase, on, Topic,
			domClass, ContentPane, domConstruct,
			formatter, TabContainer, GenomeOverview,
			xhr, lang, FeatureGridContainer, SpecialtyGeneGridContainer,
			ActionBar, ContainerActionBar, PathwaysContainer, ProteinFamiliesContainer,
			DiseaseContainer, PublicationGridContainer, CircularViewerContainer,
			TranscriptomicsContainer/*, JBrowser*/, InteractionsContainer){
	return declare([TabViewerBase], {
		"baseClass": "GenomeGroup",
		"disabled": false,
		"query": null,
		containerType: "genome_group",
		genome_id: "",
		apiServiceUrl: window.App.dataAPI,

		_setGenome_idAttr: function(id){
			console.log("_setGenome_IDAttr: ", id, this.genome_id, this.state);
			if(!id){
				return;
			}
			this.state = this.state || {};
			this.genome_id = id;
			this.state.genome_ids = [id];

			xhr.get(this.apiServiceUrl + "/genome/" + id, {
				headers: {
					accept: "application/json",
					'X-Requested-With': null,
					'Authorization': (window.App.authorizationToken || "")
				},
				handleAs: "json"
			}).then(lang.hitch(this, function(genome){
				this.set("genome", genome)
			}));

			var gidQueryState = lang.mixin({},this.state, {search: "eq(genome_id," + id + ")"});
			if (this.features){
				this.features.set("state", gidQueryState);
			}

			if(this.specialtyGenes){
				this.specialtyGenes.set("state", gidQueryState);
			}

			if(this.pathways){
				this.pathways.set("state", this.state);
			}

			if(this.proteinFamilies){
				this.proteinFamilies.set("state", this.state);
			}
		},

		_setGenomeAttr: function(genome){
			// console.log("Set Genome Attr: ", genome)
			var state = this.state || {};

			state.genome = genome;

			this.viewHeader.set("content", genome.taxon_lineage_names.slice(1).join(" » "));
			this.overview.set("state", state);

			this._set("genome", genome);

			this.resize();

		},

		createOverviewPanel: function(){
			return new GenomeOverview({
				title: "Overview",
				style: "overflow:auto;",
				id: this.viewer.id + "_" + "overview",
				state: this.state
			});
		},

		onSetState: function(attr, oldVal, state){

			var parts = this.state.pathname.split("/");
			this.set("genome_id", parts[parts.length - 1]);

			if(!state){
				return;
			}

			if(state.hashParams && state.hashParams.view_tab){
				// console.log("    Look for Tab (this." + state.hashParams.view_tab + "): ", state.hashParams.view_tab);

				if(this[state.hashParams.view_tab]){

					var vt = this[state.hashParams.view_tab];
					// console.log("     View Tab: ", vt);
					vt.set("visible", true);
					this.viewer.selectChild(vt);
				}else{
					// console.log("No view-tab supplied in State Object");
				}
			}
			// console.log("viewer/Genome onSetState() after set genome_id")
		},

		postCreate: function(){
			if(!this.state){
				this.state = {};
			}

			this.inherited(arguments);

			this.overview = this.createOverviewPanel();
			this.phylogeny = new ContentPane({
				content: "Phylogeny",
				title: "Phylogeny",
				id: this.viewer.id + "_" + "phylogeny"
			});
			this.features = new FeatureGridContainer({
				title: "Features",
				id: this.viewer.id + "_" + "features",
				state: lang.mixin({}, this.state, {search: "?eq(genome_id," + this.genome_id + ")"})
			});
			this.specialtyGenes = new SpecialtyGeneGridContainer({
				title: "Specialty Genes",
				id: this.viewer.id + "_" + "specialtyGenes",
				state: this.state
			});
			this.pathways = new PathwaysContainer({
				apiServer: this.apiServiceUrl,
				title: "Pathways",
				id: this.viewer.id + "_" + "pathways",
				state: this.state
			});
			this.proteinFamilies = new ProteinFamiliesContainer({
				title: "Protein Families",
				id: this.viewer.id + "_" + "proteinFamilies",
				state: this.state
			});
			this.transcriptomics = new TranscriptomicsContainer({
				title: "Transcriptomics",
				id: this.viewer.id + "_" + "transcriptomics",
				state: this.state
			});
			this.viewer.addChild(this.overview);
			this.viewer.addChild(this.phylogeny);
			this.viewer.addChild(this.features);
			this.viewer.addChild(this.specialtyGenes);
			this.viewer.addChild(this.pathways);
			this.viewer.addChild(this.proteinFamilies);
			this.viewer.addChild(this.transcriptomics);
		}
	});
});
<commit_msg>only pass the state down to the active tab to avoid unecessary loading and rendering<commit_after>define([
	"dojo/_base/declare", "./TabViewerBase", "dojo/on", "dojo/topic",
	"dojo/dom-class", "dijit/layout/ContentPane", "dojo/dom-construct",
	"../formatter", "../TabContainer", "../GenomeOverview",
	"dojo/request", "dojo/_base/lang", "../FeatureGridContainer", "../SpecialtyGeneGridContainer",
	"../ActionBar", "../ContainerActionBar", "../PathwaysContainer", "../ProteinFamiliesContainer",
	"../DiseaseContainer", "../PublicationGridContainer", "../CircularViewerContainer",
	"../TranscriptomicsContainer"/*,"JBrowse/Browser"*/, "../InteractionsContainer"
], function(declare, TabViewerBase, on, Topic,
			domClass, ContentPane, domConstruct,
			formatter, TabContainer, GenomeOverview,
			xhr, lang, FeatureGridContainer, SpecialtyGeneGridContainer,
			ActionBar, ContainerActionBar, PathwaysContainer, ProteinFamiliesContainer,
			DiseaseContainer, PublicationGridContainer, CircularViewerContainer,
			TranscriptomicsContainer/*, JBrowser*/, InteractionsContainer){
	return declare([TabViewerBase], {
		"baseClass": "GenomeGroup",
		"disabled": false,
		"query": null,
		containerType: "genome_group",
		genome_id: "",
		apiServiceUrl: window.App.dataAPI,

		_setGenome_idAttr: function(id){
			console.log("_setGenome_IDAttr: ", id, this.genome_id, this.state);
			if(!id){
				return;
			}
			var state = this.state = this.state || {};
			this.genome_id = id;
			this.state.genome_ids = [id];

			xhr.get(this.apiServiceUrl + "/genome/" + id, {
				headers: {
					accept: "application/json",
					'X-Requested-With': null,
					'Authorization': (window.App.authorizationToken || "")
				},
				handleAs: "json"
			}).then(lang.hitch(this, function(genome){
				this.set("genome", genome)
			}));
			var activeQueryState = lang.mixin({},this.state, {search: "eq(genome_id," + id + ")"});
			var active = (state && state.hashParams && state.hashParams.view_tab)?state.hashParams.view_tab:"overview";
			var activeTab = this[active];

			switch(active){
				case "pathways":
					break;
				default:
					activeTab.set("state",activeQueryState)
			}

			// var gidQueryState = lang.mixin({},this.state, {search: "eq(genome_id," + id + ")"});
			// if (this.features){
			// 	this.features.set("state", gidQueryState);
			// }

			// if(this.specialtyGenes){
			// 	this.specialtyGenes.set("state", gidQueryState);
			// }

			// if(this.pathways){
			// 	this.pathways.set("state", this.state);
			// }

			// if(this.proteinFamilies){
			// 	this.proteinFamilies.set("state", this.state);
			// }
		},

		_setGenomeAttr: function(genome){
			// console.log("Set Genome Attr: ", genome)
			var state = this.state || {};

			state.genome = genome;

			this.viewHeader.set("content", genome.taxon_lineage_names.slice(1).join(" » "));
			this.overview.set("state", state);

			this._set("genome", genome);

			this.resize();

		},

		createOverviewPanel: function(){
			return new GenomeOverview({
				title: "Overview",
				style: "overflow:auto;",
				id: this.viewer.id + "_" + "overview",
				state: this.state
			});
		},

		onSetState: function(attr, oldVal, state){

			var parts = this.state.pathname.split("/");
			this.set("genome_id", parts[parts.length - 1]);

			if(!state){
				return;
			}

			if(state.hashParams && state.hashParams.view_tab){
				// console.log("    Look for Tab (this." + state.hashParams.view_tab + "): ", state.hashParams.view_tab);

				if(this[state.hashParams.view_tab]){

					var vt = this[state.hashParams.view_tab];
					// console.log("     View Tab: ", vt);
					vt.set("visible", true);
					this.viewer.selectChild(vt);
				}else{
					// console.log("No view-tab supplied in State Object");
				}
			}
			// console.log("viewer/Genome onSetState() after set genome_id")
		},

		postCreate: function(){
			if(!this.state){
				this.state = {};
			}

			this.inherited(arguments);

			this.overview = this.createOverviewPanel();
			this.phylogeny = new ContentPane({
				content: "Phylogeny",
				title: "Phylogeny",
				id: this.viewer.id + "_" + "phylogeny"
			});
			this.features = new FeatureGridContainer({
				title: "Features",
				id: this.viewer.id + "_" + "features",
				state: lang.mixin({}, this.state, {search: "?eq(genome_id," + this.genome_id + ")"})
			});
			this.specialtyGenes = new SpecialtyGeneGridContainer({
				title: "Specialty Genes",
				id: this.viewer.id + "_" + "specialtyGenes",
				state: this.state
			});
			this.pathways = new PathwaysContainer({
				apiServer: this.apiServiceUrl,
				title: "Pathways",
				id: this.viewer.id + "_" + "pathways",
				state: this.state
			});
			this.proteinFamilies = new ProteinFamiliesContainer({
				title: "Protein Families",
				id: this.viewer.id + "_" + "proteinFamilies",
				state: this.state
			});
			this.transcriptomics = new TranscriptomicsContainer({
				title: "Transcriptomics",
				id: this.viewer.id + "_" + "transcriptomics",
				state: this.state
			});
			this.viewer.addChild(this.overview);
			this.viewer.addChild(this.phylogeny);
			this.viewer.addChild(this.features);
			this.viewer.addChild(this.specialtyGenes);
			this.viewer.addChild(this.pathways);
			this.viewer.addChild(this.proteinFamilies);
			this.viewer.addChild(this.transcriptomics);
		}
	});
});
<|endoftext|>


<commit_before>// --------------------------------------------------
// Crop - Adds jcrop where appropriate
// --------------------------------------------------
define(function (require) {

	// Dependencies
	var $ = require('jquery'),
		_ = require('underscore'),
		Backbone = require('backbone');
	require('decoy/plugins/jquery.Jcrop');
	require('decoy/plugins/jquery.imagesloaded');

	// Define a backbone view for each image
	var Crop = Backbone.View.extend({

		// Instance vars
		jcrop: null, // A jcrop API instance
		width: null,
		height: null,
		style: null, // The style of the crop
		ratio: undefined,
		initted: false,
		$input: null, // The hidden field that stores the output

		// Constructor
		initialize: function() {
			_.bindAll(this);

			// Cache selectors
			this.$input = this.$el.closest('.image-upload').find(':hidden[name*="_crops"]');

			// Remove clicking on the parent a tag
			this.$el.parent('a').click(function(e) { e.preventDefault(); });

			// Cache configruation variables
			this.style = this.$el.data('style');
			var ratio = this.$el.data('ratio');
			if (ratio) {
				ratio = ratio.split(':');
				this.ratio = ratio[0]/ratio[1];
			}

			// Listen for window resizing as a way to check whether the img has been resized
			// since it resizes responsively.  We listen on the leading edge for the start
			// and the tailing edge for the end
			var $window = $(window), delay = 400;
			$window.resize(_.debounce(this.destroy, delay, true));
			$window.resize(_.debounce(this.init, delay, false));

			// Listen for fullscreen events
			var $fullscreen = this.$el.closest('[data-js-view="image-fullscreen"]');
			$fullscreen.on('expand contract', _.debounce(this.destroy, delay, true));
			$fullscreen.on('expand contract', _.debounce(this.init, delay, true));

			// Start jcrop up once the images loaded
			this.$el.imagesLoaded(this.init);

		},

		// Events
		events: {
			'active': 'activate' // This image has now been activated
		},

		// Activated, meaning a tab has been clicked to reveal it.  Note: the first
		// image is assumed to be activated on load.
		activate: function() {
			if (!this.initted) this.init();
		},

		// Add jcrop to the element
		init: function() {

			// Only init once and only add jcrop if the image is visible.  Otherwise, it will
			// wait until it is first activated by the style tabs.  It needs to be visible
			// so the size can be measured correctly
			if (this.initted || !this.visible()) return;
			this.initted = true;

			// Cache the visible dimensions of the image
			this.width = this.$el.width();
			this.height = this.$el.height();

			// Check if there is any selection defined
			var val = this.input_to_json();
			var selection = val[this.style] ? this.convert_from_perc(val[this.style]) : undefined;

			// Init jcrop
			var self = this;
			this.$el.Jcrop({
				onSelect: this.select,
				onRelease: this.select,
				aspectRatio: this.ratio,
				setSelect: selection

			// Store a reference to jcrop and call the ready function
			}, function() {
				self.jcrop = this;

				// Put all of the jcrop instances in a parent to give them the polariod effect
				self.$el.siblings('.jcrop-holder').wrap('
');
			});

		},

		// Remove jcrop from the element
		destroy: function() {

			// Only valid if currently initted
			if (!this.jcrop || !this.initted) return;

			// Unset everything
			this.jcrop.destroy();
			this.$el.siblings('.img-polaroid').remove();
			this.jcrop = null;
			this.initted = false;

			// Jcrop will have set width/height on the style
			this.$el.css({width:'', height:''});

		},

		// Perist the user's selection
		select: function(c) {

			// Convert the coordinates from jcrop into percentages.  It may be undefined if the user
			// cleared the crop
			if (c) c = this.convert_to_perc(c);

			// Add the coordinates to the input's value
			var val = this.input_to_json();
			val[this.style] = c;
			this.$input.val(JSON.stringify(val));

		},

		// Check if the this crop is visible
		visible: function() {
			return this.$el.is(":visible");
		},

		// Convert the coordinates from jcrop into percentages.  So an x value of 10
		// in a 100px wide image would become .1.  This is done because Croppa will already
		// be serving an image that is resized from it's source, so a perc offset
		// is the only thing that will be useful.
		convert_to_perc: function(c) {
			return {
				x1 : c.x / this.width,
				x2 : c.x2 / this.width,
				y1 : c.y / this.height,
				y2 : c.y2 / this.height
			};
		},

		// Convert from perc back to pixels of the current image size
		convert_from_perc: function(c) {
			return [
				c.x1 * this.width,
				c.y1 * this.height,
				c.x2 * this.width,
				c.y2 * this.height
			];
		},

		// Get JSON from the $input
		input_to_json: function() {
			var val = this.$input.val();
			if (!val) return {};
			else return JSON.parse(val);
		}

	});

	return Crop;

});<commit_msg>Fixes weird scroll jump issue with second cropper instance<commit_after>// --------------------------------------------------
// Crop - Adds jcrop where appropriate
// --------------------------------------------------
define(function (require) {

	// Dependencies
	var $ = require('jquery'),
		_ = require('underscore'),
		Backbone = require('backbone');
	require('decoy/plugins/jquery.Jcrop');
	require('decoy/plugins/jquery.imagesloaded');

	// Define a backbone view for each image
	var Crop = Backbone.View.extend({

		// Instance vars
		jcrop: null, // A jcrop API instance
		width: null,
		height: null,
		style: null, // The style of the crop
		ratio: undefined,
		initted: false,
		$input: null, // The hidden field that stores the output

		// Constructor
		initialize: function() {
			_.bindAll(this);

			// Cache selectors
			this.$input = this.$el.closest('.image-upload').find(':hidden[name*="_crops"]');

			// Remove clicking on the parent a tag
			this.$el.parent('a').click(function(e) { e.preventDefault(); });

			// Cache configruation variables
			this.style = this.$el.data('style');
			var ratio = this.$el.data('ratio');
			if (ratio) {
				ratio = ratio.split(':');
				this.ratio = ratio[0]/ratio[1];
			}

			// Listen for window resizing as a way to check whether the img has been resized
			// since it resizes responsively.  We listen on the leading edge for the start
			// and the tailing edge for the end
			var $window = $(window), delay = 400;
			$window.resize(_.debounce(this.destroy, delay, true));
			$window.resize(_.debounce(this.init, delay, false));

			// Listen for fullscreen events
			var $fullscreen = this.$el.closest('[data-js-view="image-fullscreen"]');
			$fullscreen.on('expand contract', _.debounce(this.destroy, delay, true));
			$fullscreen.on('expand contract', _.debounce(this.init, delay, true));

			// Start jcrop up once the images loaded
			this.$el.imagesLoaded(this.init);

		},

		// Events
		events: {
			'active': 'activate' // This image has now been activated
		},

		// Activated, meaning a tab has been clicked to reveal it.  Note: the first
		// image is assumed to be activated on load.
		activate: function() {
			if (!this.initted) this.init();
		},

		// Add jcrop to the element
		init: function() {

			// Only init once and only add jcrop if the image is visible.  Otherwise, it will
			// wait until it is first activated by the style tabs.  It needs to be visible
			// so the size can be measured correctly
			if (this.initted || !this.visible()) return;
			this.initted = true;

			// Cache the visible dimensions of the image
			this.width = this.$el.width();
			this.height = this.$el.height();

			// Check if there is any selection defined
			var val = this.input_to_json();
			var selection = val[this.style] ? this.convert_from_perc(val[this.style]) : undefined;

			// Init jcrop
			var self = this;
			this.$el.Jcrop({
				onSelect: this.select,
				onRelease: this.select,
				aspectRatio: this.ratio,
				setSelect: selection,
				keySupport: false // Stop the page scroll from jumping: http://cl.ly/0e1e1615262h

			// Store a reference to jcrop and call the ready function
			}, function() {
				self.jcrop = this;

				// Put all of the jcrop instances in a parent to give them the polariod effect
				self.$el.siblings('.jcrop-holder').wrap('
');
			});

		},

		// Remove jcrop from the element
		destroy: function() {

			// Only valid if currently initted
			if (!this.jcrop || !this.initted) return;

			// Unset everything
			this.jcrop.destroy();
			this.$el.siblings('.img-polaroid').remove();
			this.jcrop = null;
			this.initted = false;

			// Jcrop will have set width/height on the style
			this.$el.css({width:'', height:''});

		},

		// Perist the user's selection
		select: function(c) {

			// Convert the coordinates from jcrop into percentages.  It may be undefined if the user
			// cleared the crop
			if (c) c = this.convert_to_perc(c);

			// Add the coordinates to the input's value
			var val = this.input_to_json();
			val[this.style] = c;
			this.$input.val(JSON.stringify(val));

		},

		// Check if the this crop is visible
		visible: function() {
			return this.$el.is(":visible");
		},

		// Convert the coordinates from jcrop into percentages.  So an x value of 10
		// in a 100px wide image would become .1.  This is done because Croppa will already
		// be serving an image that is resized from it's source, so a perc offset
		// is the only thing that will be useful.
		convert_to_perc: function(c) {
			return {
				x1 : c.x / this.width,
				x2 : c.x2 / this.width,
				y1 : c.y / this.height,
				y2 : c.y2 / this.height
			};
		},

		// Convert from perc back to pixels of the current image size
		convert_from_perc: function(c) {
			return [
				c.x1 * this.width,
				c.y1 * this.height,
				c.x2 * this.width,
				c.y2 * this.height
			];
		},

		// Get JSON from the $input
		input_to_json: function() {
			var val = this.$input.val();
			if (!val) return {};
			else return JSON.parse(val);
		}

	});

	return Crop;

});<|endoftext|>


<commit_before>const KEYWORDS_TEMPLATE_URL = '/templates/keywords.html';

const KEYWORDS_OBJ_URL = '/json/keywords.json';

const CIVIC_OBJ_URL = '/actions/civic'

const NEWS_OBJ_URL =  '/json/news.json';
const PROJECTS_OBJ_URL = '/actions/projects';
const OBJECTS_URLS = [NEWS_OBJ_URL, PROJECTS_OBJ_URL];

const KEYWORDS_PROMISE = loadKeywords(KEYWORDS_OBJ_URL);

const HTML_SECTIONS_PROMISE = loadHtmlSections(KEYWORDS_TEMPLATE_URL, OBJECTS_URLS, KEYWORDS_PROMISE);

/**
 * Loads the keywords array from a servlet or from cookies.
 * Returns a promise of the keywords array.
 */
async function loadKeywords(keywordsUrl) {
  const key = $("body").attr("data-key");
  let keywords;
  const keywordsCookie = getCookie(key);
  if (keywordsCookie === "") {
    keywords = await loadObject(`${keywordsUrl}?k=${key}`);
    const keywordsJson = JSON.stringify(keywords);
    setCookie(key, keywordsJson, 1);
  } else {
    keywords = JSON.parse(keywordsCookie);
  }
  return keywords;
}

/**
 * Loads an array of html templates, an array of json objects, and renders them using mustache.
 * Returns a promise.all of all the render html sections.
 */
async function loadHtmlSections(templateUrl, objsUrls, keywordsPromise) {
  const htmlTemplatePromise = loadTemplate(templateUrl);
  const keywords = await keywordsPromise;
  const queryString = `?key=${keywords.join('&key=')}`;
  objsUrls = objsUrls.map(url => `${url}${queryString}`);
  const objsPromises = loadUrls(objsUrls, loadObject);
  const values =  await Promise.all([htmlTemplatePromise, objsPromises]);
  const template = values[0];
  const objs = values[1];
  return await renderTemplateObj(template, objs, keywords);
}

async function renderTemplateObj(template, objs, keywords) {
  let result = new Object();
  result.keywords = new Array(keywords.length);
  for (let i = 0; i < keywords.length; i++) {
    let term = keywords[i];
    let keywordObj = new Object();
    keywordObj.term = term;
    keywordObj.news = objs[0].articles[term];
    keywordObj.projects = objs[1].results[term];
    result.keywords[i] = keywordObj;
  }

  // TODO: Change true to if the user gave their location, and get real coordinates.
  if (true) {
    let lat = 33.969058;
    let lng = -118.422146;
    let civicObj = await loadObject(`${CIVIC_OBJ_URL}?lat=${lat}&lng=${lng}`);
    let locationObj = new Object();
    locationObj.address = civicObj.normalizedInput;
    locationObj.officials = extractOfficials(civicObj);
    result.location = locationObj;
  }
  let htmlSections = Mustache.render(template, result);
  return htmlSections;
}

/**
 * Extract the government officials from the civic API response.
 */
function extractOfficials(civicObj) {
  let officials = new Object();
  let levels = ["administrativeArea1", "administrativeArea2", "country", "international", "locality", "regional", "special", "subLocality1", "subLocality2"];
  levels.forEach((level) => {
    officials[level] = new Array();
  });
  civicObj.offices.forEach((officeObj) => {
    let level = officeObj.levels[0];
    officeObj.officialIndices.forEach((officialIndex) => {
      let official = civicObj.officials[officialIndex];
      official.title = officeObj.name;
      officials[level].push(official);
    });
  });
  return officials;
}

/**
 * Activates the section that triggered the event.
 */
function activateSection(event) {
  const selectedOption = event.currentTarget.value;
  loadSection(selectedOption);
  return;
}

/**
 * Loads the content section.
 */
async function loadContentSection() {
  const htmlSection = await HTML_SECTIONS_PROMISE;
  $("#content").html(htmlSection);
  return;
}
<commit_msg>Update data pipeline to fetch appropiate data to the template<commit_after>const KEYWORDS_TEMPLATE_URL = '/templates/keywords.html';

const KEYWORDS_OBJ_URL = '/json/keywords.json';

const CIVIC_OBJ_URL = '/actions/civic'

const NEWS_OBJ_URL =  '/json/news.json';
const PROJECTS_OBJ_URL = '/actions/projects';
const OBJECTS_URLS = [NEWS_OBJ_URL, PROJECTS_OBJ_URL];

const KEYWORDS_PROMISE = loadKeywords(KEYWORDS_OBJ_URL);

const HTML_SECTIONS_PROMISE = loadHtmlSections(KEYWORDS_TEMPLATE_URL, OBJECTS_URLS, KEYWORDS_PROMISE);

/**
 * Loads the keywords array from a servlet or from cookies.
 * Returns a promise of the keywords array.
 */
async function loadKeywords(keywordsUrl) {
  const key = $("body").attr("data-key");
  let keywords;
  const keywordsCookie = getCookie(key);
  if (keywordsCookie === "") {
    keywords = await loadObject(`${keywordsUrl}?k=${key}`);
    const keywordsJson = JSON.stringify(keywords);
    setCookie(key, keywordsJson, 1);
  } else {
    keywords = JSON.parse(keywordsCookie);
  }
  return keywords;
}

/**
 * Loads an array of html templates, an array of json objects, and renders them using mustache.
 * Returns a promise.all of all the render html sections.
 */
async function loadHtmlSections(templateUrl, objsUrls, keywordsPromise) {
  const htmlTemplatePromise = loadTemplate(templateUrl);
  const keywords = await keywordsPromise;
  const queryString = `?key=${keywords.join('&key=')}`;
  objsUrls = objsUrls.map(url => `${url}${queryString}`);
  const objsPromises = loadUrls(objsUrls, loadObject);
  const values =  await Promise.all([htmlTemplatePromise, objsPromises]);
  const template = values[0];
  const objs = values[1];
  return await renderTemplateObj(template, objs, keywords);
}

async function renderTemplateObj(template, objs, keywords) {
  let result = new Object();
  result.keywords = new Array(keywords.length);
  for (let i = 0; i < keywords.length; i++) {
    let term = keywords[i];
    let keywordObj = new Object();
    keywordObj.term = term;
    keywordObj.news = objs[0].articles[term];
    keywordObj.projects = objs[1].results[term];
    result.keywords[i] = keywordObj;
  }

  // TODO: Change true to if the user gave their location, and get real coordinates.
  if (true) {
    let lat = 33.969058;
    let lng = -118.422146;
    let civicObj = await loadObject(`${CIVIC_OBJ_URL}?lat=${lat}&lng=${lng}`);
    let locationObj = new Object();
    locationObj.address = civicObj.normalizedInput;
    locationObj.levels = extractOfficials(civicObj);
    result.location = locationObj;
  }
  let htmlSections = Mustache.render(template, result);
  return htmlSections;
}

/**
 * Extract the government officials from the civic API response.
 */
function extractOfficials(civicObj) {
  let levelsArray = new Array();
  const levels = {"international" : "International",
                  "country" : "Country",
                  "regional" : "Regional",
                  "administrativeArea2" : "Administrative Area 2",
                  "administrativeArea1" : "Administrative Area 1",
                  "locality" : "Locality",
                  "subLocality2" : "Sublocality 2",
                  "subLocality1" : "Sublocality 1",
                  "special" : "Special",};
  for (const level in levels) {
    let levelsObj = new Object();
    levelsObj.levelType = level;
    levelsObj.levelName = levels[level]
    levelsObj.officials = new Array();
    levelsArray.push(levelsObj);
  }
  civicObj.offices.forEach((officeObj) => {
    const level = officeObj.levels[0];
    officeObj.officialIndices.forEach((officialIndex) => {
      let official = civicObj.officials[officialIndex];
      official.title = officeObj.name;
      levelsArray.find(obj => obj.levelType === level).officials.push(official);
    });
  });
  return levelsArray.filter(obj => obj.officials.length > 0);
}

/**
 * Activates the section that triggered the event.
 */
function activateSection(event) {
  const selectedOption = event.currentTarget.value;
  loadSection(selectedOption);
  return;
}

/**
 * Loads the content section.
 */
async function loadContentSection() {
  const htmlSection = await HTML_SECTIONS_PROMISE;
  $("#content").html(htmlSection);
  return;
}
<|endoftext|>


<commit_before>/*!
 * Logger tests
 * @author Andrew Teologov <teologov.and@gmail.com>
 * @date 3/12/15
 */
/* global define, describe, beforeEach, afterEach, it, assert, sinon, teoBase  */

var logger = require(teoBase + "/teo.logger");
var util = require("util");

describe("Testing Logger", function() {

    var formatSpy,
        consoleLogStub,
        message = "my message";

    before(function() {

        // special case. Restore logger methods for testing themselves
        logger.info.restore();
        logger.warn.restore();
        logger.error.restore();
        logger.fatal.restore();
        logger.success.restore();
        logger.log.restore();

    });

    beforeEach(function() {

        formatSpy = sinon.spy(util, "format");
        consoleLogStub = sinon.stub(console, "log", function(message) {
            return message;
        });

    });

    afterEach(function() {

        formatSpy.restore();
        consoleLogStub.restore();

    });

    after(function() {

        sinon.stub(logger, "info", function() {});
        sinon.stub(logger, "warn", function() {});
        sinon.stub(logger, "error", function() {});
        sinon.stub(logger, "fatal", function() {});
        sinon.stub(logger, "success", function() {});
        sinon.stub(logger, "log", function() {});

    });

    it("Should log success message", function() {

        logger.success(message);

        assert.deepEqual(formatSpy.args[0], ["Success: %s", message], "Message should be formatted correctly");

    });

    it("Should log info message", function() {

        logger.info(message);

        assert.deepEqual(formatSpy.args[0], ["Info: %s", message], "Message should be formatted correctly");

    });

    it("Should log warn message", function() {

        logger.warn(message);

        assert.deepEqual(formatSpy.args[0], ["Warn: %s", message], "Message should be formatted correctly");

    });

    it("Should log error message", function() {

        logger.error(message);

        assert.deepEqual(formatSpy.args[0], ["Error: %s", message], "Message should be formatted correctly");

    });

    it("Should parse error object and log error stack", function() {

        var error = new Error("My error");

        logger.error(error);

        assert.deepEqual(formatSpy.args[0], ["Error: %s", error.stack], "Error message should be formatted correctly");

    });

    it("Should log fatal error message", function() {

        logger.fatal(message);

        assert.deepEqual(formatSpy.args[0], ["Fatal Error: %s", message], "Message should be formatted correctly");

    });

    it("Should format final message correctly", function() {

        logger.success(message);

        assert.equal(formatSpy.args[1][0], "[%s] %s", "Format of final message should be correct");
        assert.equal(formatSpy.args[1][2], "Success: " + message, "Message should be formatted correctly");

    });

    it("Should log multiple messages in arguments", function() {

        logger.success("One", "two");

        assert.equal(formatSpy.args[1][2], "Success: One|two", "Message should be formatted correctly");

    });

    it("Should just log message", function() {

        logger.log("One", "two");
        assert.equal(formatSpy.args[1][2], "One|two", "Message should be formatted correctly");

    });

});<commit_msg>fixed tests<commit_after>/*!
 * Logger tests
 * @author Andrew Teologov <teologov.and@gmail.com>
 * @date 3/12/15
 */
/* global define, describe, beforeEach, afterEach, it, assert, sinon, teoBase  */

var logger = require(teoBase + "/teo.logger");
var util = require("util");

describe("Testing Logger", function() {

    var formatSpy,
        consoleLogStub,
        message = "my message";

    before(function() {

        // special case. Restore logger methods for testing themselves
        logger.info.restore();
        logger.warn.restore();
        logger.error.restore();
        logger.fatal.restore();
        logger.success.restore();
        logger.log.restore();

    });

    beforeEach(function() {

        formatSpy = sinon.spy(util, "format");
        consoleLogStub = sinon.stub(console, "log", function(message) {
            return message;
        });

    });

    afterEach(function() {

        formatSpy.restore();
        consoleLogStub.restore();

    });

    after(function() {

        sinon.stub(logger, "info", function() {});
        sinon.stub(logger, "warn", function() {});
        sinon.stub(logger, "error", function() {});
        sinon.stub(logger, "fatal", function() {});
        sinon.stub(logger, "success", function() {});
        sinon.stub(logger, "log", function() {});

    });

    it("Should log success message", function() {

        logger.success(message);

        assert.deepEqual(formatSpy.args[0], ["Success: %s", message], "Message should be formatted correctly");

    });

    it("Should log info message", function() {

        logger.info(message);

        assert.deepEqual(formatSpy.args[0], ["Info: %s", message], "Message should be formatted correctly");

    });

    it("Should log warn message", function() {

        logger.warn(message);

        assert.deepEqual(formatSpy.args[0], ["Warn: %s", message], "Message should be formatted correctly");

    });

    it("Should log error message", function() {

        logger.error(message);

        assert.deepEqual(formatSpy.args[0], ["Error: %s", message], "Message should be formatted correctly");

    });

    it("Should parse error object and log error stack", function() {

        var error = new Error("My error");

        logger.error(error);

        assert.deepEqual(formatSpy.args[0], ["Error: %s", error.stack], "Error message should be formatted correctly");

    });

    it("Should log fatal error message", function() {

        logger.fatal(message);

        assert.deepEqual(formatSpy.args[0], ["Fatal Error: %s", message], "Message should be formatted correctly");

    });

    it("Should format final message correctly", function() {

        logger.success(message);

        assert.equal(formatSpy.args[1][0], "[%s] %s", "Format of final message should be correct");
        assert.equal(formatSpy.args[1][2], "\u001b[32mSuccess: " + message +"\u001b[39m", "Message should be formatted correctly");

    });

    it("Should log multiple messages in arguments", function() {

        logger.success("One", "two");

        assert.equal(formatSpy.args[1][2], "\u001b[32mSuccess: One|two\u001b[39m", "Message should be formatted correctly");

    });

    it("Should just log message", function() {

        logger.log("One", "two");
        assert.equal(formatSpy.args[1][2], "One|two", "Message should be formatted correctly");

    });

});<|endoftext|>