<commit_before>;(function() {
    "use strict";
    // <body data-resequence="#ID_OF_SCRIPT_CONTAINING_RESEQUENCE">
    // or
    // <body data-resequence-src="path.to.resequence.file.rseqdef">
    var g = window;
    var findBody, body = (findBody = document.getElementsByTagName('body')).length > 0 ? findBody[0] : null;
    var resequenceEl, resequenceSrc;
    if ((resequenceSrc = body.getAttribute("data-resequence-src")) == null &&
        (resequenceEl = body.getAttribute("data-resequence")) == null) {
        var scriptTags = document.getElementsByTagName("script");
        var seqscript;
        for (var s in scriptTags) {
            var ta = scriptTags[s].getAttribute("type");
            if (!!ta && ta == "text/resequencer") {
                resequenceEl = scriptTags[s];
                break;
            }
        }
        return;
    }
    var _opts = {
        src : resequenceSrc,
        seqdef  : resequenceEl,
        targetEl: body
    }
    var resequence = g.resequenceHTML = function resequence(seqdef, src, targetEl) {
        if (seqdef instanceof Event) {
            seqdef = undefined;
        }
        var opts = _opts;
        if (typeof seqdef == "object" && !(seqdef instanceof jQuery)) {
            for (var p in seqdef) {
                opts[p] = seqdef[p];
            }
            seqdef = null;
        }
        seqdef = seqdef || opts.seqdef;
        src = src || opts.src;
        targetEl = targetEl || opts.targetEl;

        if (src && !seqdef) {
            if (typeof jQuery != 'undefined') {
                jQuery.get(src, function(data, textStatus, jqXHR) {
                    resequence({seqdef: data, src: null});
                });
            } else {
                throw new Error("AJAX loading independent from jQuery not yet implemented.");
            }
            return;
        }
        if (typeof seqdef == "object") {
            if (typeof jQuery != 'undefined' && seqdef instanceof jQuery) {
                resequence({seqdef: seqdef[0]})
                return;
            }
            resequence({seqdef: seqdef.innerHTML});
            return;
        }
        if (typeof seqdef == "string" && seqdef) {
            if (seqdef.trim) {
                seqdef = seqdef.trim();
            }
            if (seqdef.indexOf("\n") == -1) {
                if (typeof jQuery != 'undefined') {
                    var jqseqdef = jQuery(seqdef);
                    if (jqseqdef.length == 0) {
                        throw new Error("Not found: " + seqdef);
                    }
                    resequence(jqseqdef);
                } else {
                    if ("#" + seqdef.replace(/[^a-z0-9]/gi, '') == seqdef) {
                        resequence(document.getElementById(seqdef.substr(1, seqdef.length)));
                    } else {
                        throw new Error("DOM element selection independent from jQuery not yet implemented. If a full "
                            + "sequence was given, it cannot be on only one line.");
                    }
                }
                return;
            }

            // finally ...
            var seqdefstr = seqdef;
            seqdef = parseResequenceDefinition(seqdef);
            var description = "";
            for (var cmd in seqdef) {
                if (description.length > 0) description += "\n";
                description += seqdef[cmd].toString();
            }

            // all the following in this function due to non-implementation
            $('body').css('margin', '10px');
            $('pre#input-RO').html(seqdefstr.replace(/\</g, '<'));
            $('pre#output').html(description.replace(/\</g, '<'));
            processResequence(seqdef, targetEl);
        }
    }

    function addListener(obj, eventName, listener) { //function to add event
        if (obj.addEventListener) {
            obj.addEventListener(eventName, listener, false);
        } else {
            obj.attachEvent("on" + eventName, listener);
        }
    }
    addListener(document, "DOMContentLoaded", resequence);
    if (document.readyState == "complete"
        || document.readyState == "loaded"
        || document.readyState == "interactive") {
        resequence();
    }
    function ResequenceCommand(relativeToThis, element, position, action, container, nesting) {
        this.relative = relativeToThis;
        this.element = element;
        this.position = position;
        this.action = action;
        this.container = container;
        this.nesting = nesting;
        this.toString = function() {
            var relativeToThisStr = relativeToThis;
            if (typeof relativeToThis == 'object') {
                for (var p in relativeToThis) {
                    relativeToThisStr = "{" + p + ":" + relativeToThis[p] + "}";
                }
            }
            var elementStr = element;
            if (typeof element == 'object') {
                for (var p in element) {
                    elementStr = "{" + p + ":" + element[p] + "}";
                }
            }
            var ret = position + " " + relativeToThisStr + " " + action + " " + elementStr;
            if (relativeToThisStr === undefined) {
                if (action == "append") action = "prepend";
                ret = "at the top of the body, " + action + " " + elementStr;
            }
            if (ret.trim) ret = ret.trim();
            return ret;
        }
    }
    var POSITIONS = {
        "INSIDE": "inside",
        "AFTER": "after",
        "NEAR": "near"
    };
    var ACTIONS = {
        "APPEND": "append",
        "PREPEND": "prepend",
        "PREPENDCREATE": "prepend-create",
        "CREATE": "create",
        "HIDE": "hide",
        "REMOVE": "remove"
    }

    var createInsideAtTopL3Regexp = /^(\>\s*\>\s*\+\+\s*\^)\s*(.+)/;
    var createInsideL3Regexp = /^(\>\s*\>\s*\+\+)\s*(.+)/;
    var inside2Regexp = /^(\>\s*\>)\s*(.+)/;
    var insideTop2Regexp = /^(\>\s*\>\s*\^)\s*(.+)/;
    var hide3Regexp = /^(\>\s*\>\s*\-)\s*(.+)/;
    var remove3Regexp = /^(\>\s*\>\s*\-\s*\-)\s*(.+)/;
    var hide2Regexp = /^(\>\s*\-)\s*(.+)/;
    var remove2Regexp = /^(\>\s*\-\s*\-)\s*(.+)/;
    var insideRegexp = /^(\>)\s*(.+)/;
    var insideTopRegexp = /^(\>\s*\^)\s*(.+)/;
    var createAfterRegexp = /^(\+\+)\s*(.+)/;
    var createInsideRegexp = /^(\>\s*\+\+)\s*(.+)/;
    var createInsideAtTopRegexp = /^(\>\s*\+\+\s\^)\s*(.+)/;
    var hideRegexp = /^(\-)\s*(.+)/;
    var removeRegexp = /^(\-\s*\-)\s*(.+)/;

    function parseResequenceDefinition(seqdef) {
        if (seqdef.trim) seqdef = seqdef.trim();
        var cmdlines = seqdef.split('\n');
        var cmds = [];
        var previousElement;
        var previousNesting = 0;
        var outerElements = [];
        var previousElementOuter;

        for (var l in cmdlines) {
            var line = cmdlines[l];
            var tline = line;
            tline = tline.replace(/\([^)]*\)/g, ''); // remove parenthesis (they're comments)
            if (tline.trim) tline = tline.trim();

            var relativeTo = previousElement,
                element    = {find: tline},
                action     = ACTIONS.APPEND,
                position   = POSITIONS.AFTER;

            var nesting = 0;

            if (createInsideAtTopL3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideAtTopL3Regexp.exec(tline)[2]};
                action = ACTIONS.PREPENDCREATE;
                nesting = 2;
            }
            else if (createInsideL3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideL3Regexp.exec(tline)[2]};
                action = ACTIONS.CREATE;
                nesting = 2;
            }
            else if (inside2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: inside2Regexp.exec(tline)[2]};
                nesting = 2;
            }
            else if (insideTop2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: insideTop2Regexp.exec(tline)[2]};
                action = ACTIONS.PREPEND;
                nesting = 2;
            }
            else if (remove3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: remove3Regexp.exec(tline)[2]};
                action = ACTIONS.REMOVE;
                nesting = 2;
            }
            else if (hide3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: hide3Regexp.exec(tline)[2]};
                action = ACTIONS.HIDE;
                nesting = 2;
            }
            else if (inside2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: inside2Regexp.exec(tline)[2]};
                nesting = 2;
            }
            else if (remove2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: remove2Regexp.exec(tline)[2]};
                action = ACTIONS.REMOVE;
                nesting = 1;
            }
            else if (hide2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: hide2Regexp.exec(tline)[2]};
                action = ACTIONS.HIDE;
                nesting = 1;
            }
            else if (createInsideAtTopRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideAtTopRegexp.exec(tline)[2]};
                action = ACTIONS.PREPENDCREATE;
                nesting = 1;
            }
            else if (createInsideRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideRegexp.exec(tline)[2]};
                action = ACTIONS.CREATE;
                nesting = 1;
            }
            else if (insideTopRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: insideTopRegexp.exec(tline)[2]};
                action = ACTIONS.PREPEND;
                nesting = 1;
            }
            else if (insideRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: insideRegexp.exec(tline)[2]};
                nesting = 1;
            }
            else if (createAfterRegexp.test(tline)) {
                position = POSITIONS.AFTER;
                element = {create: createAfterRegexp.exec(tline)[2]};
                action = ACTIONS.CREATE;
            }
            else if (removeRegexp.test(tline)) {
                position = POSITIONS.NEAR;
                element = {find: removeRegexp.exec(tline)[2]};
                action = ACTIONS.REMOVE;
                nesting = 0;
            }
            else if (hideRegexp.test(tline)) {
                position = POSITIONS.NEAR;
                element = {find: hideRegexp.exec(tline)[2]};
                action = ACTIONS.HIDE;
                nesting = 0;
            }

            for (var i = nesting; i < previousNesting; i++) {
                outerElements.pop();
            }
            if (previousNesting > nesting || (nesting == previousNesting && nesting > 0)) {
                relativeTo = outerElements[outerElements.length - 1] || previousElementOuter;
            }
            if (nesting > previousNesting) {
                if (nesting == 1) previousElementOuter = previousElement;
                outerElements.push(previousElement);
            }
            var container = outerElements.length >= 1
                ? outerElements[outerElements.length - 1]
                : {find: 'body'};
            for (var cnr in container);
            container = container[cnr];
            cmds.push(new ResequenceCommand(relativeTo, element, position, action, container, nesting));
            if (action != ACTIONS.REMOVE) {
                previousElement = element;
                previousNesting = nesting;
            }
        }
        return cmds;
    }
    function processResequence(seqdef) {
        var created = {};
        var containers = ['body'];
        var prevNesting = 1;
        for (var c=0; c<seqdef.length; c++) {
            var cmd = seqdef[c];
            if (relative === undefined) {
                cmd = new ResequenceCommand(
                    {find: 'body'},
                    cmd.element,
                    POSITIONS.INSIDE,
                    cmd.action == ACTIONS.APPEND || cmd.action == ACTIONS.PREPEND
                        ? ACTIONS.PREPEND
                        : cmd.action
                );
            }
            var action = cmd.action;
            var element = cmd.element,
                el;
            var position = cmd.position;
            var relative = cmd.relative;
            var container = cmd.container;
            var nesting = (cmd.nesting || 0) + 1;
            for (var n=prevNesting; n>nesting; n--) {
                containers.pop();
            }
            if (nesting > prevNesting) {
                containers.push(container);
            }

            if (typeof jQuery != 'undefined') {
                var $ = jQuery;
                var relativeSelMode, relativeSel,
                    elementSelMode, elementSel;
                for (var relativeSelMode in relative)
                    relativeSel = relative[relativeSelMode];
                for (var elementSelMode in element);
                    elementSel = element[elementSelMode];
                var rel;
                switch (relativeSelMode) {
                    case "find":
                        rel = $(relativeSel);
                        break;
                    case "create":
                        rel = created[relativeSel];
                        break;
                }
                if (rel.length == 0) {
                    console.log("Warning: Relative selector was not found: " + relativeSel);
                    rel = $(document);
                    for (var cn=0; cn<containers.length; cn++) {
                        relativeSel = containers[cn];
                        rel = rel.find(relativeSel);
                    }
                    console.log("         Choosing next parent: " + rel[0].tagName)
                }
                var commonSelSetup = function(hard_relative) {
                    switch (position) {
                        case POSITIONS.NEAR:
                            rel = rel.parent();
                            el = rel.find(elementSel);
                            break;
                        case POSITIONS.INSIDE:
                            if (!hard_relative) {
                                el = $(elementSel);
                            } else {
                                el = rel.find(elementSel);
                            }
                            break;
                        case POSITIONS.AFTER:
                            if (!hard_relative) {
                                el = $(elementSel);
                            } else {
                                el = rel.nextAll(elementSel);
                                if (el.length == 0) el = rel.find(elementSel);
                            }
                            break;
                    }
                    if (el.length == 0) {
                        console.log("Warning: Selected element not found: " + elementSel);
                    }
                }
                switch (action) {
                    case ACTIONS.CREATE:
                        el = $(elementSel);
                        created[elementSel] = el;
                        switch (position) {
                            case POSITIONS.AFTER:
                            case POSITIONS.NEAR:
                                rel.after(el);
                                break;
                            case POSITIONS.INSIDE:
                                rel.append(el);
                                break;
                        }
                        break;
                    case ACTIONS.PREPENDCREATE:
                        el = $(elementSel);
                        created[elementSel] = el;
                        rel.prepend(el);
                        break;
                    case ACTIONS.APPEND:
                        commonSelSetup();
                        switch (position) {
                            case POSITIONS.AFTER:
                            case POSITIONS.NEAR:
                                rel.after(el);
                                break;
                            case POSITIONS.INSIDE:
                                rel.append(el);
                                break;
                        }
                        break;
                    case ACTIONS.HIDE:
                        commonSelSetup(true);
                        el.hide();
                        break;
                    case ACTIONS.PREPEND:
                        commonSelSetup();
                        switch (position) {
                            case POSITIONS.AFTER:
                            case POSITIONS.NEAR:
                                rel.before(el);
                                break;
                            case POSITIONS.INSIDE:
                                rel.prepend(el);
                                break;
                        }
                        break;
                    case ACTIONS.REMOVE:
                        commonSelSetup(true);
                        el.remove();
                        break;
                }
                prevNesting = nesting;

            } else {
                throw new Error("Not yet implemented without jQuery");
            }
        }
    }
}());<commit_msg>Basic implementation has been applied and basically "tested" manually. (Minor edit to properly annotate previous commit.)<commit_after>;
// Resequencer
// http://github.com/stimpy77/resequencerjs
// v0.1
(function() {
    "use strict";
    // <body data-resequence="#ID_OF_SCRIPT_CONTAINING_RESEQUENCE">
    // or
    // <body data-resequence-src="path.to.resequence.file.rseqdef">
    var g = window;
    var findBody, body = (findBody = document.getElementsByTagName('body')).length > 0 ? findBody[0] : null;
    var resequenceEl, resequenceSrc;
    if ((resequenceSrc = body.getAttribute("data-resequence-src")) == null &&
        (resequenceEl = body.getAttribute("data-resequence")) == null) {
        var scriptTags = document.getElementsByTagName("script");
        var seqscript;
        for (var s in scriptTags) {
            var ta = scriptTags[s].getAttribute("type");
            if (!!ta && ta == "text/resequencer") {
                resequenceEl = scriptTags[s];
                break;
            }
        }
        return;
    }
    var _opts = {
        src : resequenceSrc,
        seqdef  : resequenceEl,
        targetEl: body
    }
    var resequence = g.resequenceHTML = function resequence(seqdef, src, targetEl) {
        if (seqdef instanceof Event) {
            seqdef = undefined;
        }
        var opts = _opts;
        if (typeof seqdef == "object" && !(seqdef instanceof jQuery)) {
            for (var p in seqdef) {
                opts[p] = seqdef[p];
            }
            seqdef = null;
        }
        seqdef = seqdef || opts.seqdef;
        src = src || opts.src;
        targetEl = targetEl || opts.targetEl;

        if (src && !seqdef) {
            if (typeof jQuery != 'undefined') {
                jQuery.get(src, function(data, textStatus, jqXHR) {
                    resequence({seqdef: data, src: null});
                });
            } else {
                throw new Error("AJAX loading independent from jQuery not yet implemented.");
            }
            return;
        }
        if (typeof seqdef == "object") {
            if (typeof jQuery != 'undefined' && seqdef instanceof jQuery) {
                resequence({seqdef: seqdef[0]})
                return;
            }
            resequence({seqdef: seqdef.innerHTML});
            return;
        }
        if (typeof seqdef == "string" && seqdef) {
            if (seqdef.trim) {
                seqdef = seqdef.trim();
            }
            if (seqdef.indexOf("\n") == -1) {
                if (typeof jQuery != 'undefined') {
                    var jqseqdef = jQuery(seqdef);
                    if (jqseqdef.length == 0) {
                        throw new Error("Not found: " + seqdef);
                    }
                    resequence(jqseqdef);
                } else {
                    if ("#" + seqdef.replace(/[^a-z0-9]/gi, '') == seqdef) {
                        resequence(document.getElementById(seqdef.substr(1, seqdef.length)));
                    } else {
                        throw new Error("DOM element selection independent from jQuery not yet implemented. If a full "
                            + "sequence was given, it cannot be on only one line.");
                    }
                }
                return;
            }

            // finally ...
            var seqdefstr = seqdef;
            seqdef = parseResequenceDefinition(seqdef);
            var description = "";
            for (var cmd in seqdef) {
                if (description.length > 0) description += "\n";
                description += seqdef[cmd].toString();
            }

            // all the following in this function due to non-implementation
            $('body').css('margin', '10px');
            $('pre#input-RO').html(seqdefstr.replace(/\</g, '<'));
            $('pre#output').html(description.replace(/\</g, '<'));
            processResequence(seqdef, targetEl);
        }
    }

    function addListener(obj, eventName, listener) { //function to add event
        if (obj.addEventListener) {
            obj.addEventListener(eventName, listener, false);
        } else {
            obj.attachEvent("on" + eventName, listener);
        }
    }
    addListener(document, "DOMContentLoaded", resequence);
    if (document.readyState == "complete"
        || document.readyState == "loaded"
        || document.readyState == "interactive") {
        resequence();
    }
    function ResequenceCommand(relativeToThis, element, position, action, container, nesting) {
        this.relative = relativeToThis;
        this.element = element;
        this.position = position;
        this.action = action;
        this.container = container;
        this.nesting = nesting;
        this.toString = function() {
            var relativeToThisStr = relativeToThis;
            if (typeof relativeToThis == 'object') {
                for (var p in relativeToThis) {
                    relativeToThisStr = "{" + p + ":" + relativeToThis[p] + "}";
                }
            }
            var elementStr = element;
            if (typeof element == 'object') {
                for (var p in element) {
                    elementStr = "{" + p + ":" + element[p] + "}";
                }
            }
            var ret = position + " " + relativeToThisStr + " " + action + " " + elementStr;
            if (relativeToThisStr === undefined) {
                if (action == "append") action = "prepend";
                ret = "at the top of the body, " + action + " " + elementStr;
            }
            if (ret.trim) ret = ret.trim();
            return ret;
        }
    }
    var POSITIONS = {
        "INSIDE": "inside",
        "AFTER": "after",
        "NEAR": "near"
    };
    var ACTIONS = {
        "APPEND": "append",
        "PREPEND": "prepend",
        "PREPENDCREATE": "prepend-create",
        "CREATE": "create",
        "HIDE": "hide",
        "REMOVE": "remove"
    }

    var createInsideAtTopL3Regexp = /^(\>\s*\>\s*\+\+\s*\^)\s*(.+)/;
    var createInsideL3Regexp = /^(\>\s*\>\s*\+\+)\s*(.+)/;
    var inside2Regexp = /^(\>\s*\>)\s*(.+)/;
    var insideTop2Regexp = /^(\>\s*\>\s*\^)\s*(.+)/;
    var hide3Regexp = /^(\>\s*\>\s*\-)\s*(.+)/;
    var remove3Regexp = /^(\>\s*\>\s*\-\s*\-)\s*(.+)/;
    var hide2Regexp = /^(\>\s*\-)\s*(.+)/;
    var remove2Regexp = /^(\>\s*\-\s*\-)\s*(.+)/;
    var insideRegexp = /^(\>)\s*(.+)/;
    var insideTopRegexp = /^(\>\s*\^)\s*(.+)/;
    var createAfterRegexp = /^(\+\+)\s*(.+)/;
    var createInsideRegexp = /^(\>\s*\+\+)\s*(.+)/;
    var createInsideAtTopRegexp = /^(\>\s*\+\+\s\^)\s*(.+)/;
    var hideRegexp = /^(\-)\s*(.+)/;
    var removeRegexp = /^(\-\s*\-)\s*(.+)/;

    function parseResequenceDefinition(seqdef) {
        if (seqdef.trim) seqdef = seqdef.trim();
        var cmdlines = seqdef.split('\n');
        var cmds = [];
        var previousElement;
        var previousNesting = 0;
        var outerElements = [];
        var previousElementOuter;

        for (var l in cmdlines) {
            var line = cmdlines[l];
            var tline = line;
            tline = tline.replace(/\([^)]*\)/g, ''); // remove parenthesis (they're comments)
            if (tline.trim) tline = tline.trim();

            var relativeTo = previousElement,
                element    = {find: tline},
                action     = ACTIONS.APPEND,
                position   = POSITIONS.AFTER;

            var nesting = 0;

            if (createInsideAtTopL3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideAtTopL3Regexp.exec(tline)[2]};
                action = ACTIONS.PREPENDCREATE;
                nesting = 2;
            }
            else if (createInsideL3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideL3Regexp.exec(tline)[2]};
                action = ACTIONS.CREATE;
                nesting = 2;
            }
            else if (inside2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: inside2Regexp.exec(tline)[2]};
                nesting = 2;
            }
            else if (insideTop2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: insideTop2Regexp.exec(tline)[2]};
                action = ACTIONS.PREPEND;
                nesting = 2;
            }
            else if (remove3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: remove3Regexp.exec(tline)[2]};
                action = ACTIONS.REMOVE;
                nesting = 2;
            }
            else if (hide3Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: hide3Regexp.exec(tline)[2]};
                action = ACTIONS.HIDE;
                nesting = 2;
            }
            else if (inside2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: inside2Regexp.exec(tline)[2]};
                nesting = 2;
            }
            else if (remove2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: remove2Regexp.exec(tline)[2]};
                action = ACTIONS.REMOVE;
                nesting = 1;
            }
            else if (hide2Regexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: hide2Regexp.exec(tline)[2]};
                action = ACTIONS.HIDE;
                nesting = 1;
            }
            else if (createInsideAtTopRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideAtTopRegexp.exec(tline)[2]};
                action = ACTIONS.PREPENDCREATE;
                nesting = 1;
            }
            else if (createInsideRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {create: createInsideRegexp.exec(tline)[2]};
                action = ACTIONS.CREATE;
                nesting = 1;
            }
            else if (insideTopRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: insideTopRegexp.exec(tline)[2]};
                action = ACTIONS.PREPEND;
                nesting = 1;
            }
            else if (insideRegexp.test(tline)) {
                position = POSITIONS.INSIDE;
                element = {find: insideRegexp.exec(tline)[2]};
                nesting = 1;
            }
            else if (createAfterRegexp.test(tline)) {
                position = POSITIONS.AFTER;
                element = {create: createAfterRegexp.exec(tline)[2]};
                action = ACTIONS.CREATE;
            }
            else if (removeRegexp.test(tline)) {
                position = POSITIONS.NEAR;
                element = {find: removeRegexp.exec(tline)[2]};
                action = ACTIONS.REMOVE;
                nesting = 0;
            }
            else if (hideRegexp.test(tline)) {
                position = POSITIONS.NEAR;
                element = {find: hideRegexp.exec(tline)[2]};
                action = ACTIONS.HIDE;
                nesting = 0;
            }

            for (var i = nesting; i < previousNesting; i++) {
                outerElements.pop();
            }
            if (previousNesting > nesting || (nesting == previousNesting && nesting > 0)) {
                relativeTo = outerElements[outerElements.length - 1] || previousElementOuter;
            }
            if (nesting > previousNesting) {
                if (nesting == 1) previousElementOuter = previousElement;
                outerElements.push(previousElement);
            }
            var container = outerElements.length >= 1
                ? outerElements[outerElements.length - 1]
                : {find: 'body'};
            for (var cnr in container);
            container = container[cnr];
            cmds.push(new ResequenceCommand(relativeTo, element, position, action, container, nesting));
            if (action != ACTIONS.REMOVE) {
                previousElement = element;
                previousNesting = nesting;
            }
        }
        return cmds;
    }
    function processResequence(seqdef) {
        var created = {};
        var containers = ['body'];
        var prevNesting = 1;
        for (var c=0; c<seqdef.length; c++) {
            var cmd = seqdef[c];
            if (relative === undefined) {
                cmd = new ResequenceCommand(
                    {find: 'body'},
                    cmd.element,
                    POSITIONS.INSIDE,
                    cmd.action == ACTIONS.APPEND || cmd.action == ACTIONS.PREPEND
                        ? ACTIONS.PREPEND
                        : cmd.action
                );
            }
            var action = cmd.action;
            var element = cmd.element,
                el;
            var position = cmd.position;
            var relative = cmd.relative;
            var container = cmd.container;
            var nesting = (cmd.nesting || 0) + 1;
            for (var n=prevNesting; n>nesting; n--) {
                containers.pop();
            }
            if (nesting > prevNesting) {
                containers.push(container);
            }

            if (typeof jQuery != 'undefined') {
                var $ = jQuery;
                var relativeSelMode, relativeSel,
                    elementSelMode, elementSel;
                for (var relativeSelMode in relative)
                    relativeSel = relative[relativeSelMode];
                for (var elementSelMode in element);
                    elementSel = element[elementSelMode];
                var rel;
                switch (relativeSelMode) {
                    case "find":
                        rel = $(relativeSel);
                        break;
                    case "create":
                        rel = created[relativeSel];
                        break;
                }
                if (rel.length == 0) {
                    console.log("Warning: Relative selector was not found: " + relativeSel);
                    rel = $(document);
                    for (var cn=0; cn<containers.length; cn++) {
                        relativeSel = containers[cn];
                        rel = rel.find(relativeSel);
                    }
                    console.log("         Choosing next parent: " + rel[0].tagName)
                }
                var commonSelSetup = function(hard_relative) {
                    switch (position) {
                        case POSITIONS.NEAR:
                            rel = rel.parent();
                            el = rel.find(elementSel);
                            break;
                        case POSITIONS.INSIDE:
                            if (!hard_relative) {
                                el = $(elementSel);
                            } else {
                                el = rel.find(elementSel);
                            }
                            break;
                        case POSITIONS.AFTER:
                            if (!hard_relative) {
                                el = $(elementSel);
                            } else {
                                el = rel.nextAll(elementSel);
                                if (el.length == 0) el = rel.find(elementSel);
                            }
                            break;
                    }
                    if (el.length == 0) {
                        console.log("Warning: Selected element not found: " + elementSel);
                    }
                }
                switch (action) {
                    case ACTIONS.CREATE:
                        el = $(elementSel);
                        created[elementSel] = el;
                        switch (position) {
                            case POSITIONS.AFTER:
                            case POSITIONS.NEAR:
                                rel.after(el);
                                break;
                            case POSITIONS.INSIDE:
                                rel.append(el);
                                break;
                        }
                        break;
                    case ACTIONS.PREPENDCREATE:
                        el = $(elementSel);
                        created[elementSel] = el;
                        rel.prepend(el);
                        break;
                    case ACTIONS.APPEND:
                        commonSelSetup();
                        switch (position) {
                            case POSITIONS.AFTER:
                            case POSITIONS.NEAR:
                                rel.after(el);
                                break;
                            case POSITIONS.INSIDE:
                                rel.append(el);
                                break;
                        }
                        break;
                    case ACTIONS.HIDE:
                        commonSelSetup(true);
                        el.hide();
                        break;
                    case ACTIONS.PREPEND:
                        commonSelSetup();
                        switch (position) {
                            case POSITIONS.AFTER:
                            case POSITIONS.NEAR:
                                rel.before(el);
                                break;
                            case POSITIONS.INSIDE:
                                rel.prepend(el);
                                break;
                        }
                        break;
                    case ACTIONS.REMOVE:
                        commonSelSetup(true);
                        el.remove();
                        break;
                }
                prevNesting = nesting;

            } else {
                throw new Error("Not yet implemented without jQuery");
            }
        }
    }
}());<|endoftext|>


<commit_before>
var search_list = [];
var datearray = [];

function showHeadlines(){

  //if tempdata = x.filter(function(d){ return d.wordCol == key[i]; });
  d3.csv("http://singaporenews.github.io/Words_story_headlines_27oct.csv", function(error, data){
    list = [];
    theLength = d3.selectAll('.term_label')[0].length;
    for (i=0; i<theLength; i++){
      list.push(d3.selectAll('.term_label')[0][i].innerHTML);
    }

    /*
    data = $.map(data, function(element){
      return ($.inArray(element.wordCol,list)>-1?element:null)
    });
    */

    console.log(data[0]);

    line_svg.selectAll('.headline')
      .transition()
      .duration(400)
      .remove();

    line_svg.append('text')
      .transition()
      .duration(500)
      .attr("x", width/2)
      .attr("y", 50)
      .attr('class', 'headline')
      .style("text-anchor", "middle")
      .style("font-size", "16px")
      .style("fill", "#000")
      .text(data[0].headlineCol);

  })
}

function updateData(frm){
  search_list.push(frm.toLowerCase());
  d3.csv("http://singaporenews.github.io/transposed_terms_27oct.csv", function(error, data){

    line_color.domain(d3.keys(
      data[0]).filter(function(key){ return key.toLowerCase() !== 'headline_year'; }
      )
    );

    var headline_terms = line_color.domain().map(function(term){
      return {
        term: term.toLowerCase(),
        values: data.map(function(d){
          return {year: d.headline_year, count: +d[term]};
        })
      };
    });

    if (search_list.length > 5){
      length = search_list.length;
      search_list = search_list.slice(-5);
    };

    used_data = $.map(headline_terms, function(element){
      return ($.inArray(element.term,search_list)>-1?element:null)
    });

    line_color.domain(search_list);

    //used_data = headline_terms.filter(function(d){ return d.term == frm; });

    var xAxis = d3.svg.axis()
      .scale(line_x)
      .orient("bottom")
      .ticks(used_data[0].values.map(function(d){ return d.year; }));

    var yAxis = d3.svg.axis()
      .scale(line_y)
      .orient('left');

    var minY = d3.min(used_data, function(c){ return d3.min(c.values, function(v){
                  return v.count; });
                });

    var maxY = d3.max(used_data, function(c){ return d3.max(c.values, function(v){
                  return v.count; });
                });

    line_x.domain(used_data[0].values.map(function(d){ return d.year; }));

    line_y.domain([minY, maxY]);

    var term_label = line_svg.selectAll('.term_label')
        .data(used_data);

    term_label
        .enter()
      .append('text')
        .attr('class', 'term_label');

        /*
        .transition()
        .duration(750)
        .attr('class', 'term_label')
        .attr("x", -60)
        .attr("y", function(d,i){ return i+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .transition()
        .duration(750)
        .style('fill', function(d){ return color(d.term); })
        .text(function(d){ return d.term; });
      */
    term_label
        .transition()
        .duration(750)
        .attr("x", -70)
        .attr("y", function(d,i){ return i+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .transition()
        .duration(750)
        .style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d.term; });

    term_label.exit().transition().duration(750).remove();

    line_svg.selectAll('.line_y.axis')
      .transition()
      .duration(750)
      .call(yAxis);

    var terms = line_svg.selectAll('.terms');

    var termsLines = terms.selectAll('.line')
        .data(used_data);

    termsLines.enter().append('path')
        .transition()
        .duration(750)
        .attr('class', 'line')
        .attr('d', function(d){ return line(d.values); })
        .style('stroke', function(d){ return line_color(d.term); });

    termsLines.exit().transition().duration(750).remove();

    termsLines
      .transition()
      .duration(750)
      .attr('class', 'line')
      .attr('d', function(d){ return line(d.values); })
      .style('stroke', function(d){ return line_color(d.term); });

  });
};

function createChart(frm){
  search_list.push(frm);
  d3.csv("http://singaporenews.github.io/transposed_terms_27oct.csv", function(error, data){
    console.log(data);
    line_color.domain(d3.keys(
      data[0]).filter(function(key){ return key.toLowerCase() !== 'headline_year'; }
      )
    );

    var headline_terms = line_color.domain().map(function(term){
      return {
        term: term.toLowerCase(),
        values: data.map(function(d){
          return {year: d.headline_year, count: +d[term]};
        })
      };
    });

    used_data = headline_terms.filter(function(d){ return d.term == frm.toLowerCase(); });

    var xAxis = d3.svg.axis()
      .scale(line_x)
      .orient("bottom")
      .ticks(used_data[0].values.map(function(d){ return d.year; }));

    var yAxis = d3.svg.axis()
      .scale(line_y)
      .orient('left');

    var minY = d3.min(used_data, function(c){ return d3.min(c.values, function(v){
                  return v.count; });
                });

    var maxY = d3.max(used_data, function(c){ return d3.max(c.values, function(v){
                  return v.count; });
                });

    line_x.domain(used_data[0].values.map(function(d){ return d.year; }));

    line_y.domain([minY, maxY]);

    var term_label = line_svg.selectAll('term_label')
        .data(used_data)
        .enter()
      .append('text')
        .attr('class', 'term_label')
        .attr("x", -70)
        .attr("y", function(d,i){ return i+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .style("fill", "#53565A")
        .transition()
        .duration(750)
        .style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d.term; });

    line_svg.append('g')
        .attr('class', 'line_x axis')
        .attr('transform', 'translate(0,' + height + ')')
        .call(xAxis)
        .selectAll('text')
            .style('text-anchor', 'end')
            .attr('dx', '-.8em')
            .attr('dy', '.15em')
            .attr('transform', function(d){
              return 'rotate(-65)'
            });

    line_svg.append('g')
        .attr('class', 'line_y axis')
        .call(yAxis)
      .append('text')
        .attr('transform', 'rotate(-90)')
        .attr('y', 6)
        .attr('dy', '.71em')
        .style('text-anchor', 'end')
        .text('Count');

    var terms = line_svg.append('g')
              .attr('class', 'terms');

    var termsLines = terms.selectAll('.line')
        .data(used_data);

    termsLines.enter().append('path')
        .attr('class', 'line');

    termsLines.exit().remove();

    termsLines
      .attr('d', function(d){ return line(d.values); })
      .style('stroke', function(d){ return line_color(d.term); });
  });

}<commit_msg>update data<commit_after>
var search_list = [];
var datearray = [];

function showHeadlines(){

  //if tempdata = x.filter(function(d){ return d.wordCol == key[i]; });
  d3.csv("http://singaporenews.github.io/Words_story_headlines_27oct.csv", function(error, data){
    list = [];
    theLength = d3.selectAll('.term_label')[0].length;
    for (i=0; i<theLength; i++){
      list.push(d3.selectAll('.term_label')[0][i].innerHTML);
    }

    /*
    data = $.map(data, function(element){
      return ($.inArray(element.wordCol,list)>-1?element:null)
    });
    */
    headline = data[Math.floor((Math.random()*data.length) + 1)].headlineCol;

    console.log(data[0]);

    line_svg.selectAll('.headline')
      .transition()
      .duration(1000)
      .remove();

    line_svg.append('text')
      .transition()
      .duration(1000)
      .attr("x", width/2)
      .attr("y", 50)
      .attr('class', 'headline')
      .style("text-anchor", "middle")
      .style("font-size", "16px")
      .style("fill", "#000")
      .text(headline);

  })
}

function updateData(frm){
  search_list.push(frm.toLowerCase());
  d3.csv("http://singaporenews.github.io/transposed_terms_27oct.csv", function(error, data){

    line_color.domain(d3.keys(
      data[0]).filter(function(key){ return key.toLowerCase() !== 'headline_year'; }
      )
    );

    var headline_terms = line_color.domain().map(function(term){
      return {
        term: term.toLowerCase(),
        values: data.map(function(d){
          return {year: d.headline_year, count: +d[term]};
        })
      };
    });

    if (search_list.length > 5){
      length = search_list.length;
      search_list = search_list.slice(-5);
    };

    used_data = $.map(headline_terms, function(element){
      return ($.inArray(element.term,search_list)>-1?element:null)
    });

    line_color.domain(search_list);

    //used_data = headline_terms.filter(function(d){ return d.term == frm; });

    var xAxis = d3.svg.axis()
      .scale(line_x)
      .orient("bottom")
      .ticks(used_data[0].values.map(function(d){ return d.year; }));

    var yAxis = d3.svg.axis()
      .scale(line_y)
      .orient('left');

    var minY = d3.min(used_data, function(c){ return d3.min(c.values, function(v){
                  return v.count; });
                });

    var maxY = d3.max(used_data, function(c){ return d3.max(c.values, function(v){
                  return v.count; });
                });

    line_x.domain(used_data[0].values.map(function(d){ return d.year; }));

    line_y.domain([minY, maxY]);

    var term_label = line_svg.selectAll('.term_label')
        .data(used_data);

    term_label
        .enter()
      .append('text')
        .attr('class', 'term_label');

        /*
        .transition()
        .duration(750)
        .attr('class', 'term_label')
        .attr("x", -60)
        .attr("y", function(d,i){ return i+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .transition()
        .duration(750)
        .style('fill', function(d){ return color(d.term); })
        .text(function(d){ return d.term; });
      */
    term_label
        .transition()
        .duration(750)
        .attr("x", -70)
        .attr("y", function(d,i){ return i+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .transition()
        .duration(750)
        .style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d.term; });

    term_label.exit().transition().duration(750).remove();

    line_svg.selectAll('.line_y.axis')
      .transition()
      .duration(750)
      .call(yAxis);

    var terms = line_svg.selectAll('.terms');

    var termsLines = terms.selectAll('.line')
        .data(used_data);

    termsLines.enter().append('path')
        .transition()
        .duration(750)
        .attr('class', 'line')
        .attr('d', function(d){ return line(d.values); })
        .style('stroke', function(d){ return line_color(d.term); });

    termsLines.exit().transition().duration(750).remove();

    termsLines
      .transition()
      .duration(750)
      .attr('class', 'line')
      .attr('d', function(d){ return line(d.values); })
      .style('stroke', function(d){ return line_color(d.term); });

  });
};

function createChart(frm){
  search_list.push(frm);
  d3.csv("http://singaporenews.github.io/transposed_terms_27oct.csv", function(error, data){
    console.log(data);
    line_color.domain(d3.keys(
      data[0]).filter(function(key){ return key.toLowerCase() !== 'headline_year'; }
      )
    );

    var headline_terms = line_color.domain().map(function(term){
      return {
        term: term.toLowerCase(),
        values: data.map(function(d){
          return {year: d.headline_year, count: +d[term]};
        })
      };
    });

    used_data = headline_terms.filter(function(d){ return d.term == frm.toLowerCase(); });

    var xAxis = d3.svg.axis()
      .scale(line_x)
      .orient("bottom")
      .ticks(used_data[0].values.map(function(d){ return d.year; }));

    var yAxis = d3.svg.axis()
      .scale(line_y)
      .orient('left');

    var minY = d3.min(used_data, function(c){ return d3.min(c.values, function(v){
                  return v.count; });
                });

    var maxY = d3.max(used_data, function(c){ return d3.max(c.values, function(v){
                  return v.count; });
                });

    line_x.domain(used_data[0].values.map(function(d){ return d.year; }));

    line_y.domain([minY, maxY]);

    var term_label = line_svg.selectAll('term_label')
        .data(used_data)
        .enter()
      .append('text')
        .attr('class', 'term_label')
        .attr("x", -70)
        .attr("y", function(d,i){ return i+"em"; })
        .style("text-anchor", "middle")
        .style("font-size", "16px")
        .style("fill", "#53565A")
        .transition()
        .duration(750)
        .style('fill', function(d){ return line_color(d.term); })
        .text(function(d){ return d.term; });

    line_svg.append('g')
        .attr('class', 'line_x axis')
        .attr('transform', 'translate(0,' + height + ')')
        .call(xAxis)
        .selectAll('text')
            .style('text-anchor', 'end')
            .attr('dx', '-.8em')
            .attr('dy', '.15em')
            .attr('transform', function(d){
              return 'rotate(-65)'
            });

    line_svg.append('g')
        .attr('class', 'line_y axis')
        .call(yAxis)
      .append('text')
        .attr('transform', 'rotate(-90)')
        .attr('y', 6)
        .attr('dy', '.71em')
        .style('text-anchor', 'end')
        .text('Count');

    var terms = line_svg.append('g')
              .attr('class', 'terms');

    var termsLines = terms.selectAll('.line')
        .data(used_data);

    termsLines.enter().append('path')
        .attr('class', 'line');

    termsLines.exit().remove();

    termsLines
      .attr('d', function(d){ return line(d.values); })
      .style('stroke', function(d){ return line_color(d.term); });
  });

}<|endoftext|>


<commit_before>var viewSection = {};

viewSection.handleMainNav = function(){
  $('nav').on('click', '.tab', function(){
    var target = $(this);
    $('.main-section').hide();
    $('.tab').removeClass('active');
    $('.main-section').each(function(index){
      if($(this).attr('id') === target.attr('data-content')){
        $(target).addClass('active');
        $(this).fadeIn(2000);
      }
    });
  });
};

viewSection.initIndexPage = function(){
  viewSection.handleMainNav();
};

$(function(){
  viewSection.initIndexPage();
  $('nav').find('a', 'Projects').click();
});
<commit_msg>Adjusting fadein to compensate for slower load time experienced in live-server and the new ajax.<commit_after>var viewSection = {};

viewSection.handleMainNav = function(){
  $('nav').on('click', '.tab', function(){
    var target = $(this);
    $('.main-section').hide();
    $('.tab').removeClass('active');
    $('.main-section').each(function(index){
      if($(this).attr('id') === target.attr('data-content')){
        $(target).addClass('active');
        $(this).fadeIn(500);
      }
    });
  });
};

viewSection.initIndexPage = function(){
  viewSection.handleMainNav();
};

$(function(){
  viewSection.initIndexPage();
  $('nav').find('a', 'Projects').click();
});
<|endoftext|>


<commit_before>/**
* @class solgs
* general solGS app wide and misc functions
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/

JSAN.use('jquery.blockUI');
JSAN.use('jquery.form');

function solGS () {};

solGS.waitPage = function (page) {

    if ( page.match(/solgs\/trait\//) || page.match(/solgs\/model\/combined\/trials\//)) {
    	askUser(page);
    } else {
    	blockPage(page);
    }

}

function  askUser(page, args) {

    var t = '
This analysis may take longer than 20 min. '
	+ 'Would you like to be emailed when it is done?
';

    jQuery('
')
	.html(t)
	.dialog({
	    height : 200,
	    width  : 400,
	    modal  : true,
	    title  : "Analysis update message",
 	    buttons: {
		No: { text: "No, I will wait...",
                      click: function() {
			  jQuery(this).dialog("close");

			  displayAnalysisNow(page, args);
		      },
		    },

		Yes: { text: "Yes",
                       click: function() {
			   jQuery(this).dialog("close");

			   checkUserLogin(page, args);
		       },
		     }
	    }
	});

}

function checkUserLogin (page, args) {

    if (args === undefined) {
	args = {};
    }

    jQuery.ajax({
	type    : 'POST',
	dataType: 'json',
	url     : '/solgs/check/user/login/',
	success : function(response) {
            if (response.loggedin) {
		var contact = response.contact;

		args['user_name']  = contact.name;
		args['user_email'] = contact.email;

		getProfileDialog(page, args);

            } else {

		loginAlert();

	    }
	}
    });

}

function loginAlert () {

    jQuery('
')
	.html('To use this feature, you need to log in and start over the process.')
	.dialog({
	    height : 200,
	    width  : 250,
	    modal  : true,
	    title  : 'Login Alert',
	    buttons: {
		OK: function () {
		    jQuery(this).dialog('close');

		    loginUser();
		}
	    }
	});

}

function loginUser () {

   window.location = '/solpeople/login.pl?goto_url=' + window.location.pathname;

}

function displayAnalysisNow (page, args) {

    blockPage(page, args);

 }

function blockPage (page, args) {

    goToPage(page, args);

    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
    jQuery.blockUI({message: 'Please wait..'});

    jQuery(window).unload(function()  {
	jQuery.unblockUI();
    });

}

function goToPage (page, args) {

    if (page.match(/solgs\/confirm\/request/)) {

	window.location = page;

    } else if (page.match(/solgs\/analyze\/traits\/population\//)) {

	submitTraitSelections(page, args);

    } else if (page.match(/solgs\/trait\//)) {

	window.location = page;

    } else if (page.match(/solgs\/models\/combined\/trials\//)) {

	submitTraitSelections(page, args);

    }

}

function submitTraitSelections (page, args) {

    wrapTraitsForm();

    if ( typeof args.analysis_name == 'undefined') {
	document.getElementById('traits_selection_form').submit();
	document.getElementById('traits_selection_form').reset();
    } else {
	jQuery('#traits_selection_form').ajaxSubmit();
	jQuery('#traits_selection_form').resetForm();
    }
}

function wrapTraitsForm () {

    var popId  = jQuery('#population_id').val();
    var formId = ' id="traits_selection_form"';

    var action;
    var referer = window.location.href;

    if ( referer.match(/solgs\/populations\/combined\//) ) {
	action = ' action="/solgs/models/combined/trials/' + popId + '"';
    }

    if ( referer.match(/solgs\/population\//) ) {
	action = ' action="/solgs/analyze/traits/population/' + popId + '"';
    }

    var method = ' method="POST"';

    var traitsForm = '<form'
	+ formId
	+ action
	+ method
	+ '>'
	+ '</form>';

    jQuery('#population_traits_list').wrap(traitsForm);

}

function getProfileDialog (page, args) {

    if (page.match(/solgs\/trait\//) || page.match(/solgs\/model\/combined\/trials\//)) {
	args = getArgsFromUrl(page, args);
    }

    var form = getProfileForm(args);

    jQuery('
', {id: 'email-form'})
	.html(form)
	.dialog({
	    height : 300,
	    width  : 300,
	    modal  : true,
	    title  : 'Info about your analysis.',
 	    buttons: {
		Submit: function() {

		    var userName  = jQuery("#user_name").val();
		    var userEmail = jQuery("#user_email").val();

		    var analysisName = jQuery('#analysis_name').val();
		    var analysisType = args.analysis_type;

		    var dataSetType = args.data_set_type;

		    args['user_email'] = userEmail;
		    args = JSON.stringify(args);

		    var analysisProfile = {
			'user_name'    : userName,
			'user_email'   : userEmail,
			'analysis_name': analysisName,
			'analysis_page': page,
			'analysis_type': analysisType,
			'data_set_type': dataSetType,
			'arguments'    : args,
		    }

		    jQuery(this).dialog('close');

		    saveAnalysisProfile(analysisProfile);
		},
		Cancel:  function() {
		    jQuery(this).dialog('close');
		},
	    }
	});

}

function getArgsFromUrl (url, args) {

    if (url.match(/solgs\/trait\//)) {

	var urlStr = url.split(/\/+/);

	if (!args) {

	    args = {'trait_id'      : [ urlStr[4] ],
		    'population_id' : [ urlStr[6] ],
		    'analysis_type' : 'single model',
		    'data_set_type' : 'single population',
		   };
	}
	else {

	    args['trait_id']      = [ urlStr[4]  ];
	    args['population_id'] = [  urlStr[6] ] ;
	    args['analysis_type'] = 'single model';
	    args['data_set_type'] = 'single population';

	}
    }

    if (url.match(/solgs\/model\/combined\/trials\//)) {

	var urlStr = url.split(/\/+/);

	if (!args) {

	    args = {'trait_id'      : [ urlStr[8] ],
		    'population_id' : [ urlStr[6] ],
		    'analysis_type' : 'single model',
		    'data_set_type' : 'combined populations',
		   };
	}
	else {

	    args['trait_id']      = [ urlStr[8]  ];
	    args['population_id'] = [  urlStr[6] ] ;
	    args['analysis_type'] = 'single model';
	    args['data_set_type'] = 'combined populations';

	}
    }

    return args;

}

function getProfileForm (args) {

    var email = '';
    if (args.user_email) {
	email = args.user_email;
    }

    var userName = '';
    if (args.user_name) {
	userName = args.user_name;
    }

    var emailForm = '
Please fill in your:
'
	+'
'
	+  '
'
     	+  'name:	'
     	+  '<input type="text" name="user_name" id="user_name" value=\"' + userName + '\"/>	'
     	+  '
'
	+  '
'
	+  'analysis name:	'
	+  '<input  type="text" name="analysis_name" id="analysis_name">	'
	+  '
'
        +  '
'
     	+  'email:	'
     	+  '<input type="text" name="user_email" id="user_email" value=\"' + email + '\"/>	'
     	+  '
'
	+'
';

    return emailForm;
}

jQuery(document).ready(function (){

     jQuery('#runGS').on('click',  function() {

	 var hostName = window.location.protocol
	     + '//'
	     + window.location.host;

	 var referer = window.location.href;

	 if ( referer.match(/solgs\/populations\/combined\//) ) {

	     dataSetType = 'combined populations';
	 }

	 if ( referer.match(/solgs\/population\//) ) {

	     dataSetType = 'single population';
	 }

	 var traitIds = jQuery("#traits_selection_div :checkbox").fieldValue();
	 var popId = jQuery('#population_id').val();

	 var page;
	 var analysisType;
	 var dataSetType;

	 if (traitIds.length == 1 ) {

	     analysisType = 'single model';

	     if ( referer.match(/solgs\/populations\/combined\//) ) {

		 page = hostName
		     + '/solgs/model/combined/trials/'
		     + popId
		     + '/trait/'
		     + traitIds[0];

	     } else if ( referer.match(/solgs\/population\//)) {

		 page = hostName
		     + '/solgs/trait/'
		     + traitIds[0]
		     + '/population/'
		     + popId;
	     }

	 } else {

	      analysisType = 'multiple models';

	     if ( referer.match(/solgs\/populations\/combined\//) ) {
		 page = hostName
		     + '/solgs/models/combined/trials/'
		     + popId;

	     } else {

		 page = hostName
		     + '/solgs/analyze/traits/population/'
		     + popId;
	     }
	 }

	 var args = {'trait_id'      : traitIds,
		     'population_id' : [ popId ],
		     'analysis_type' : analysisType,
		     'data_set_type' : dataSetType,
		    };

	 askUser(page, args);

     });

});

function saveAnalysisProfile (profile) {

    jQuery.ajax({
	type    : 'POST',
	dataType: 'json',
	data    : profile,
	url     : '/solgs/save/analysis/profile/',
	success : function(response) {
            if (response.result) {
		runAnalysis(profile);
		confirmRequest();

            } else {
		jQuery('
', {id: 'error-message'})
		    .html('Failed saving your analysis profile.')
		    .dialog({
			height : 200,
			width  : 250,
			modal  : true,
			title  : 'Error message',
			buttons: {
			    OK: function () {
				jQuery(this).dialog('close');
				window.location = window.location.href;
			    }
			}
		    });
            }
	},
	error: function () {
	    jQuery('
')
		.html('Error occured calling the function to save your analysis profile.')
		.dialog({
		    height : 200,
		    width  : 250,
		    modal  : true,
		    title  : 'Error message',
		    buttons: {
			OK: function () {
			    jQuery(this).dialog('close');
			    window.location = window.location.href;
			}
		    }
		});
	}
    });

}

function runAnalysis (profile) {

    jQuery.ajax({
	dataType: 'json',
	type    : 'POST',
 	data    : profile,
	url     : '/solgs/run/saved/analysis/',
    });

}

function confirmRequest () {

    blockPage('/solgs/confirm/request');

}

//executes two functions alternately
jQuery.fn.alternateFunctions = function(a, b) {
    return this.each(function() {
        var clicked = false;
        jQuery(this).bind("click", function() {
            if (clicked) {
                clicked = false;
                return b.apply(this, arguments);

            }
            clicked = true;
             return a.apply(this, arguments);

        });
    });
};

<commit_msg>compact logic...<commit_after>/**
* @class solgs
* general solGS app wide and misc functions
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/

JSAN.use('jquery.blockUI');
JSAN.use('jquery.form');

function solGS () {};

solGS.waitPage = function (page) {

    if ( page.match(/solgs\/trait\//) || page.match(/solgs\/model\/combined\/trials\//)) {
    	askUser(page);
    } else {
    	blockPage(page);
    }

}

function  askUser(page, args) {

    var t = '
This analysis may take longer than 20 min. '
	+ 'Would you like to be emailed when it is done?
';

    jQuery('
')
	.html(t)
	.dialog({
	    height : 200,
	    width  : 400,
	    modal  : true,
	    title  : "Analysis update message",
 	    buttons: {
		No: { text: "No, I will wait...",
                      click: function() {
			  jQuery(this).dialog("close");

			  displayAnalysisNow(page, args);
		      },
		    },

		Yes: { text: "Yes",
                       click: function() {
			   jQuery(this).dialog("close");

			   checkUserLogin(page, args);
		       },
		     }
	    }
	});

}

function checkUserLogin (page, args) {

    if (args === undefined) {
	args = {};
    }

    jQuery.ajax({
	type    : 'POST',
	dataType: 'json',
	url     : '/solgs/check/user/login/',
	success : function(response) {
            if (response.loggedin) {
		var contact = response.contact;

		args['user_name']  = contact.name;
		args['user_email'] = contact.email;

		getProfileDialog(page, args);

            } else {

		loginAlert();

	    }
	}
    });

}

function loginAlert () {

    jQuery('
')
	.html('To use this feature, you need to log in and start over the process.')
	.dialog({
	    height : 200,
	    width  : 250,
	    modal  : true,
	    title  : 'Login Alert',
	    buttons: {
		OK: function () {
		    jQuery(this).dialog('close');

		    loginUser();
		}
	    }
	});

}

function loginUser () {

   window.location = '/solpeople/login.pl?goto_url=' + window.location.pathname;

}

function displayAnalysisNow (page, args) {

    blockPage(page, args);

 }

function blockPage (page, args) {

    goToPage(page, args);

    jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
    jQuery.blockUI({message: 'Please wait..'});

    jQuery(window).unload(function()  {
	jQuery.unblockUI();
    });

}

function goToPage (page, args) {

    if (page.match(/[solgs\/confirm\/request\/ | solgs\/trait\/]/)) {

	window.location = page;

    } else if (page.match(/[solgs\/analyze\/traits\/population\/ | solgs\/models\/combined\/trials\/]/)) {

	submitTraitSelections(page, args);

    } else {

	window.location = window.location.href;

    }

}

function submitTraitSelections (page, args) {

    wrapTraitsForm();

    if ( typeof args.analysis_name == 'undefined') {
	document.getElementById('traits_selection_form').submit();
	document.getElementById('traits_selection_form').reset();
    } else {
	jQuery('#traits_selection_form').ajaxSubmit();
	jQuery('#traits_selection_form').resetForm();
    }
}

function wrapTraitsForm () {

    var popId  = jQuery('#population_id').val();
    var formId = ' id="traits_selection_form"';

    var action;
    var referer = window.location.href;

    if ( referer.match(/solgs\/populations\/combined\//) ) {
	action = ' action="/solgs/models/combined/trials/' + popId + '"';
    }

    if ( referer.match(/solgs\/population\//) ) {
	action = ' action="/solgs/analyze/traits/population/' + popId + '"';
    }

    var method = ' method="POST"';

    var traitsForm = '<form'
	+ formId
	+ action
	+ method
	+ '>'
	+ '</form>';

    jQuery('#population_traits_list').wrap(traitsForm);

}

function getProfileDialog (page, args) {

    if (page.match(/solgs\/trait\//) || page.match(/solgs\/model\/combined\/trials\//)) {
	args = getArgsFromUrl(page, args);
    }

    var form = getProfileForm(args);

    jQuery('
', {id: 'email-form'})
	.html(form)
	.dialog({
	    height : 300,
	    width  : 300,
	    modal  : true,
	    title  : 'Info about your analysis.',
 	    buttons: {
		Submit: function() {

		    var userName  = jQuery("#user_name").val();
		    var userEmail = jQuery("#user_email").val();

		    var analysisName = jQuery('#analysis_name').val();
		    var analysisType = args.analysis_type;

		    var dataSetType = args.data_set_type;

		    args['user_email'] = userEmail;
		    args = JSON.stringify(args);

		    var analysisProfile = {
			'user_name'    : userName,
			'user_email'   : userEmail,
			'analysis_name': analysisName,
			'analysis_page': page,
			'analysis_type': analysisType,
			'data_set_type': dataSetType,
			'arguments'    : args,
		    }

		    jQuery(this).dialog('close');

		    saveAnalysisProfile(analysisProfile);
		},
		Cancel:  function() {
		    jQuery(this).dialog('close');
		},
	    }
	});

}

function getArgsFromUrl (url, args) {

    if (url.match(/solgs\/trait\//)) {

	var urlStr = url.split(/\/+/);

	if (!args) {

	    args = {'trait_id'      : [ urlStr[4] ],
		    'population_id' : [ urlStr[6] ],
		    'analysis_type' : 'single model',
		    'data_set_type' : 'single population',
		   };
	}
	else {

	    args['trait_id']      = [ urlStr[4]  ];
	    args['population_id'] = [  urlStr[6] ] ;
	    args['analysis_type'] = 'single model';
	    args['data_set_type'] = 'single population';

	}
    }

    if (url.match(/solgs\/model\/combined\/trials\//)) {

	var urlStr = url.split(/\/+/);

	if (!args) {

	    args = {'trait_id'      : [ urlStr[8] ],
		    'population_id' : [ urlStr[6] ],
		    'analysis_type' : 'single model',
		    'data_set_type' : 'combined populations',
		   };
	}
	else {

	    args['trait_id']      = [ urlStr[8]  ];
	    args['population_id'] = [  urlStr[6] ] ;
	    args['analysis_type'] = 'single model';
	    args['data_set_type'] = 'combined populations';

	}
    }

    return args;

}

function getProfileForm (args) {

    var email = '';
    if (args.user_email) {
	email = args.user_email;
    }

    var userName = '';
    if (args.user_name) {
	userName = args.user_name;
    }

    var emailForm = '
Please fill in your:
'
	+'
'
	+  '
'
     	+  'name:	'
     	+  '<input type="text" name="user_name" id="user_name" value=\"' + userName + '\"/>	'
     	+  '
'
	+  '
'
	+  'analysis name:	'
	+  '<input  type="text" name="analysis_name" id="analysis_name">	'
	+  '
'
        +  '
'
     	+  'email:	'
     	+  '<input type="text" name="user_email" id="user_email" value=\"' + email + '\"/>	'
     	+  '
'
	+'
';

    return emailForm;
}

jQuery(document).ready(function (){

     jQuery('#runGS').on('click',  function() {

	 var hostName = window.location.protocol
	     + '//'
	     + window.location.host;

	 var referer = window.location.href;

	 if ( referer.match(/solgs\/populations\/combined\//) ) {

	     dataSetType = 'combined populations';
	 }

	 if ( referer.match(/solgs\/population\//) ) {

	     dataSetType = 'single population';
	 }

	 var traitIds = jQuery("#traits_selection_div :checkbox").fieldValue();
	 var popId = jQuery('#population_id').val();

	 var page;
	 var analysisType;
	 var dataSetType;

	 if (traitIds.length == 1 ) {

	     analysisType = 'single model';

	     if ( referer.match(/solgs\/populations\/combined\//) ) {

		 page = hostName
		     + '/solgs/model/combined/trials/'
		     + popId
		     + '/trait/'
		     + traitIds[0];

	     } else if ( referer.match(/solgs\/population\//)) {

		 page = hostName
		     + '/solgs/trait/'
		     + traitIds[0]
		     + '/population/'
		     + popId;
	     }

	 } else {

	      analysisType = 'multiple models';

	     if ( referer.match(/solgs\/populations\/combined\//) ) {
		 page = hostName
		     + '/solgs/models/combined/trials/'
		     + popId;

	     } else {

		 page = hostName
		     + '/solgs/analyze/traits/population/'
		     + popId;
	     }
	 }

	 var args = {'trait_id'      : traitIds,
		     'population_id' : [ popId ],
		     'analysis_type' : analysisType,
		     'data_set_type' : dataSetType,
		    };

	 askUser(page, args);

     });

});

function saveAnalysisProfile (profile) {

    jQuery.ajax({
	type    : 'POST',
	dataType: 'json',
	data    : profile,
	url     : '/solgs/save/analysis/profile/',
	success : function(response) {
            if (response.result) {
		runAnalysis(profile);
		confirmRequest();

            } else {
		jQuery('
', {id: 'error-message'})
		    .html('Failed saving your analysis profile.')
		    .dialog({
			height : 200,
			width  : 250,
			modal  : true,
			title  : 'Error message',
			buttons: {
			    OK: function () {
				jQuery(this).dialog('close');
				window.location = window.location.href;
			    }
			}
		    });
            }
	},
	error: function () {
	    jQuery('
')
		.html('Error occured calling the function to save your analysis profile.')
		.dialog({
		    height : 200,
		    width  : 250,
		    modal  : true,
		    title  : 'Error message',
		    buttons: {
			OK: function () {
			    jQuery(this).dialog('close');
			    window.location = window.location.href;
			}
		    }
		});
	}
    });

}

function runAnalysis (profile) {

    jQuery.ajax({
	dataType: 'json',
	type    : 'POST',
 	data    : profile,
	url     : '/solgs/run/saved/analysis/',
    });

}

function confirmRequest () {

    blockPage('/solgs/confirm/request');

}

//executes two functions alternately
jQuery.fn.alternateFunctions = function(a, b) {
    return this.each(function() {
        var clicked = false;
        jQuery(this).bind("click", function() {
            if (clicked) {
                clicked = false;
                return b.apply(this, arguments);

            }
            clicked = true;
             return a.apply(this, arguments);

        });
    });
};

<|endoftext|>


<commit_before>Assembly.prototype.squarePlot = function(parent_div, scale_type, max_count, max_span) {

  // setup plot dimensions
  var size = 600;
  var margin = {top: 80, right: 20, bottom: 60, left: 20},
    width = size - margin.left - margin.right,
    height = size - margin.top - margin.bottom;
  var tick = 10;
  var w = 12; // coloured box size for legend

  if (!scale_type) scale_type = 'linear'
  if (!max_count) max_count = this.scaffold_count //.toLocaleString()
  if (!max_span) max_span = this.assembly

  var x = d3.scale.linear()
    .domain([1, max_count])
    .range([0, width])
    .nice();

  var y = d3.scale.linear()
    .domain([1, max_span])
    .range([height, 0])
    .nice();

  var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
      .tickFormat(d3.format("s"));
  this.xAxis = xAxis;
  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
      .tickFormat(d3.format("s"));
  this.yAxis = yAxis;

  this.parent_div = parent_div;
  var parent = d3.select('#' + parent_div);
  var svg = parent.append('svg');

  svg.attr('width', '100%')
    .attr('height', '100%')
    .attr('viewBox', '0 0 ' + size + ' ' + size)
    .attr('preserveAspectRatio', 'xMidYMid meet')
  var plot_area = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
    .call(xAxis)
    .selectAll("text")
    .attr("y", 0)
    .attr("x", 9)
    .attr("dy", ".35em")
    .attr("transform", "rotate(90)")
    .style("text-anchor", "start");

  svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .call(yAxis);

  this.svg = svg;
  this.plot_area = plot_area;
  this.xScale = x;
  this.yScale = y;
  this.max_count = max_count;
  this.max_span = max_span;
  this.line_data = [];
  var data = this.prepareLine()
  this.addLine(data,this.name,this);
  this.line_data[0].line.classed('asm-reference-line',true).transition().duration(500).style('opacity',1)

  return this;
}

Assembly.prototype.addKey = function(assemblies) {
  var current = this;
  var plot_area = this.plot_area
  var group = plot_area.append('g').attr('class','asm-square-key');
  var height = assemblies.length * 25;
  var width = 200;
  group.attr('transform','translate(370,'+(430-height)+')')
  var rows = group.selectAll('g').data(assemblies);
  var rows_enter = rows.enter().append('g').attr('class',function(d,i){ var css = 'asm-square-key-row '; if (i == 0){css += 'asm-reference-key'} return css})
                        .attr('transform',function(d,i){return 'translate(0,'+(i*25)+')'})
  var rect = rows_enter.append('rect').attr('height',25).attr('width',150).attr('y',-12.5).style('fill','rgba(255,255,255,0.01)');
  rows_enter.append('text').attr('class',function(d){return 'asm-square-key-text '+d});
  rows.select('text').text(function(d){return d})
  rect.on('mouseover',function(d){
    //d3.select(this).style('fill','rgba(0,0,0,0.3)')
    plot_area.select('text.'+d).classed('asm-square-focus',true)
    plot_area.select('path.'+d).classed('asm-square-focus',true)
  })
  rect.on('click',function(d){
    //d3.select(this).style('fill','rgba(0,0,0,0.3)')
    var obj = findByValue(current.line_data,'name',d)
    current.zoomTo(obj)
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  rect.on('mouseout',function(d){
    //d3.select(this).style('fill','rgba(0,0,0,0.01)')
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  return this;
}

function findByValue(source, key, value) {
  for (var i = 0; i < source.length; i++) {
    if (source[i][key] === value) {
      return source[i];
    }
  }
}

Assembly.prototype.zoomTo = function(obj){
  var xScale = this.xScale;
  var yScale = this.yScale;
  xScale.domain([1,obj.count]).nice()
  this.max_count = obj.count;
  yScale.domain([1,obj.span]).nice()
  this.max_span = obj.span;
  this.svg.selectAll("g.y.axis").transition().duration(500)
      .call(this.yAxis);
  this.svg.selectAll("g.x.axis")
      .transition().duration(500).call(this.xAxis)
      .selectAll("text")
      .attr("y", 0)
      .attr("x", 9)
      .attr("dy", ".35em")
      .attr("transform", "rotate(90)")
      .style("text-anchor", "start");
  var line_data = this.line_data;
  var reference = this;
  line_data.forEach(function(line){
    reference.rescaleLine(line);
  })
}

Assembly.prototype.prepareLine = function() {
  var current = this;
  var line_data = [];
  current.npct_count.forEach(function(count,index){
    line_data[index] = {x:count,y:((index+1)/1000*current.assembly)}
  })
  return line_data;
}

Assembly.prototype.addLine = function(data,classname,assembly) {
  var xScale = this.xScale;
  var yScale = this.yScale;
  var plot_area = this.plot_area;
  var current = this;
  var rescale = 0;

  var lineFunction = d3.svg.line()
                            .x(function(d) { return xScale(d.x); })
                            .y(function(d) { return yScale(d.y); })
                            .interpolate("linear");
  this.lineFunction = lineFunction;
  var lineGraph = this.plot_area.append("path")
                              .attr("d", lineFunction(data))
                              .attr("class", 'asm-cumulative-line '+classname)
                              .attr("rel", classname)
                              .style('opacity',0)
  lineGraph.on('mouseover',function(){
    var d = d3.select(this).attr('rel')
    plot_area.select('text.'+d).classed('asm-square-focus',true)
    plot_area.select('path.'+d).classed('asm-square-focus',true)
  })
  lineGraph.on('click',function(){
    var d = d3.select(this).attr('rel')
    var obj = findByValue(current.line_data,'name',d)
    current.zoomTo(obj)
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  lineGraph.on('mouseout',function(){
    var d = d3.select(this).attr('rel')
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  this.line_data.push({name:classname,data:data,line:lineGraph,count:assembly.scaffold_count,span:assembly.assembly})

  if (assembly.scaffold_count > this.max_count){
    rescale = 1;
    xScale.domain([1,assembly.scaffold_count]).nice()
    this.max_count = assembly.scaffold_count;
  }
  if (assembly.assembly > this.max_span){
    rescale = 1
    yScale.domain([1,assembly.assembly]).nice()
    this.max_span = assembly.assembly;
  }
  if (rescale){
    this.svg.selectAll("g.y.axis").transition().duration(500)
        .call(this.yAxis);
    this.svg.selectAll("g.x.axis")
        .transition().duration(500).call(this.xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(90)")
        .style("text-anchor", "start");
    var line_data = this.line_data;
    var reference = this;
    line_data.forEach(function(line){
      reference.rescaleLine(line);
    })
  }
  else {
    lineGraph.transition().duration(500).style('opacity',1)
  }
}

Assembly.prototype.rescaleLine = function(line_data) {
  line_data.line.transition().duration(500).attr("d", this.lineFunction(line_data.data)).style('opacity',1)
}
<commit_msg>adjust positioning<commit_after>Assembly.prototype.squarePlot = function(parent_div, scale_type, max_count, max_span) {

  // setup plot dimensions
  var size = 600;
  var margin = {top: 40, right: 40, bottom: 50, left: 50},
    width = size - margin.left - margin.right,
    height = size - margin.top - margin.bottom;
  var tick = 10;
  var w = 12; // coloured box size for legend

  if (!scale_type) scale_type = 'linear'
  if (!max_count) max_count = this.scaffold_count //.toLocaleString()
  if (!max_span) max_span = this.assembly

  var x = d3.scale.linear()
    .domain([1, max_count])
    .range([0, width])
    .nice();

  var y = d3.scale.linear()
    .domain([1, max_span])
    .range([height, 0])
    .nice();

  var xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
      .tickFormat(d3.format("s"));
  this.xAxis = xAxis;
  var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
      .tickFormat(d3.format("s"));
  this.yAxis = yAxis;

  this.parent_div = parent_div;
  var parent = d3.select('#' + parent_div);
  var svg = parent.append('svg');

  svg.attr('width', '100%')
    .attr('height', '100%')
    .attr('viewBox', '0 0 ' + size + ' ' + size)
    .attr('preserveAspectRatio', 'xMidYMid meet')
  var plot_area = svg.append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
    .call(xAxis)
    .selectAll("text")
    .attr("y", 0)
    .attr("x", 9)
    .attr("dy", ".35em")
    .attr("transform", "rotate(90)")
    .style("text-anchor", "start");

  svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
    .call(yAxis);

  this.svg = svg;
  this.plot_area = plot_area;
  this.xScale = x;
  this.yScale = y;
  this.max_count = max_count;
  this.max_span = max_span;
  this.line_data = [];
  var data = this.prepareLine()
  this.addLine(data,this.name,this);
  this.line_data[0].line.classed('asm-reference-line',true).transition().duration(500).style('opacity',1)

  return this;
}

Assembly.prototype.addKey = function(assemblies) {
  var current = this;
  var plot_area = this.plot_area
  var group = plot_area.append('g').attr('class','asm-square-key');
  var height = assemblies.length * 25;
  var width = 200;
  group.attr('transform','translate(300,'+(430-height)+')')
  var rows = group.selectAll('g').data(assemblies);
  var rows_enter = rows.enter().append('g').attr('class',function(d,i){ var css = 'asm-square-key-row '; if (i == 0){css += 'asm-reference-key'} return css})
                        .attr('transform',function(d,i){return 'translate(0,'+(i*25)+')'})
  var rect = rows_enter.append('rect').attr('height',25).attr('width',150).attr('y',-12.5).style('fill','rgba(255,255,255,0.01)');
  rows_enter.append('text').attr('class',function(d){return 'asm-square-key-text '+d});
  rows.select('text').text(function(d){return d})
  rect.on('mouseover',function(d){
    //d3.select(this).style('fill','rgba(0,0,0,0.3)')
    plot_area.select('text.'+d).classed('asm-square-focus',true)
    plot_area.select('path.'+d).classed('asm-square-focus',true)
  })
  rect.on('click',function(d){
    //d3.select(this).style('fill','rgba(0,0,0,0.3)')
    var obj = findByValue(current.line_data,'name',d)
    current.zoomTo(obj)
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  rect.on('mouseout',function(d){
    //d3.select(this).style('fill','rgba(0,0,0,0.01)')
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  return this;
}

function findByValue(source, key, value) {
  for (var i = 0; i < source.length; i++) {
    if (source[i][key] === value) {
      return source[i];
    }
  }
}

Assembly.prototype.zoomTo = function(obj){
  var xScale = this.xScale;
  var yScale = this.yScale;
  xScale.domain([1,obj.count]).nice()
  this.max_count = obj.count;
  yScale.domain([1,obj.span]).nice()
  this.max_span = obj.span;
  this.svg.selectAll("g.y.axis").transition().duration(500)
      .call(this.yAxis);
  this.svg.selectAll("g.x.axis")
      .transition().duration(500).call(this.xAxis)
      .selectAll("text")
      .attr("y", 0)
      .attr("x", 9)
      .attr("dy", ".35em")
      .attr("transform", "rotate(90)")
      .style("text-anchor", "start");
  var line_data = this.line_data;
  var reference = this;
  line_data.forEach(function(line){
    reference.rescaleLine(line);
  })
}

Assembly.prototype.prepareLine = function() {
  var current = this;
  var line_data = [];
  current.npct_count.forEach(function(count,index){
    line_data[index] = {x:count,y:((index+1)/1000*current.assembly)}
  })
  return line_data;
}

Assembly.prototype.addLine = function(data,classname,assembly) {
  var xScale = this.xScale;
  var yScale = this.yScale;
  var plot_area = this.plot_area;
  var current = this;
  var rescale = 0;

  var lineFunction = d3.svg.line()
                            .x(function(d) { return xScale(d.x); })
                            .y(function(d) { return yScale(d.y); })
                            .interpolate("linear");
  this.lineFunction = lineFunction;
  var lineGraph = this.plot_area.append("path")
                              .attr("d", lineFunction(data))
                              .attr("class", 'asm-cumulative-line '+classname)
                              .attr("rel", classname)
                              .style('opacity',0)
  lineGraph.on('mouseover',function(){
    var d = d3.select(this).attr('rel')
    plot_area.select('text.'+d).classed('asm-square-focus',true)
    plot_area.select('path.'+d).classed('asm-square-focus',true)
  })
  lineGraph.on('click',function(){
    var d = d3.select(this).attr('rel')
    var obj = findByValue(current.line_data,'name',d)
    current.zoomTo(obj)
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  lineGraph.on('mouseout',function(){
    var d = d3.select(this).attr('rel')
    plot_area.select('text.'+d).classed('asm-square-focus',false)
    plot_area.select('path.'+d).classed('asm-square-focus',false)
  })
  this.line_data.push({name:classname,data:data,line:lineGraph,count:assembly.scaffold_count,span:assembly.assembly})

  if (assembly.scaffold_count > this.max_count){
    rescale = 1;
    xScale.domain([1,assembly.scaffold_count]).nice()
    this.max_count = assembly.scaffold_count;
  }
  if (assembly.assembly > this.max_span){
    rescale = 1
    yScale.domain([1,assembly.assembly]).nice()
    this.max_span = assembly.assembly;
  }
  if (rescale){
    this.svg.selectAll("g.y.axis").transition().duration(500)
        .call(this.yAxis);
    this.svg.selectAll("g.x.axis")
        .transition().duration(500).call(this.xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(90)")
        .style("text-anchor", "start");
    var line_data = this.line_data;
    var reference = this;
    line_data.forEach(function(line){
      reference.rescaleLine(line);
    })
  }
  else {
    lineGraph.transition().duration(500).style('opacity',1)
  }
}

Assembly.prototype.rescaleLine = function(line_data) {
  line_data.line.transition().duration(500).attr("d", this.lineFunction(line_data.data)).style('opacity',1)
}
<|endoftext|>


<commit_before>// Copyright 2012 Google Inc.  All Rights Reserved.
//
// 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 distrib-
// uted 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
// specific language governing permissions and limitations under the License.

/**
 * @fileoverview [MODULE: edit] A single-line text entry field.
 * @author kpy@google.com (Ka-Ping Yee)
 */
goog.provide('cm.TextEditor');

goog.require('cm.Editor');
goog.require('cm.ui');

/**
 * A single-line text input field.
 * @param {Element} parentElem The parent element in which to create the editor.
 * @param {string} id The element ID for the editor.
 * @param {Object.<{input_class: string}>} options Editor options:
 *     options.input_class: a CSS class for the input element.
 * @extends cm.Editor
 * @constructor
 */
cm.TextEditor = function(parentElem, id, options) {
  cm.Editor.call(this);

  /**
   * @type Element
   * @private
   */
  this.input_ = cm.ui.create('input',
      {'id': id, 'type': 'text',
       'class': options && options.input_class || null});
  parentElem.appendChild(this.input_);

  // When the user makes an edit in the UI, update the MVCObject property.
  cm.events.listen(
      this.input_, ['change', 'input', 'keyup', 'cut', 'paste'], function() {
    this.validate(this.input_.value);
  }, this);
};
goog.inherits(cm.TextEditor, cm.Editor);

/**
 * Validates the given user-supplied value for submission.
 * If acceptable, implementations must invoke this.setValid(...).
 * If validation fails, implementations must invoke this.setInvalid(message).
 * @param {string} value User-supplied value.
 */
cm.TextEditor.prototype.validate = function(value) {
  this.setValid(value.replace(/^\s+|\s+$/g, ''));
};

/** @override */
cm.TextEditor.prototype.updateUi = function(value) {
  this.input_.value = (value === null) ? '' : '' + value;
};
<commit_msg>Support placeholder text in text_editor ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=62145040<commit_after>// Copyright 2012 Google Inc.  All Rights Reserved.
//
// 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 distrib-
// uted 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
// specific language governing permissions and limitations under the License.

/**
 * @fileoverview [MODULE: edit] A single-line text entry field.
 * @author kpy@google.com (Ka-Ping Yee)
 */
goog.provide('cm.TextEditor');

goog.require('cm.Editor');
goog.require('cm.ui');

/**
 * A single-line text input field.
 * @param {Element} parentElem The parent element in which to create the editor.
 * @param {string} id The element ID for the editor.
 * @param {Object.<{input_class: string, placeholder: string}>} options
 *     Editor options:
 *     options.input_class: a CSS class for the input element.
 *     options.placeholder: placeholder text for the input element.
 * @extends cm.Editor
 * @constructor
 */
cm.TextEditor = function(parentElem, id, options) {
  cm.Editor.call(this);

  /**
   * @type Element
   * @private
   */
  this.input_ = cm.ui.create('input',
      {'id': id, 'type': 'text',
       'class': options && options.input_class || null,
       'placeholder': options && options.placeholder || ''});
  parentElem.appendChild(this.input_);

  // When the user makes an edit in the UI, update the MVCObject property.
  cm.events.listen(
      this.input_, ['change', 'input', 'keyup', 'cut', 'paste'], function() {
    this.validate(this.input_.value);
  }, this);
};
goog.inherits(cm.TextEditor, cm.Editor);

/**
 * Validates the given user-supplied value for submission.
 * If acceptable, implementations must invoke this.setValid(...).
 * If validation fails, implementations must invoke this.setInvalid(message).
 * @param {string} value User-supplied value.
 */
cm.TextEditor.prototype.validate = function(value) {
  this.setValid(value.replace(/^\s+|\s+$/g, ''));
};

/** @override */
cm.TextEditor.prototype.updateUi = function(value) {
  this.input_.value = (value === null) ? '' : '' + value;
};
<|endoftext|>


<commit_before>/*!
Deck JS - deck.hash - v1.0
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/

/*
This module adds deep linking to individual slides, enables internal links
to slides within decks, and updates the address bar with the hash as the user
moves through the deck. A permalink anchor is also updated. Standard themes
hide this link in browsers that support the History API, and show it for
those that do not. Slides that do not have an id are assigned one according to
the hashPrefix option.
*/
(function ($, deck, window, undefined) {
	var $d = $(document),
	$window = $(window),

	/* Collection of internal fragment links in the deck */
	$internals,

	/*
	Internal only function.  Given a string, extracts the id from the hash,
	matches it to the appropriate slide, and navigates there.
	*/
	goByHash = function(str) {
		var id = str.substr(str.indexOf("#") + 1),
		slides = $[deck]('getSlides');

		$.each(slides, function(i, $el) {
			if ($el.attr('id') === id) {
				$[deck]('go', i);
				return false;
			}
		});
	};

	/*
	Extends defaults/options.

	options.selectors.hashLink
		The element matching this selector has its href attribute updated to
		the hash of the current slide as the user navigates through the deck.

	options.hashPrefix
		Every slide that does not have an id is assigned one at initialization.
		Assigned ids take the form of hashPrefix + slideIndex, e.g., slide-0,
		slide-12, etc.
	*/
	$.extend(true, $[deck].defaults, {
		selectors: {
			hashLink: '.deck-permalink'
		},

		hashPrefix: 'slide-'
	});

	$d.bind('deck.init', function() {
		$internals = $();

		$.each($[deck]('getSlides'), function(i, $el) {
			var hash;

			/* Hand out ids to the unfortunate slides born without them */
			if (!$el.attr('id')) {
				$el.attr('id', $[deck]('getOptions').hashPrefix + i);
			}

			hash ='#' + $el.attr('id');

			/* Deep link to slides on init */
			if (hash === window.location.hash) {
				$[deck]('go', i);
			}

			/* Add internal links to this slide */
			$internals = $internals.add('a[href="' + hash + '"]');
		});

		if (!Modernizr.hashchange) {
			/* Set up internal links using click for the poor browsers
			without a hashchange event. */
			$internals.bind('click.deck', function(e) {
				goByHash($(this).attr('href'));
			});
		}
	})
	/* Update permalink and address bar on a slide change */
	.bind('deck.change', function(e, from, to) {
		var hash = '#' + $[deck]('getSlide', to).attr('id');

		$($[deck]('getOptions').selectors.hashLink).attr('href', hash);
		if (Modernizr.history) {
			window.history.replaceState({}, "", hash);
		}
	});

	/* Deals with internal links in modern browsers */
	$window.bind('hashchange.deck', function(e) {
		if (e.originalEvent.newURL) {
			goByHash(e.originalEvent.newURL);
		}
		else {
			goByHash(window.location.hash);
		}
	});
})(jQuery, 'deck', this);<commit_msg>#18: Add safety check for e.originalEvent inside hashchange<commit_after>/*!
Deck JS - deck.hash - v1.0
Copyright (c) 2011 Caleb Troughton
Dual licensed under the MIT license and GPL license.
https://github.com/imakewebthings/deck.js/blob/master/MIT-license.txt
https://github.com/imakewebthings/deck.js/blob/master/GPL-license.txt
*/

/*
This module adds deep linking to individual slides, enables internal links
to slides within decks, and updates the address bar with the hash as the user
moves through the deck. A permalink anchor is also updated. Standard themes
hide this link in browsers that support the History API, and show it for
those that do not. Slides that do not have an id are assigned one according to
the hashPrefix option.
*/
(function ($, deck, window, undefined) {
	var $d = $(document),
	$window = $(window),

	/* Collection of internal fragment links in the deck */
	$internals,

	/*
	Internal only function.  Given a string, extracts the id from the hash,
	matches it to the appropriate slide, and navigates there.
	*/
	goByHash = function(str) {
		var id = str.substr(str.indexOf("#") + 1),
		slides = $[deck]('getSlides');

		$.each(slides, function(i, $el) {
			if ($el.attr('id') === id) {
				$[deck]('go', i);
				return false;
			}
		});
	};

	/*
	Extends defaults/options.

	options.selectors.hashLink
		The element matching this selector has its href attribute updated to
		the hash of the current slide as the user navigates through the deck.

	options.hashPrefix
		Every slide that does not have an id is assigned one at initialization.
		Assigned ids take the form of hashPrefix + slideIndex, e.g., slide-0,
		slide-12, etc.
	*/
	$.extend(true, $[deck].defaults, {
		selectors: {
			hashLink: '.deck-permalink'
		},

		hashPrefix: 'slide-'
	});

	$d.bind('deck.init', function() {
		$internals = $();

		$.each($[deck]('getSlides'), function(i, $el) {
			var hash;

			/* Hand out ids to the unfortunate slides born without them */
			if (!$el.attr('id')) {
				$el.attr('id', $[deck]('getOptions').hashPrefix + i);
			}

			hash ='#' + $el.attr('id');

			/* Deep link to slides on init */
			if (hash === window.location.hash) {
				$[deck]('go', i);
			}

			/* Add internal links to this slide */
			$internals = $internals.add('a[href="' + hash + '"]');
		});

		if (!Modernizr.hashchange) {
			/* Set up internal links using click for the poor browsers
			without a hashchange event. */
			$internals.bind('click.deck', function(e) {
				goByHash($(this).attr('href'));
			});
		}
	})
	/* Update permalink and address bar on a slide change */
	.bind('deck.change', function(e, from, to) {
		var hash = '#' + $[deck]('getSlide', to).attr('id');

		$($[deck]('getOptions').selectors.hashLink).attr('href', hash);
		if (Modernizr.history) {
			window.history.replaceState({}, "", hash);
		}
	});

	/* Deals with internal links in modern browsers */
	$window.bind('hashchange.deck', function(e) {
		if (e.originalEvent && e.originalEvent.newURL) {
			goByHash(e.originalEvent.newURL);
		}
		else {
			goByHash(window.location.hash);
		}
	});
})(jQuery, 'deck', this);<|endoftext|>