<commit_before>badgeSetup = function () {
    if (false && repoEndpoint().contains("localhost"))
        error("Endpoint Configuration is not set.", 500);

    if (EcRepository.repos == null || EcRepository.repos.length == 0) {
        //Permit find to work.
        var repo = new EcRepository();
        repo.selectedServer = repoEndpoint();
    }
    var identity = new EcIdentity();
    identity.ppk = EcPpk.fromPem(openbadgesPpk());
    identity.displayName = "OpenBadges Internal Identity";
    EcIdentityManager.addIdentity(identity);

}
badgeGetPerson = function (fingerprint) {
    var person = EcRepository.getBlocking(repoEndpoint() + "data/" + fingerprint);

    if (person.isAny(new EcEncryptedValue().getTypes())) {
        var v = new EcEncryptedValue();
        v.copyFrom(person);
        person = v.decryptIntoObject();
    }
    return person;
}

badgeCryptographicKey = function (fingerprint) {
    badgeSetup.call(this);
    if (fingerprint == null)
        fingerprint = this.params.urlRemainder.replace("/", "");
    var person = badgeGetPerson.call(this, fingerprint);
    if (person == null)
        error("Insufficient data available to generate cryptographic key.", 405);

    return JSON.stringify({
        "@context": "https://w3id.org/openbadges/v2",
        id: repoEndpoint() + "badge/cryptographicKey/" + fingerprint,
        type: "CryptographicKey",
        owner: repoEndpoint() + "data/" + fingerprint,
        publicKeyPem: person.publicKey
    });
};

badgeProfile = function (fingerprint) {
    badgeSetup.call(this);
    if (fingerprint == null)
        fingerprint = this.params.urlRemainder.replace("/", "");
    var person = badgeGetPerson.call(this, fingerprint);
    if (person == null)
        error("Insufficient data available to generate issuer.", 405);

    return JSON.stringify({
        "@context": "https://w3id.org/openbadges/v2",
        id: repoEndpoint() + "badge/profile/" + fingerprint,
        type: "Profile",
        name: person.name,
        url: person.url,
        telephone: person.telephone,
        description: person.description,
        image: person.image,
        email: person.email,
        publicKey: repoEndpoint() + "badge/cryptographicKey/" + fingerprint,
        verification: {
            type: "hosted"
        }
    })
};

badgeSubject = function (fingerprint) {
    badgeSetup.call(this);
    if (fingerprint == null)
        fingerprint = this.params.urlRemainder.replace("/", "");
    var person = badgeGetPerson.call(this, fingerprint);
    if (person == null)
        error("Insufficient data available to generate identityObject.", 405);

    if (person.email != null) {
        var sha = forge.md.sha256.create();
        var salt = EcAes.newIv(16);
        sha.update(person.email + salt);
        var hashed = "sha256$" + sha.digest().toHex();
        return JSON.stringify({
            type: "email",
            identity: hashed,
            salt: salt,
            hashed: true
        })
    }
    if (person.url != null) {
        var sha = forge.md.sha256.create();
        var salt = EcAes.newIv(16);
        sha.update(person.url + salt);
        var hashed = "sha256$" + sha.digest().toHex();
        return JSON.stringify({
            type: "url",
            identity: hashed,
            salt: salt,
            hashed: true
        })
    }
    if (person.telephone != null) {
        var sha = forge.md.sha256.create();
        var salt = EcAes.newIv(16);
        sha.update(person.telephone + salt);
        var hashed = "sha256$" + sha.digest().toHex();
        return JSON.stringify({
            type: "telephone",
            identity: hashed,
            salt: salt,
            hashed: true
        })
    }
};

badgeClass = function (competencyId, fingerprint, assertion) {
    badgeSetup.call(this);

    var competency = null;
    if (competencyId != null)
        competency = EcRepository.getBlocking(competencyId);
    else {
        var query = queryParse.call(this);
        debug(query);
        competency = EcCompetency.getBlocking(repoEndpoint() + "data/" + query.type);
        fingerprint = query.id;
    }

    var competencyAlignment = new AlignmentObject();
    competencyAlignment.alignmentType = "requires";
    competencyAlignment.targetUrl = competency.id;
    competencyAlignment.targetName = competency.name;
    if (assertion != null)
        competencyAlignment.educationalFramework = assertion.framework;

    competencyId = repoEndpoint() + "badge/class/" + competency.getGuid() + "/" + fingerprint;
    if (EcRepository.shouldTryUrl(competency.id) == false) {
        var md5 = forge.md.md5.create();
        md5.update(competency.id);
        competencyId = repoEndpoint() + "badge/class/" + md5.digest().toHex() + "/" + fingerprint;
    }

    return JSON.stringify({
        "@context": "https://w3id.org/openbadges/v2",
        id: competencyId,
        type: "BadgeClass",
        issuer: repoEndpoint() + "badge/profile/" + fingerprint,
        name: competency.name,
        description: competency.description,
        image: competency.image,
        alignmentObject: [competencyAlignment]
    })
};

badgeAssertion = function () {
    badgeSetup.call(this);

    var query = queryParse.call(this);
    var assertion = EcRepository.getBlocking(repoEndpoint() + "data/" + query.id);
    if (assertion == null)
        error("Assertion not found.", 404);
    var a = new EcAssertion();
    a.copyFrom(assertion);

    var subject = a.getSubject();
    if (subject == null)
        error("Not authorized to perform this operation. Add the key found at /badge/pk to the assertion's @readers.", 401);
    var agent = a.getAgent();
    if (agent == null)
        error("Not authorized to perform this operation. Add the key found at /badge/pk to the assertion's @readers.", 401);
    subject = JSON.parse(badgeSubject(subject.fingerprint()));
    if (subject == null)
        error("Insufficient data available to generate badge recipient object.", 405);
    var clazz = JSON.parse(badgeClass(a.competency, agent.fingerprint(), a));
    if (clazz == null)
        error("Insufficient data available to generate badge class object.", 405);
    agent = JSON.parse(badgeProfile(agent.fingerprint()));
    if (agent == null)
        error("Insufficient data available to generate badge issuer object.", 405);

    var evidences = [];
    for (var i = 0; i < a.getEvidenceCount(); i++)
        evidences.push(a.getEvidence(i));
    var result = {
        "@context": "https://w3id.org/openbadges/v2",
        "id": repoEndpoint() + "badge/assertion/" + query.id,
        "type": "Assertion",
        "recipient": subject,
        "evidence": evidences,
        "issuedOn": new Date(a.getAssertionDate()).toISOString(),
        "expires": new Date(a.getExpirationDate()).toISOString(),
        "badge": clazz.id,
        "verification": {
            "type": "hosted"
        }
    };
    //    result = bakeImage(result);
    return JSON.stringify(result);
}

bindWebService("/badge/profile", badgeProfile);
bindWebService("/badge/cryptographicKey", badgeCryptographicKey);
bindWebService("/badge/class", badgeClass);
bindWebService("/badge/assertion", badgeAssertion);
<commit_msg>Passed validation.<commit_after>badgeSetup = function () {
    if (false && repoEndpoint().contains("localhost"))
        error("Endpoint Configuration is not set.", 500);

    if (EcRepository.repos == null || EcRepository.repos.length == 0) {
        //Permit find to work.
        var repo = new EcRepository();
        repo.selectedServer = repoEndpoint();
    }
    var identity = new EcIdentity();
    identity.ppk = EcPpk.fromPem(openbadgesPpk());
    identity.displayName = "OpenBadges Internal Identity";
    EcIdentityManager.addIdentity(identity);

}
badgeGetPerson = function (fingerprint) {
    var person = EcRepository.getBlocking(repoEndpoint() + "data/" + fingerprint);

    if (person.isAny(new EcEncryptedValue().getTypes())) {
        var v = new EcEncryptedValue();
        v.copyFrom(person);
        person = v.decryptIntoObject();
    }
    return person;
}
badgeCryptographicKey = function (fingerprint) {
    badgeSetup.call(this);
    if (fingerprint == null)
        fingerprint = this.params.urlRemainder.replace("/", "");
    var person = badgeGetPerson.call(this, fingerprint);
    if (person == null)
        error("Insufficient data available to generate cryptographic key.", 405);

    return JSON.stringify({
        "@context": "https://w3id.org/openbadges/v2",
        id: repoEndpoint() + "badge/cryptographicKey/" + fingerprint,
        type: "CryptographicKey",
        owner: repoEndpoint() + "data/" + fingerprint,
        publicKeyPem: person.publicKey
    });
};
badgeProfile = function (fingerprint) {
    badgeSetup.call(this);
    if (fingerprint == null)
        fingerprint = this.params.urlRemainder.replace("/", "");
    var person = badgeGetPerson.call(this, fingerprint);
    if (person == null)
        error("Insufficient data available to generate issuer.", 405);

    return JSON.stringify({
        "@context": "https://w3id.org/openbadges/v2",
        id: repoEndpoint() + "badge/profile/" + fingerprint,
        type: "Profile",
        name: person.name,
        url: person.url,
        telephone: person.telephone,
        description: person.description,
        image: "https://api.badgr.io/public/badges/X7kb4H72TXiMoYN_kJNdEQ/image",
        email: person.email,
        publicKey: repoEndpoint() + "badge/cryptographicKey/" + fingerprint,
        verification: {
            type: "hosted"
        }
    })
};
badgeSubject = function (fingerprint) {
    badgeSetup.call(this);
    if (fingerprint == null)
        fingerprint = this.params.urlRemainder.replace("/", "");
    var person = badgeGetPerson.call(this, fingerprint);
    if (person == null)
        error("Insufficient data available to generate identityObject.", 405);

    if (person.email != null) {
        var sha = forge.md.sha256.create();
        var salt = EcAes.newIv(16);
        sha.update(person.email + salt);
        var hashed = "sha256$" + sha.digest().toHex();
        return JSON.stringify({
            type: "email",
            identity: hashed,
            salt: salt,
            hashed: true
        })
    }
    if (person.url != null) {
        var sha = forge.md.sha256.create();
        var salt = EcAes.newIv(16);
        sha.update(person.url + salt);
        var hashed = "sha256$" + sha.digest().toHex();
        return JSON.stringify({
            type: "url",
            identity: hashed,
            salt: salt,
            hashed: true
        })
    }
    if (person.telephone != null) {
        var sha = forge.md.sha256.create();
        var salt = EcAes.newIv(16);
        sha.update(person.telephone + salt);
        var hashed = "sha256$" + sha.digest().toHex();
        return JSON.stringify({
            type: "telephone",
            identity: hashed,
            salt: salt,
            hashed: true
        })
    }
};
badgeClass = function (competencyId, fingerprint, assertion) {
    badgeSetup.call(this);

    var competency = null;
    if (competencyId != null)
        competency = EcRepository.getBlocking(competencyId);
    else {
        var query = queryParse.call(this);
        debug(query);
        competency = EcCompetency.getBlocking(repoEndpoint() + "data/" + query.type);
        fingerprint = query.id;
    }

    var competencyAlignment = new AlignmentObject();
    competencyAlignment.alignmentType = "requires";
    competencyAlignment.targetUrl = competency.id;
    competencyAlignment.targetName = competency.name;
    if (assertion != null)
        competencyAlignment.educationalFramework = assertion.framework;

    competencyId = repoEndpoint() + "badge/class/" + competency.getGuid() + "/" + fingerprint;
    if (EcRepository.shouldTryUrl(competency.id) == false) {
        var md5 = forge.md.md5.create();
        md5.update(competency.id);
        competencyId = repoEndpoint() + "badge/class/" + md5.digest().toHex() + "/" + fingerprint;
    }

    var criteria = {type:"Criteria"};
    if (competency.description != null)
        criteria.narrative = competency.description;
    else
        criteria.narrative = competency.getName();
    return JSON.stringify({
        "@context": "https://w3id.org/openbadges/v2",
        id: competencyId,
        type: "BadgeClass",
        issuer: repoEndpoint() + "badge/profile/" + fingerprint,
        name: competency.name,
        criteria: criteria,
        description: competency.description,
        image: "https://api.badgr.io/public/badges/X7kb4H72TXiMoYN_kJNdEQ/image",
        alignment: [competencyAlignment]
    });
};
badgeAssertion = function () {
    badgeSetup.call(this);

    var query = queryParse.call(this);
    var assertion = EcRepository.getBlocking(repoEndpoint() + "data/" + query.id);
    if (assertion == null)
        error("Assertion not found.", 404);
    var a = new EcAssertion();
    a.copyFrom(assertion);

    var subject = a.getSubject();
    if (subject == null)
        error("Not authorized to perform this operation. Add the key found at /badge/pk to the assertion's @readers.", 401);
    var agent = a.getAgent();
    if (agent == null)
        error("Not authorized to perform this operation. Add the key found at /badge/pk to the assertion's @readers.", 401);
    subject = JSON.parse(badgeSubject(subject.fingerprint()));
    if (subject == null)
        error("Insufficient data available to generate badge recipient object.", 405);
    var clazz = JSON.parse(badgeClass(a.competency, agent.fingerprint(), a));
    if (clazz == null)
        error("Insufficient data available to generate badge class object.", 405);
    agent = JSON.parse(badgeProfile(agent.fingerprint()));
    if (agent == null)
        error("Insufficient data available to generate badge issuer object.", 405);

    var evidences = [];
    for (var i = 0; i < a.getEvidenceCount(); i++)
    {
        var evidence = a.getEvidence(i);
        if (evidence.toLowerCase().startsWith("http"))
                evidences.push(evidence);
        else if (EcObject.isObject(evidence))
                evidences.push(evidence);
        else
                evidences.push({type:"Evidence",narrative:evidence});
    }
    if (evidences.length == 1)
        evidences = evidences[0];
    var result = {
        "@context": "https://w3id.org/openbadges/v2",
        "id": repoEndpoint() + "badge/assertion/" + query.id,
        "type":"Assertion",
        "recipient": subject,
        "evidence": evidences,
"narrative": "This individual was claimed to have demonstrated this competency.",
        "image": "https://api.badgr.io/public/badges/X7kb4H72TXiMoYN_kJNdEQ/image",
        "issuedOn": new Date(a.getAssertionDate()).toISOString(),
        "expires": new Date(a.getExpirationDate()).toISOString(),
        "badge": clazz.id,
        "verification": {
            "type": "HostedBadge"
        }
    };
    //    result = bakeImage(result);
    return JSON.stringify(result);
}

bindWebService("/badge/profile", badgeProfile);
bindWebService("/badge/cryptographicKey", badgeCryptographicKey);
bindWebService("/badge/class", badgeClass);
bindWebService("/badge/assertion", badgeAssertion);

<|endoftext|>


<commit_before>"use strict";
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var curator = require('./curator');
var RestMixin = require('./rest').RestMixin;
var form = require('../libs/bootstrap/form');
var panel = require('../libs/bootstrap/panel');

var RecordHeader = curator.RecordHeader;
var PmidSummary = curator.PmidSummary;
var queryKeyValue = globals.queryKeyValue;
var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Panel = panel.Panel;

var ExperimentalSubmit = React.createClass({
    mixins: [FormMixin, RestMixin],

    // Keeps track of values from the query string
    queryValues: {},

    getInitialState: function() {
        return {
            gdm: null, // GDM object given in query string
            experimental: null, // Experimental object given in query string
            annotation: null, // Annotation object given in query string
        };
    },

    // Load objects from query string into the state variables. Must have already parsed the query string
    // and set the queryValues property of this React class.
    loadData: function() {
        var gdmUuid = this.queryValues.gdmUuid;
        var experimentalUuid = this.queryValues.experimentalUuid;
        var annotationUuid = this.queryValues.annotationUuid;

        // Make an array of URIs to query the database. Don't include any that didn't include a query string.
        var uris = _.compact([
            gdmUuid ? '/gdm/' + gdmUuid : '',
            experimentalUuid ? '/experimental/' + experimentalUuid : '',
            annotationUuid ? '/evidence/' + annotationUuid : ''
        ]);

        // With all given query string variables, get the corresponding objects from the DB.
        this.getRestDatas(
            uris
        ).then(datas => {
            // See what we got back so we can build an object to copy in this React object's state to rerender the page.
            var stateObj = {};
            datas.forEach(function(data) {
                switch(data['@type'][0]) {
                    case 'gdm':
                        stateObj.gdm = data;
                        break;

                    case 'experimental':
                        stateObj.experimental = data;
                        break;

                    case 'annotation':
                        stateObj.annotation = data;
                        break;

                    default:
                        break;
                }
            });

            // Set all the state variables we've collected
            this.setState(stateObj);

            // Not passing data to anyone; just resolve with an empty promise.
            return Promise.resolve();
        }).catch(function(e) {
            console.log('OBJECT LOAD ERROR: %s — %s', e.statusText, e.url);
        });
    },

    // After the Experimental Curation page component mounts, grab the GDM, experimental, and annotation UUIDs (as many as given)
    // from the query string and retrieve the corresponding objects from the DB, if they exist. Note, we have to do this after
    // the component mounts because AJAX DB queries can't be done from unmounted components.
    componentDidMount: function() {
        // Get the 'evidence', 'gdm', and 'experimental' UUIDs from the query string and save them locally.
        this.loadData();
    },

    render: function() {
        var gdm = this.state.gdm;
        var experimental = this.state.experimental;
        var annotation = this.state.annotation;

        // Get the query strings. Have to do this now so we know whether to render the form or not. The form
        // uses React controlled inputs, so we can only render them the first time if we already have the
        // family object read in.
        this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href);
        this.queryValues.experimentalUuid = queryKeyValue('experimental', this.props.href);
        this.queryValues.annotationUuid = queryKeyValue('evidence', this.props.href);

        // Build the link to go back and edit the newly created experimental page
        var editExperimentalLink = (gdm && experimental && annotation) ? '/experimental-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid + '&experimental=' + experimental.uuid : '';

        return (

                <RecordHeader gdm={gdm} omimId={gdm && gdm.omimId} />

                    {experimental ?

{experimental.evidenceType}
Experimental Data Information: {experimental.label} View Edit

                    : null}
                    {annotation && annotation.article ?

                            <PmidSummary article={annotation.article} displayJournal />

                    : null}

                            <Panel panelClassName="submit-results-panel" panelBodyClassName="bg-info">

                                    Your Experimental Data has been added!

                            </Panel>
                            { experimental && annotation && annotation.article ?
                                <Panel panelClassName="submit-results-panel submit-results-response">

                                                    Add another Experimental Data entry

                                                    Return to Record Curation page

                                </Panel>
                            : null }

        );
    }
});

globals.curator_page.register(ExperimentalSubmit, 'curator_page', 'experimental-submit');
<commit_msg>increase width of experimental-submit<commit_after>"use strict";
var React = require('react');
var _ = require('underscore');
var globals = require('./globals');
var curator = require('./curator');
var RestMixin = require('./rest').RestMixin;
var form = require('../libs/bootstrap/form');
var panel = require('../libs/bootstrap/panel');

var RecordHeader = curator.RecordHeader;
var PmidSummary = curator.PmidSummary;
var queryKeyValue = globals.queryKeyValue;
var Form = form.Form;
var FormMixin = form.FormMixin;
var Input = form.Input;
var Panel = panel.Panel;

var ExperimentalSubmit = React.createClass({
    mixins: [FormMixin, RestMixin],

    // Keeps track of values from the query string
    queryValues: {},

    getInitialState: function() {
        return {
            gdm: null, // GDM object given in query string
            experimental: null, // Experimental object given in query string
            annotation: null, // Annotation object given in query string
        };
    },

    // Load objects from query string into the state variables. Must have already parsed the query string
    // and set the queryValues property of this React class.
    loadData: function() {
        var gdmUuid = this.queryValues.gdmUuid;
        var experimentalUuid = this.queryValues.experimentalUuid;
        var annotationUuid = this.queryValues.annotationUuid;

        // Make an array of URIs to query the database. Don't include any that didn't include a query string.
        var uris = _.compact([
            gdmUuid ? '/gdm/' + gdmUuid : '',
            experimentalUuid ? '/experimental/' + experimentalUuid : '',
            annotationUuid ? '/evidence/' + annotationUuid : ''
        ]);

        // With all given query string variables, get the corresponding objects from the DB.
        this.getRestDatas(
            uris
        ).then(datas => {
            // See what we got back so we can build an object to copy in this React object's state to rerender the page.
            var stateObj = {};
            datas.forEach(function(data) {
                switch(data['@type'][0]) {
                    case 'gdm':
                        stateObj.gdm = data;
                        break;

                    case 'experimental':
                        stateObj.experimental = data;
                        break;

                    case 'annotation':
                        stateObj.annotation = data;
                        break;

                    default:
                        break;
                }
            });

            // Set all the state variables we've collected
            this.setState(stateObj);

            // Not passing data to anyone; just resolve with an empty promise.
            return Promise.resolve();
        }).catch(function(e) {
            console.log('OBJECT LOAD ERROR: %s — %s', e.statusText, e.url);
        });
    },

    // After the Experimental Curation page component mounts, grab the GDM, experimental, and annotation UUIDs (as many as given)
    // from the query string and retrieve the corresponding objects from the DB, if they exist. Note, we have to do this after
    // the component mounts because AJAX DB queries can't be done from unmounted components.
    componentDidMount: function() {
        // Get the 'evidence', 'gdm', and 'experimental' UUIDs from the query string and save them locally.
        this.loadData();
    },

    render: function() {
        var gdm = this.state.gdm;
        var experimental = this.state.experimental;
        var annotation = this.state.annotation;

        // Get the query strings. Have to do this now so we know whether to render the form or not. The form
        // uses React controlled inputs, so we can only render them the first time if we already have the
        // family object read in.
        this.queryValues.gdmUuid = queryKeyValue('gdm', this.props.href);
        this.queryValues.experimentalUuid = queryKeyValue('experimental', this.props.href);
        this.queryValues.annotationUuid = queryKeyValue('evidence', this.props.href);

        // Build the link to go back and edit the newly created experimental page
        var editExperimentalLink = (gdm && experimental && annotation) ? '/experimental-curation/?gdm=' + gdm.uuid + '&evidence=' + annotation.uuid + '&experimental=' + experimental.uuid : '';

        return (

                <RecordHeader gdm={gdm} omimId={gdm && gdm.omimId} />

                    {experimental ?

{experimental.evidenceType}
Experimental Data Information: {experimental.label} View Edit

                    : null}
                    {annotation && annotation.article ?

                            <PmidSummary article={annotation.article} displayJournal />

                    : null}

                            <Panel panelClassName="submit-results-panel" panelBodyClassName="bg-info">

                                    Your Experimental Data has been added!

                            </Panel>
                            { experimental && annotation && annotation.article ?
                                <Panel panelClassName="submit-results-panel submit-results-response">

                                                    Add another Experimental Data entry

                                                    Return to Record Curation page

                                </Panel>
                            : null }

        );
    }
});

globals.curator_page.register(ExperimentalSubmit, 'curator_page', 'experimental-submit');
<|endoftext|>


<commit_before>var sum = 10 + 10; //make this equal to 20 by changing the 0 into the appropriate number.
console.log(sum);

var difference = 45 - 33; //make this equal to 12 by changing the 0 into the appropriate number.
console.log(difference);

var product = 8 * 10; //make this equal to 80 by changing the 0 into the appropriate number.
console.log(product);

var quotient = 66 / 33; //make this equal to 2 by changing the 0 into the appropriate number.
console.log(quotient);

// Create a number with a decimal point here called myDecimal
var myDecimal = 12.12;
console.log(myDecimal);

var quotient = 4.4 / 2.0; // equals 2.2
var product = 2.0 * 2.5; // equals 5.0
console.log(product);

// A new array called myArray that contains both a string and a number
var myArray = ["a string", 12];
console.log(myArray);

// A nested array called myArray2.
var myArray2 = [["inception", "array"], 12];
console.log(myArray2);

// A variable called myData set iequal to the first value of myArray3.
var myArray3 = [1,2,3];
// Only change code below this line.
var myData = myArray3[0];
console.log(myData);

// Modify the data stored at index 0 of myArray to the value of 3.
var myArray = [1,2,3];
myArray[0] = 3;
console.log(myArray);

// Used the .pop() function to remove the last item from myArray.
var myArray = ["John", 23, ["cat", 2]];

var removed = myArray.pop(); // This should be ["cat", 2] and myArray should now be ["John", 23]
console.log(removed);

// Takes the myArray array and push() this value to the end of it: ["dog", 3].
var myArray = ["John", 23, ["cat", 2]];
myArray.pop();
//Add a ["dog", 3] to the end of myArray using push()
// Only change code below this line.
myArray.push(["dog", 3]);
console.log(myArray);

// Takes the myArray array and shift() the first value off of it.
var myArray = ["John", 23, ["dog", 3]];
var myRemoved = myArray.shift(); // This should be ["John"] and myArray should now be [23, ["dog", 3]]
console.log(myArray);
<commit_msg>140. Manipulate Arrays With unshift<commit_after>var sum = 10 + 10; //make this equal to 20 by changing the 0 into the appropriate number.
console.log(sum);

var difference = 45 - 33; //make this equal to 12 by changing the 0 into the appropriate number.
console.log(difference);

var product = 8 * 10; //make this equal to 80 by changing the 0 into the appropriate number.
console.log(product);

var quotient = 66 / 33; //make this equal to 2 by changing the 0 into the appropriate number.
console.log(quotient);

// Create a number with a decimal point here called myDecimal
var myDecimal = 12.12;
console.log(myDecimal);

var quotient = 4.4 / 2.0; // equals 2.2
var product = 2.0 * 2.5; // equals 5.0
console.log(product);

// A new array called myArray that contains both a string and a number
var myArray = ["a string", 12];
console.log(myArray);

// A nested array called myArray2.
var myArray2 = [["inception", "array"], 12];
console.log(myArray2);

// A variable called myData set iequal to the first value of myArray3.
var myArray3 = [1,2,3];
// Only change code below this line.
var myData = myArray3[0];
console.log(myData);

// Modify the data stored at index 0 of myArray to the value of 3.
var myArray = [1,2,3];
myArray[0] = 3;
console.log(myArray);

// Used the .pop() function to remove the last item from myArray.
var myArray = ["John", 23, ["cat", 2]];

var removed = myArray.pop(); // This should be ["cat", 2] and myArray should now be ["John", 23]
console.log(removed);

// Takes the myArray array and push() this value to the end of it: ["dog", 3].
var myArray = ["John", 23, ["cat", 2]];
myArray.pop();
//Add a ["dog", 3] to the end of myArray using push()
// Only change code below this line.
myArray.push(["dog", 3]);
console.log(myArray);

// Takes the myArray array and shift() the first value off of it.
var myArray = ["John", 23, ["dog", 3]];
var myRemoved = myArray.shift(); // This should be ["John"] and myArray should now be [23, ["dog", 3]]
console.log(myArray);

var myArray = ["John", 23, ["dog", 3]];
myArray.shift();

// Add "Paul" to the start of myArray
myArray.unshift("Paul");
console.log(myArray);<|endoftext|>


<commit_before>//http://chimera.labs.oreilly.com/books/1230000000345/index.html

(function(){
  var w = 1000;
  var h = 600;

  var svg = d3.select("div")
    .append("svg")
    .attr({
      width: w,
      height: h
    });

  d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function(error, data) {
    if(error) {
      console.log(error);
      return;
    } else {
      console.log(data);
      ds = data;
    }

    //buildLine();
  });
})();<commit_msg>+ scales<commit_after>//http://chimera.labs.oreilly.com/books/1230000000345/index.html

(function(){
  var w = 1000;
  var h = 600;

  var svg = d3.select("div")
    .append("svg")
    .attr({
      width: w,
      height: h
    });

  d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function(error, data) {
    if(error) {
      console.log(error);
      return;
    } else {
      console.log(data);
      var dataSet = data.data;
      var minValue = 0;
      var maxValue = dataSet[0][1];
      var minYear = new Date(data.from_date).getYear() + 1900;
      var maxYear = new Date(data.to_date).getYear() + 1900;

      dataSet.forEach(function(item) {
        var value = item[1];
        maxValue = value > maxValue  ? value : maxValue;
      });

      /* console.log(minValue)
      console.log(maxValue)

      console.log(minYear)
      console.log(maxYear) */

      var x = d3.scale.linear()
        .range([maxValue, minValue]);

      var y = d3.scale.linear()
        .range([maxYear, minYear]);

      var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

      var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");
    }

    //buildLine();
  });
})();<|endoftext|>


<commit_before>/**@license
 * Copyright (c) 2013-2016, XorfacX - FairyDwarves
 * Please report to LICENSE.md file.
 */

/**
* Main file
*/
//"use strict"; //enable strict mode

define([
    'dojo/_base/lang',
    'dojo/_base/declare',
    "dojo/on",
    "dojo/touch",
    "dojo/ready",
    "dojo/Deferred",
    "app/system",
    "app/appM",
    "app/appV",
    "app/Environment"
], function (lang, declare, on, touch, ready, Deferred, system, model, view) {

    /** @private */
    var context, screenTO = 2000; //screenTO == sum of transition duration defined inside css for #title and #logo

    /**
     * Create the whole app view
     * This is the controller part
     */
    return declare(null, {
        /**
         * @constructor
         */
        constructor: function () {
            context = this; //need to keep track inside "on" and "require" calls if we don't want to (or can't) use lang.hitch

            var forcedNode = (location.search.match(/n=(\S+)/) ? RegExp.$1 : undefined); //"n", node parameter

            //set AppEnv
            setEnvironment();
            system.LSKey = AppEnv.LSKey;

            //create the gloabal app Deferred
            window.appDeferred = new Deferred();

            //create the model
            this.model = new model();

            //create the default view empty (can't be populated until appDeferred is resolved)
            var aV = this.view = new view();

            //wait for dom ready
            ready(function () {
                if (typeof forcedNode == "undefined") {
                    aV.showTitle("My App Title".replace(/_/gi, " ").replace(/ /g, "
")); //replace potential underscore with space than spaces with
 tag

                    var onSig = on.once(aV.getRawView(), "click", function (e) {
                        context._Title2Logo(aV, to);
                    });

                    var to = setTimeout(function () {
                        context._Title2Logo(aV, onSig); //CANT use on.emit ...
                    }, screenTO);
                } else { //to display directly a specific node
                    this._launch(aV, forcedNode);
                }
            }); //ready
        }, //constructor

        model: undefined,
        view: undefined,

        /**
         * Transition from Title to Logo screen
         *
         * @private
         */
        _Title2Logo: function (aV, _signal) {
            if (_signal) {
                if (typeof _signal.remove == "function") { //remove event if called through dojo.on event
                    _signal.remove();
                } else {
                    clearTimeout(_signal); //clearTimeout if called through setTimeout
                }
            }

            aV.hideTitle().showLogo();

            var onSig = on.once(aV.getRawView(), "click", function (e) {
                context._Logo2Launch(aV, to);
            });

            var to = setTimeout(function () {
                context._Logo2Launch(aV, onSig);
            }, screenTO);
        },

        /**
         * Transition from Logo to Launch screen
         *
         * @private
         */
        _Logo2Launch: function (aV, _signal) {
            if (_signal) {
                if (typeof _signal.remove == "function") { //remove event if called through setTimeout
                    _signal.remove();
                } else {
                    clearTimeout(_signal); //cleartimeout if called through on event
                }
            }

            context._launch(aV);
        },

        /**
         * Launch the view
         * @private
         */
        _launch: function (aV, node) {
            window.appDeferred.then( //waiting for whatever we want to preload
                function (deferredRes) { //when wating is over call this function
                    console.log(deferredRes);

                    //init sound
                    window.appSound = new AppEnv.platformSound();
                    AppEnv.platformSound = undefined, delete AppEnv.platformSound; //clean
                    window.appSound.init(AppEnv.LSKey);
                    window.appSound.setMusicMute(); //toggle the music ON if set by the option or if we need to set default

                    //context.setup.sound.setMute("music");

                    aV.hideLogo();
                    context.reset();
                }
            );

            if (AppEnv.platform != 'android') {
                window.appDeferred.resolve("Loading successful"); //TOSET: proper location of this code when all you want to preload is done
            }
        },

        /**
         * Reset the displayed view
         *
         * @param nId {string}, node id to display
         *
         * @return {!object} this, for chaining
         */
        reset: function (nId) {
            //TOSET: APP CODE GOES HERE

            this.view.reset();
            on(document, touch.release, lang.hitch(this, function (event) {
                var res = "App model says: " + this.model.get() + ". SFX is played";
                window.appSound.playSFX("click");
                var int1 = setInterval(function () {
                    window.appSound.playSFX("click");
                }, 750);
                var int2 = setInterval(function () {
                    window.appSound.playSFX("click");
                }, 500);
                setTimeout(function () {
                    clearInterval(int1), clearInterval(int2);
                }, 7000);
                console.log(res);
                this.view.display(res);
            }));
            on(document, "backbutton", lang.hitch(this, function (event) {
                var res = "back btn pressed";
                console.log(res);
                this.view.display(res);
            }));
        }
    });  //declare
});     //define

<commit_msg>remove "context" usage<commit_after>/**@license
 * Copyright (c) 2013-2016, XorfacX - FairyDwarves
 * Please report to LICENSE.md file.
 */

/**
* Main file
*/
//"use strict"; //enable strict mode

define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    "dojo/on",
    "dojo/touch",
    "dojo/ready",
    "dojo/Deferred",
    "app/system",
    "app/appM",
    "app/appV",
    "app/Environment"
], function (declare, lang, on, touch, ready, Deferred, system, model, view) {

    /**
     * Create the whole app view
     * This is the controller part
     */
    return declare(null, {
        /**
         * @constructor
         */
        constructor: function () {

            var forcedNode = (location.search.match(/n=(\S+)/) ? RegExp.$1 : undefined); //"n", node parameter

            //set AppEnv
            setEnvironment();
            system.LSKey = AppEnv.LSKey;

            //create the gloabal app Deferred
            window.appDeferred = new Deferred();

            //create the model
            this.model = new model();

            //create the default view empty (can't be populated until appDeferred is resolved)
            var aV = this.view = new view();

            //wait for dom ready
            ready(lang.hitch(this, function () {
                if (typeof forcedNode == "undefined") {
                    aV.showTitle("My App Title".replace(/_/gi, " ").replace(/ /g, "
")); //replace potential underscore with space than spaces with
 tag

                    var onSig = on.once(aV.getRawView(), "click", lang.hitch(this, function (e) {
                        this._Title2Logo(aV, to);
                    }));

                    var to = setTimeout(lang.hitch(this, function () {
                        this._Title2Logo(aV, onSig); //CANT use on.emit ...
                    }), this.screenTO);
                } else { //to display directly a specific node
                    this._launch(aV, forcedNode);
                }
            })); //ready
        }, //constructor

        model: undefined,
        view: undefined,

        screenTO: 2000, //screenTO == sum of transition duration defined inside css for #title and #logo

        /**
         * Transition from Title to Logo screen
         *
         * @private
         */
        _Title2Logo: function (aV, _signal) {
            if (_signal) {
                if (typeof _signal.remove == "function") { //remove event if called through dojo.on event
                    _signal.remove();
                } else {
                    clearTimeout(_signal); //clearTimeout if called through setTimeout
                }
            }

            aV.hideTitle().showLogo();

            var onSig = on.once(aV.getRawView(), "click", lang.hitch(this, function (e) {
                this._Logo2Launch(aV, to);
            }));

            var to = setTimeout(lang.hitch(this, function () {
                this._Logo2Launch(aV, onSig);
            }), this.screenTO);
        },

        /**
         * Transition from Logo to Launch screen
         *
         * @private
         */
        _Logo2Launch: function (aV, _signal) {
            if (_signal) {
                if (typeof _signal.remove == "function") { //remove event if called through setTimeout
                    _signal.remove();
                } else {
                    clearTimeout(_signal); //cleartimeout if called through on event
                }
            }

            this._launch(aV);
        },

        /**
         * Launch the view
         * @private
         */
        _launch: function (aV, node) {
            window.appDeferred.then( //waiting for whatever we want to preload
                lang.hitch(this, function (deferredRes) { //when wating is over call this function
                    console.log(deferredRes);

                    //init sound
                    window.appSound = new AppEnv.platformSound();
                    AppEnv.platformSound = undefined, delete AppEnv.platformSound; //clean
                    window.appSound.init(AppEnv.LSKey);
                    window.appSound.setMusicMute(); //toggle the music ON if set by the option or if we need to set default

                    //this.setup.sound.setMute("music");

                    aV.hideLogo();
                    this.reset();
                }
            ));

            if (AppEnv.platform != 'android') {
                window.appDeferred.resolve("Loading successful"); //TOSET: proper location of this code when all you want to preload is done
            }
        },

        /**
         * Reset the displayed view
         *
         * @param nId {string}, node id to display
         *
         * @return {!object} this, for chaining
         */
        reset: function (nId) {
            //TOSET: APP CODE GOES HERE

            this.view.reset();
            on(document, touch.release, lang.hitch(this, function (event) {
                var res = "App model says: " + this.model.get() + ". SFX is played";
                window.appSound.playSFX("click");
                var int1 = setInterval(function () {
                    window.appSound.playSFX("click");
                }, 750);
                var int2 = setInterval(function () {
                    window.appSound.playSFX("click");
                }, 500);
                setTimeout(function () {
                    clearInterval(int1), clearInterval(int2);
                }, 7000);
                console.log(res);
                this.view.display(res);
            }));
            on(document, "backbutton", lang.hitch(this, function (event) {
                var res = "back btn pressed";
                console.log(res);
                this.view.display(res);
            }));
        }
    });  //declare
});     //define

<|endoftext|>


<commit_before>import { emptyActionGenerator, payloadActionGenerator } from '../../redux/helpers';
import asyncServices from '../../services';
import { fetchOneProject } from '../Projects/redux';

/*
* Actions
*/
const FETCH_APPLICATIONS_REQUEST = 'application/FETCH_APPLICATIONS_REQUEST';
const FETCH_APPLICATIONS_SUCCESS = 'application/FETCH_APPLICATIONS_SUCCESS';
const FETCH_APPLICATIONS_FAILURE = 'application/FETCH_APPLICATIONS_FAILURE';

const FETCH_ONE_APPLICATION_REQUEST = 'application/FETCH_ONE_APPLICATION_REQUEST';
const FETCH_ONE_APPLICATION_SUCCESS = 'application/FETCH_ONE_APPLICATION_SUCCESS';
const FETCH_ONE_APPLICATION_FAILURE = 'application/FETCH_ONE_APPLICATION_FAILURE';

const SUBMIT_APPLICATION_REQUEST = 'application/SUBMIT_APPLICATION_REQUEST';
const SUBMIT_APPLICATION_SUCCESS = 'application/SUBMIT_APPLICATION_SUCCESS';
const SUBMIT_APPLICATION_FAILURE = 'application/SUBMIT_APPLICATION_FAILURE';

const fetchApplicationsStart = emptyActionGenerator(FETCH_APPLICATIONS_REQUEST);
const fetchApplicationsSuccess = payloadActionGenerator(FETCH_APPLICATIONS_SUCCESS);
const fetchApplicationsError = payloadActionGenerator(FETCH_APPLICATIONS_FAILURE);

const fetchOneApplicationStart = emptyActionGenerator(FETCH_ONE_APPLICATION_REQUEST);
const fetchOneApplicationSuccess = payloadActionGenerator(FETCH_ONE_APPLICATION_SUCCESS);
const fetchOneApplicationError = payloadActionGenerator(FETCH_ONE_APPLICATION_FAILURE);

const submitApplicationStart = emptyActionGenerator(SUBMIT_APPLICATION_REQUEST);
const submitApplicationSuccess = payloadActionGenerator(SUBMIT_APPLICATION_SUCCESS);
const submitApplicationError = payloadActionGenerator(SUBMIT_APPLICATION_FAILURE);

/*
* Public async thunk actions (mapped to component props)
*/
export function fetchApplications(dispatch) {
  dispatch(fetchApplicationsStart());

  return asyncServices.application
    .fetchApplications()
    .then(response => {
      dispatch(fetchApplicationsSuccess(response.data));
    })
    .catch(error => {
      dispatch(fetchApplicationsError(error));
    });
}

export function fetchOneApplication(dispatch, id) {
  dispatch(fetchOneApplicationStart());

  return asyncServices.application
    .fetchApplication(id)
    .then(response => {
      dispatch(fetchOneApplicationSuccess(response.data));
    })
    .catch(error => {
      dispatch(fetchOneApplicationError(error));
    });
}

export function fetchApplicationAndProject(dispatch, applicationId) {
  dispatch(fetchOneApplicationStart());

  return asyncServices.application
    .fetchApplication(applicationId)
    .then(response => {
      dispatch(fetchOneApplicationSuccess(response.data));
      fetchOneProject(dispatch, response.data.project);
    })
    .catch(error => {
      dispatch(fetchOneApplicationError(error));
    });
}

export function submitApplication(dispatch, data, next = () => null) {
  dispatch(submitApplicationStart());

  return asyncServices.application
    .submit(data)
    .then(response => {
      dispatch(submitApplicationSuccess(response.data));
      next();
    })
    .catch(error => {
      dispatch(submitApplicationError(error));
    });
}

/*
* Reducer
*/

// Applications
const _defaultState = {
  loading: true,
  hasApplications: false,
  data: [],
  error: null,
};

export const reducer = (state = _defaultState, action) => {
  switch (action.type) {
    case FETCH_APPLICATIONS_REQUEST:
      return {
        ...state,
        loading: true,
      };
    case FETCH_APPLICATIONS_SUCCESS:
      return {
        ...state,
        loading: false,
        hasApplications: true,
        data: action.payload,
      };
    case FETCH_APPLICATIONS_FAILURE:
      return {
        ...state,
        loading: false,
        hasApplications: false,
        error: action.payload,
      };
    default:
      return state;
  }
};

// Single Application
const _defaultApplicationState = {
  loading: true,
  data: null,
  error: null,
  hasFetched: false,
};

export const applicationReducer = (state = _defaultApplicationState, action) => {
  switch (action.type) {
    case SUBMIT_APPLICATION_REQUEST:
    case FETCH_ONE_APPLICATION_REQUEST:
      return {
        ...state,
        loading: true,
        data: null,
        error: null,
        hasFetched: false,
      };
    case SUBMIT_APPLICATION_SUCCESS:
    case FETCH_ONE_APPLICATION_SUCCESS:
      return {
        ...state,
        loading: false,
        data: action.payload,
        error: null,
        hasFetched: true,
      };
    case SUBMIT_APPLICATION_FAILURE:
    case FETCH_ONE_APPLICATION_FAILURE:
      return {
        ...state,
        loading: false,
        data: null,
        error: action.payload,
        hasFetched: true,
      };
    default:
      return state;
  }
};
<commit_msg>Do not show tables when no applications present<commit_after>import { emptyActionGenerator, payloadActionGenerator } from '../../redux/helpers';
import asyncServices from '../../services';
import { fetchOneProject } from '../Projects/redux';

/*
* Actions
*/
const FETCH_APPLICATIONS_REQUEST = 'application/FETCH_APPLICATIONS_REQUEST';
const FETCH_APPLICATIONS_SUCCESS = 'application/FETCH_APPLICATIONS_SUCCESS';
const FETCH_APPLICATIONS_FAILURE = 'application/FETCH_APPLICATIONS_FAILURE';

const FETCH_ONE_APPLICATION_REQUEST = 'application/FETCH_ONE_APPLICATION_REQUEST';
const FETCH_ONE_APPLICATION_SUCCESS = 'application/FETCH_ONE_APPLICATION_SUCCESS';
const FETCH_ONE_APPLICATION_FAILURE = 'application/FETCH_ONE_APPLICATION_FAILURE';

const SUBMIT_APPLICATION_REQUEST = 'application/SUBMIT_APPLICATION_REQUEST';
const SUBMIT_APPLICATION_SUCCESS = 'application/SUBMIT_APPLICATION_SUCCESS';
const SUBMIT_APPLICATION_FAILURE = 'application/SUBMIT_APPLICATION_FAILURE';

const fetchApplicationsStart = emptyActionGenerator(FETCH_APPLICATIONS_REQUEST);
const fetchApplicationsSuccess = payloadActionGenerator(FETCH_APPLICATIONS_SUCCESS);
const fetchApplicationsError = payloadActionGenerator(FETCH_APPLICATIONS_FAILURE);

const fetchOneApplicationStart = emptyActionGenerator(FETCH_ONE_APPLICATION_REQUEST);
const fetchOneApplicationSuccess = payloadActionGenerator(FETCH_ONE_APPLICATION_SUCCESS);
const fetchOneApplicationError = payloadActionGenerator(FETCH_ONE_APPLICATION_FAILURE);

const submitApplicationStart = emptyActionGenerator(SUBMIT_APPLICATION_REQUEST);
const submitApplicationSuccess = payloadActionGenerator(SUBMIT_APPLICATION_SUCCESS);
const submitApplicationError = payloadActionGenerator(SUBMIT_APPLICATION_FAILURE);

/*
* Public async thunk actions (mapped to component props)
*/
export function fetchApplications(dispatch) {
  dispatch(fetchApplicationsStart());

  return asyncServices.application
    .fetchApplications()
    .then(response => {
      dispatch(fetchApplicationsSuccess(response.data));
    })
    .catch(error => {
      dispatch(fetchApplicationsError(error));
    });
}

export function fetchOneApplication(dispatch, id) {
  dispatch(fetchOneApplicationStart());

  return asyncServices.application
    .fetchApplication(id)
    .then(response => {
      dispatch(fetchOneApplicationSuccess(response.data));
    })
    .catch(error => {
      dispatch(fetchOneApplicationError(error));
    });
}

export function fetchApplicationAndProject(dispatch, applicationId) {
  dispatch(fetchOneApplicationStart());

  return asyncServices.application
    .fetchApplication(applicationId)
    .then(response => {
      dispatch(fetchOneApplicationSuccess(response.data));
      fetchOneProject(dispatch, response.data.project);
    })
    .catch(error => {
      dispatch(fetchOneApplicationError(error));
    });
}

export function submitApplication(dispatch, data, next = () => null) {
  dispatch(submitApplicationStart());

  return asyncServices.application
    .submit(data)
    .then(response => {
      dispatch(submitApplicationSuccess(response.data));
      next();
    })
    .catch(error => {
      dispatch(submitApplicationError(error));
    });
}

/*
* Reducer
*/

// Applications
const _defaultState = {
  loading: true,
  hasApplications: false,
  data: [],
  error: null,
};

export const reducer = (state = _defaultState, action) => {
  switch (action.type) {
    case FETCH_APPLICATIONS_REQUEST:
      return {
        ...state,
        loading: true,
      };
    case FETCH_APPLICATIONS_SUCCESS:
      return {
        ...state,
        loading: false,
        hasApplications: action.payload.count > 0,
        data: action.payload,
      };
    case FETCH_APPLICATIONS_FAILURE:
      return {
        ...state,
        loading: false,
        hasApplications: false,
        error: action.payload,
      };
    default:
      return state;
  }
};

// Single Application
const _defaultApplicationState = {
  loading: true,
  data: null,
  error: null,
  hasFetched: false,
};

export const applicationReducer = (state = _defaultApplicationState, action) => {
  switch (action.type) {
    case SUBMIT_APPLICATION_REQUEST:
    case FETCH_ONE_APPLICATION_REQUEST:
      return {
        ...state,
        loading: true,
        data: null,
        error: null,
        hasFetched: false,
      };
    case SUBMIT_APPLICATION_SUCCESS:
    case FETCH_ONE_APPLICATION_SUCCESS:
      return {
        ...state,
        loading: false,
        data: action.payload,
        error: null,
        hasFetched: true,
      };
    case SUBMIT_APPLICATION_FAILURE:
    case FETCH_ONE_APPLICATION_FAILURE:
      return {
        ...state,
        loading: false,
        data: null,
        error: action.payload,
        hasFetched: true,
      };
    default:
      return state;
  }
};
<|endoftext|>


<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

{% include 'erpnext/selling/sales_common.js' %}
frappe.provide("erpnext.crm");

cur_frm.email_field = "contact_email";
frappe.ui.form.on("Opportunity", {
	setup: function(frm) {
		frm.custom_make_buttons = {
			'Quotation': 'Quotation',
			'Supplier Quotation': 'Supplier Quotation'
		},

		frm.set_query("opportunity_from", function() {
			return{
				"filters": {
					"name": ["in", ["Customer", "Lead"]],
				}
			}
		});

		if (frm.doc.opportunity_from && frm.doc.party_name){
			frm.trigger('set_contact_link');
		}
	},

	onload_post_render: function(frm) {
		frm.get_field("items").grid.set_multiple_add("item_code", "qty");
	},

	party_name: function(frm) {
		frm.toggle_display("contact_info", frm.doc.party_name);
		frm.trigger('set_contact_link');

		if (frm.doc.opportunity_from == "Customer") {
			erpnext.utils.get_party_details(frm);
		} else if (frm.doc.opportunity_from == "Lead") {
			erpnext.utils.map_current_doc({
				method: "erpnext.crm.doctype.lead.lead.make_opportunity",
				source_name: frm.doc.party_name,
				frm: frm
			});
		}
	},

	onload_post_render: function(frm) {
		frm.get_field("items").grid.set_multiple_add("item_code", "qty");
	},

	with_items: function(frm) {
		frm.trigger('toggle_mandatory');
	},

	customer_address: function(frm, cdt, cdn) {
		erpnext.utils.get_address_display(frm, 'customer_address', 'address_display', false);
	},

	contact_person: erpnext.utils.get_contact_details,

	opportunity_from: function(frm) {
		frm.toggle_reqd("party_name", frm.doc.opportunity_from);
		frm.trigger("set_dynamic_field_label");
	},

	refresh: function(frm) {
		var doc = frm.doc;
		frm.events.opportunity_from(frm);
		frm.trigger('toggle_mandatory');
		erpnext.toggle_naming_series();

		if(!doc.__islocal && doc.status!=="Lost") {
			if(doc.with_items){
				frm.add_custom_button(__('Supplier Quotation'),
					function() {
						frm.trigger("make_supplier_quotation")
					}, __('Create'));
			}

			frm.add_custom_button(__('Quotation'),
				cur_frm.cscript.create_quotation, __('Create'));

			if(doc.status!=="Quotation") {
				frm.add_custom_button(__('Lost'), () => {
					frm.trigger('set_as_lost_dialog');
				});
			}
		}

		if(!frm.doc.__islocal && frm.perm[0].write && frm.doc.docstatus==0) {
			if(frm.doc.status==="Open") {
				frm.add_custom_button(__("Close"), function() {
					frm.set_value("status", "Closed");
					frm.save();
				});
			} else {
				frm.add_custom_button(__("Reopen"), function() {
					frm.set_value("status", "Open");
					frm.save();
				});
			}
		}
	},

	set_contact_link: function(frm) {
		if(frm.doc.opportunity_from == "Customer" && frm.doc.party_name) {
			frappe.dynamic_link = {doc: frm.doc, fieldname: 'party_name', doctype: 'Customer'}
		} else if(frm.doc.opportunity_from == "Lead" && frm.doc.party_name) {
			frappe.dynamic_link = {doc: frm.doc, fieldname: 'party_name', doctype: 'Lead'}
		}
	},

	set_dynamic_field_label: function(frm){

		if (frm.doc.opportunity_from) {
			frm.set_df_property("party_name", "label", frm.doc.opportunity_from);
		}
	},

	make_supplier_quotation: function(frm) {
		frappe.model.open_mapped_doc({
			method: "erpnext.crm.doctype.opportunity.opportunity.make_supplier_quotation",
			frm: cur_frm
		})
	},

	toggle_mandatory: function(frm) {
		frm.toggle_reqd("items", frm.doc.with_items ? 1:0);
	}
})

// TODO commonify this code
erpnext.crm.Opportunity = frappe.ui.form.Controller.extend({
	onload: function() {

		if(!this.frm.doc.status) {
			frm.set_value('status', 'Open');
		}
		if(!this.frm.doc.company && frappe.defaults.get_user_default("Company")) {
			frm.set_value('company', frappe.defaults.get_user_default("Company"));
		}
		if(!this.frm.doc.currency) {
			frm.set_value('currency', frappe.defaults.get_user_default("Currency"));
		}

		this.setup_queries();
	},

	setup_queries: function() {
		var me = this;

		if(this.frm.fields_dict.contact_by.df.options.match(/^User/)) {
			this.frm.set_query("contact_by", erpnext.queries.user);
		}

		me.frm.set_query('customer_address', erpnext.queries.address_query);

		this.frm.set_query("item_code", "items", function() {
			return {
				query: "erpnext.controllers.queries.item_query",
				filters: {'is_sales_item': 1}
			};
		});

		me.frm.set_query('contact_person', erpnext.queries['contact_query'])

		if (me.frm.doc.opportunity_from == "Lead") {
			me.frm.set_query('party_name', erpnext.queries['lead']);
		}
		else if (me.frm.doc.opportunity_from == "Customer") {
			me.frm.set_query('party_name', erpnext.queries['customer']);
		}
	},

	create_quotation: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.crm.doctype.opportunity.opportunity.make_quotation",
			frm: cur_frm
		})
	}
});

$.extend(cur_frm.cscript, new erpnext.crm.Opportunity({frm: cur_frm}));

cur_frm.cscript.item_code = function(doc, cdt, cdn) {
	var d = locals[cdt][cdn];
	if (d.item_code) {
		return frappe.call({
			method: "erpnext.crm.doctype.opportunity.opportunity.get_item_details",
			args: {"item_code":d.item_code},
			callback: function(r, rt) {
				if(r.message) {
					$.each(r.message, function(k, v) {
						frappe.model.set_value(cdt, cdn, k, v);
					});
					refresh_field('image_view', d.name, 'items');
				}
			}
		})
	}
}<commit_msg>fix: set query on change in opportunity_from value<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

{% include 'erpnext/selling/sales_common.js' %}
frappe.provide("erpnext.crm");

cur_frm.email_field = "contact_email";
frappe.ui.form.on("Opportunity", {
	setup: function(frm) {
		frm.custom_make_buttons = {
			'Quotation': 'Quotation',
			'Supplier Quotation': 'Supplier Quotation'
		},

		frm.set_query("opportunity_from", function() {
			return{
				"filters": {
					"name": ["in", ["Customer", "Lead"]],
				}
			}
		});

		if (frm.doc.opportunity_from && frm.doc.party_name){
			frm.trigger('set_contact_link');
		}
	},

	onload_post_render: function(frm) {
		frm.get_field("items").grid.set_multiple_add("item_code", "qty");
	},

	party_name: function(frm) {
		frm.toggle_display("contact_info", frm.doc.party_name);
		frm.trigger('set_contact_link');

		if (frm.doc.opportunity_from == "Customer") {
			erpnext.utils.get_party_details(frm);
		} else if (frm.doc.opportunity_from == "Lead") {
			erpnext.utils.map_current_doc({
				method: "erpnext.crm.doctype.lead.lead.make_opportunity",
				source_name: frm.doc.party_name,
				frm: frm
			});
		}
	},

	onload_post_render: function(frm) {
		frm.get_field("items").grid.set_multiple_add("item_code", "qty");
	},

	with_items: function(frm) {
		frm.trigger('toggle_mandatory');
	},

	customer_address: function(frm, cdt, cdn) {
		erpnext.utils.get_address_display(frm, 'customer_address', 'address_display', false);
	},

	contact_person: erpnext.utils.get_contact_details,

	opportunity_from: function(frm) {
		frm.trigger('setup_queries');
		frm.toggle_reqd("party_name", frm.doc.opportunity_from);
		frm.trigger("set_dynamic_field_label");
	},

	refresh: function(frm) {
		var doc = frm.doc;
		frm.events.opportunity_from(frm);
		frm.trigger('toggle_mandatory');
		erpnext.toggle_naming_series();

		if(!doc.__islocal && doc.status!=="Lost") {
			if(doc.with_items){
				frm.add_custom_button(__('Supplier Quotation'),
					function() {
						frm.trigger("make_supplier_quotation")
					}, __('Create'));
			}

			frm.add_custom_button(__('Quotation'),
				cur_frm.cscript.create_quotation, __('Create'));

			if(doc.status!=="Quotation") {
				frm.add_custom_button(__('Lost'), () => {
					frm.trigger('set_as_lost_dialog');
				});
			}
		}

		if(!frm.doc.__islocal && frm.perm[0].write && frm.doc.docstatus==0) {
			if(frm.doc.status==="Open") {
				frm.add_custom_button(__("Close"), function() {
					frm.set_value("status", "Closed");
					frm.save();
				});
			} else {
				frm.add_custom_button(__("Reopen"), function() {
					frm.set_value("status", "Open");
					frm.save();
				});
			}
		}
	},

	set_contact_link: function(frm) {
		if(frm.doc.opportunity_from == "Customer" && frm.doc.party_name) {
			frappe.dynamic_link = {doc: frm.doc, fieldname: 'party_name', doctype: 'Customer'}
		} else if(frm.doc.opportunity_from == "Lead" && frm.doc.party_name) {
			frappe.dynamic_link = {doc: frm.doc, fieldname: 'party_name', doctype: 'Lead'}
		}
	},

	set_dynamic_field_label: function(frm){

		if (frm.doc.opportunity_from) {
			frm.set_df_property("party_name", "label", frm.doc.opportunity_from);
		}
	},

	make_supplier_quotation: function(frm) {
		frappe.model.open_mapped_doc({
			method: "erpnext.crm.doctype.opportunity.opportunity.make_supplier_quotation",
			frm: cur_frm
		})
	},

	toggle_mandatory: function(frm) {
		frm.toggle_reqd("items", frm.doc.with_items ? 1:0);
	}
})

// TODO commonify this code
erpnext.crm.Opportunity = frappe.ui.form.Controller.extend({
	onload: function() {

		if(!this.frm.doc.status) {
			frm.set_value('status', 'Open');
		}
		if(!this.frm.doc.company && frappe.defaults.get_user_default("Company")) {
			frm.set_value('company', frappe.defaults.get_user_default("Company"));
		}
		if(!this.frm.doc.currency) {
			frm.set_value('currency', frappe.defaults.get_user_default("Currency"));
		}

		this.setup_queries();
	},

	setup_queries: function() {
		var me = this;

		if(this.frm.fields_dict.contact_by.df.options.match(/^User/)) {
			this.frm.set_query("contact_by", erpnext.queries.user);
		}

		me.frm.set_query('customer_address', erpnext.queries.address_query);

		this.frm.set_query("item_code", "items", function() {
			return {
				query: "erpnext.controllers.queries.item_query",
				filters: {'is_sales_item': 1}
			};
		});

		me.frm.set_query('contact_person', erpnext.queries['contact_query'])

		if (me.frm.doc.opportunity_from == "Lead") {
			me.frm.set_query('party_name', erpnext.queries['lead']);
		}
		else if (me.frm.doc.opportunity_from == "Customer") {
			me.frm.set_query('party_name', erpnext.queries['customer']);
		}
	},

	create_quotation: function() {
		frappe.model.open_mapped_doc({
			method: "erpnext.crm.doctype.opportunity.opportunity.make_quotation",
			frm: cur_frm
		})
	}
});

$.extend(cur_frm.cscript, new erpnext.crm.Opportunity({frm: cur_frm}));

cur_frm.cscript.item_code = function(doc, cdt, cdn) {
	var d = locals[cdt][cdn];
	if (d.item_code) {
		return frappe.call({
			method: "erpnext.crm.doctype.opportunity.opportunity.get_item_details",
			args: {"item_code":d.item_code},
			callback: function(r, rt) {
				if(r.message) {
					$.each(r.message, function(k, v) {
						frappe.model.set_value(cdt, cdn, k, v);
					});
					refresh_field('image_view', d.name, 'items');
				}
			}
		})
	}
}<|endoftext|>


<commit_before> //
//Scripts for documents panel on cases tab
//

function createTrail(path)
{

    var pathArray = path.split('/');
    var pathString = '';
    var pathS = '';
    $.each(pathArray, function(i, v) {
        pathS += '/' + v;
        pathSa = pathS.substr(1);
        pathItem = '' + unescape(v) + '/';
        pathString += pathItem;
    });

    return pathString;
}

//User clicks to open document window
$('.case_detail_nav #item3').live('click', function() {

    var thisPanel = $(this).closest('.case_detail_nav').siblings('.case_detail_panel');
    var caseId = $(this).closest('.case_detail_nav').siblings('.case_detail_panel').data('CaseNumber');

    //Get heights
    var toolsHeight = $(this).outerHeight();
    var thisPanelHeight = $(this).closest('.case_detail_nav').height();
    var documentsWindowHeight = thisPanelHeight - toolsHeight;

    thisPanel.load('lib/php/data/cases_documents_load.php', {'id': caseId}, function() {

        //Set css
        $('div.case_detail_panel_tools').css({'height': toolsHeight});
        $('div.case_detail_panel_casenotes').css({'height': caseNotesWindowHeight});
        $('div.case_detail_panel_tools_left').css({'width': '60%'});
        $('div.case_detail_panel_tools_right').css({'width': '40%'});

        //Set buttons
        $('button.doc_new_folder').button({icons: {primary: "fff-icon-folder-add"},text: true}).next().button({icons: {primary: "fff-icon-page-white-get"},text: true});

        //Unescape folder names
		$('.folder p').each(function(){
			var t = unescape($(this).html());
			$(this).html(t);
		});
	});

    //Create context menu

    $("div.doc_item").contextMenu({menu: 'docMenu'}, function(action, el, pos) {
        //TODO fix the problem where the context menu tries to open outside the viewport
        switch (action)
        {
            case 'open':
                var thisUrl = $(el).find('a').attr('href');
                window.open(thisUrl, '_new');
                break;

            case 'cut':
                $(el).css({'opacity': '.5'});
                break;

            case 'copy':
                $(el).css({'border': '1px solid #AAA'});
                break;

            case 'delete':

                var dialogWin = $('
This document will be permanently deleted from the server.  Are you sure?
').dialog({
                    autoOpen: true,
                    resizable: false,
                    modal: true,
                    buttons: {
                        "Yes": function() {
                            //insert delete code here
                            $(this).dialog("destroy");
                        },
                        "No": function() {
                            $(this).dialog("destroy");
                        }
                    }
                });
                break;

            case 'properties':
                $(el).css({'border': '1px solid #AAA'}).next('.doc_properties').addClass('ui-corner-all').css({'top': '20%','left': '30%'}).show().focus().focusout(function() {
                    $(this).hide();
                    $(el).css({'border': '0px'});
                });
                break;
        }

    // alert(
    //     'Action: ' + action + '\n\n' +
    //     'Element ID: ' + $(el).attr('id') + '\n\n' +
    //     'X: ' + pos.x + '  Y: ' + pos.y + ' (relative to element)\n\n' +
    //     'X: ' + pos.docX + '  Y: ' + pos.docY+ ' (relative to document)'
    //     );
    });

    //Expand div to include full file name on mouse enter
    $('div.doc_item > a').live('mouseenter', function(event) {
        $(this).closest('div').css({'height': 'auto','overflow': 'auto'});

        if ($(this).closest('div').hasClass('doc'))
        {
            $(this).closest('div').draggable({revert: 'invalid'});
        }
        else
        {
            $(this).closest('div').droppable();
        }

    });

    //Reset on leave
    $('div.doc_item > a').live('mouseleave', function(event) {
        $(this).closest('div').css({'height': '120px','overflow': 'hidden'});
    });

});

//User clicks a folder or document
$('div.doc_item > a').live('click', function(event) {
    event.preventDefault();

    if ($(this).closest('div').hasClass('folder'))
    {
        var path = $(this).closest('div').attr('path');
        var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
        var pathDisplay = $(this).closest('.case_detail_panel_casenotes').siblings('.case_detail_panel_tools').find('.path_display');

        $(this).closest('.case_detail_panel_casenotes').load('lib/php/data/cases_documents_load.php', {'id': caseId,'container': path,'path': path,'update': 'y'}, function() {
            var pathString = createTrail(path);
            pathDisplay.html(pathString);
            pathDisplay.find("a[path='" + path + "']").addClass('active');
            //Unescape folder names
			$('.folder p').each(function(){
				var t = unescape($(this).html());
				$(this).html(t);
			});

        });
    }

    else

    { // TODO insert document actions

    }

});

//User clicks new folder button
$('button.doc_new_folder').live('click', function() {
    var target = $(this).closest('.case_detail_panel_tools').siblings('.case_detail_panel_casenotes');
    target.prepend("

<textarea id='new_folder_name'>New Folder</textarea>

");
    $('#new_folder_name').css({'background-color': '#EDF09F'})
    .mouseenter(function() {
        $(this).val('').focus().css({'background-color': 'white'});
    })
    .keypress(function(e) {
        if (e.which == 13) {
            event.preventDefault();
            var container = $(this).closest('.case_detail_panel_casenotes').siblings('.case_detail_panel_tools').find('a.active').attr('path');
            var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
            var newName = $('#new_folder_name').val();
            var newFolder = null;
            if (container === '')
            {
                newFolder = escape(newName);
            }
            else
            {
                newFolder = container + "/" + escape(newName);
            }
            $.post('lib/php/data/cases_documents_process.php', {'case_id': caseId,'container': container,'new_folder': newFolder,'action': 'newfolder'}, function(data) {
                var serverVals = $.parseJSON(data);
                $('#new_folder_name').parent().siblings('img').wrap('');
                $('#new_folder_name').closest('.folder').attr({'path': newFolder,'data-id': serverVals.id}).droppable();
                $('#new_folder_name').closest('p').html(newName);
                notify(serverVals.message);
            });
        }
    });

});

//User clicks the Home link in the directory path
$('a.doc_trail_home').live('click', function(event) {
    event.preventDefault();
    var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
    var thisPanel = $(this).closest('.case_detail_panel_tools').siblings('.case_detail_panel_casenotes');
    thisPanel.load('lib/php/data/cases_documents_load.php', {'id': caseId,'update': 'yes'}, function() {
        $(this).siblings('.case_detail_panel_tools').find('.path_display').html('');
        //Unescape folder names
		$('.folder p').each(function(){
			var t = unescape($(this).html());
			$(this).html(t);
		});
    });
});

//User clicks one of the other links in the directory path
$('a.doc_trail_item').live('click', function(event) {
    event.preventDefault();
    var container = $(this).html();
    var path = $(this).attr('path');
    var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
    var thisPanel = $(this).closest('.case_detail_panel_tools').siblings('.case_detail_panel_casenotes');
    var pathDisplay = $(this).parent();

    thisPanel.load('lib/php/data/cases_documents_load.php', {'id': caseId,'update': 'yes','path': path,'container': path}, function() {
        $(this).siblings('.case_detail_panel_tools').find('.path_display').html('');
        var pathString = createTrail(path);
        pathDisplay.html(pathString);
        pathDisplay.find("a[path='" + path + "']").addClass('active');

    });
});
<commit_msg>Add shadow on documents scroll<commit_after> //
//Scripts for documents panel on cases tab
//

function createTrail(path)
{

    var pathArray = path.split('/');
    var pathString = '';
    var pathS = '';
    $.each(pathArray, function(i, v) {
        pathS += '/' + v;
        pathSa = pathS.substr(1);
        pathItem = '' + unescape(v) + '/';
        pathString += pathItem;
    });

    return pathString;
}

//User clicks to open document window
$('.case_detail_nav #item3').live('click', function() {

    var thisPanel = $(this).closest('.case_detail_nav').siblings('.case_detail_panel');
    var caseId = $(this).closest('.case_detail_nav').siblings('.case_detail_panel').data('CaseNumber');

    //Get heights
    var toolsHeight = $(this).outerHeight();
    var thisPanelHeight = $(this).closest('.case_detail_nav').height();
    var documentsWindowHeight = thisPanelHeight - toolsHeight;

    thisPanel.load('lib/php/data/cases_documents_load.php', {'id': caseId}, function() {

        //Set css
        $('div.case_detail_panel_tools').css({'height': toolsHeight});
        $('div.case_detail_panel_casenotes').css({'height': caseNotesWindowHeight});
        $('div.case_detail_panel_tools_left').css({'width': '60%'});
        $('div.case_detail_panel_tools_right').css({'width': '40%'});

        //Set buttons
        $('button.doc_new_folder').button({icons: {primary: "fff-icon-folder-add"},text: true}).next().button({icons: {primary: "fff-icon-page-white-get"},text: true});

        //Unescape folder names
        $('.folder p').each(function() {
            var t = unescape($(this).html());
            $(this).html(t);
        });

        //Apply shadow on scroll
        $(this).children('.case_detail_panel_casenotes').bind('scroll', function() {
            var scrollAmount = $(this).scrollTop();
            if (scrollAmount === 0 && $(this).hasClass('csenote_shadow'))
            {
                $(this).removeClass('csenote_shadow');
            }
            else
            {
                $(this).addClass('csenote_shadow');
            }
        });

    });

    //Create context menu

    $("div.doc_item").contextMenu({menu: 'docMenu'}, function(action, el, pos) {
        //TODO fix the problem where the context menu tries to open outside the viewport
        switch (action)
        {
            case 'open':
                var thisUrl = $(el).find('a').attr('href');
                window.open(thisUrl, '_new');
                break;

            case 'cut':
                $(el).css({'opacity': '.5'});
                break;

            case 'copy':
                $(el).css({'border': '1px solid #AAA'});
                break;

            case 'delete':

                var dialogWin = $('
This document will be permanently deleted from the server.  Are you sure?
').dialog({
                    autoOpen: true,
                    resizable: false,
                    modal: true,
                    buttons: {
                        "Yes": function() {
                            //insert delete code here
                            $(this).dialog("destroy");
                        },
                        "No": function() {
                            $(this).dialog("destroy");
                        }
                    }
                });
                break;

            case 'properties':
                $(el).css({'border': '1px solid #AAA'}).next('.doc_properties').addClass('ui-corner-all').css({'top': '20%','left': '30%'}).show().focus().focusout(function() {
                    $(this).hide();
                    $(el).css({'border': '0px'});
                });
                break;
        }

    // alert(
    //     'Action: ' + action + '\n\n' +
    //     'Element ID: ' + $(el).attr('id') + '\n\n' +
    //     'X: ' + pos.x + '  Y: ' + pos.y + ' (relative to element)\n\n' +
    //     'X: ' + pos.docX + '  Y: ' + pos.docY+ ' (relative to document)'
    //     );
    });

    //Expand div to include full file name on mouse enter
    $('div.doc_item > a').live('mouseenter', function(event) {
        $(this).closest('div').css({'height': 'auto','overflow': 'auto'});

        if ($(this).closest('div').hasClass('doc'))
        {
            $(this).closest('div').draggable({revert: 'invalid'});
        }
        else
        {
            $(this).closest('div').droppable();
        }

    });

    //Reset on leave
    $('div.doc_item > a').live('mouseleave', function(event) {
        $(this).closest('div').css({'height': '120px','overflow': 'hidden'});
    });

});

//User clicks a folder or document
$('div.doc_item > a').live('click', function(event) {
    event.preventDefault();

	if ($(this).closest('div').hasClass('folder'))
    {
        var path = $(this).closest('div').attr('path');
        var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
        var pathDisplay = $(this).closest('.case_detail_panel_casenotes').siblings('.case_detail_panel_tools').find('.path_display');

        $(this).closest('.case_detail_panel_casenotes').load('lib/php/data/cases_documents_load.php', {'id': caseId,'container': path,'path': path,'update': 'y'}, function() {
            var pathString = createTrail(path);
            pathDisplay.html(pathString);
            pathDisplay.find("a[path='" + path + "']").addClass('active');
            //Unescape folder names
            $('.folder p').each(function() {
                var t = unescape($(this).html());
                $(this).html(t);
            });
            //Apply shadow on scroll
            $(this).children('.case_detail_panel_casenotes').bind('scroll', function() {
                var scrollAmount = $(this).scrollTop();
                if (scrollAmount === 0 && $(this).hasClass('csenote_shadow'))
                {
                    $(this).removeClass('csenote_shadow');
                }
                else
                {
                    $(this).addClass('csenote_shadow');
                }
            });

        });
    }

    else

    { // TODO insert document actions

    }

});

//User clicks new folder button
$('button.doc_new_folder').live('click', function() {
    var target = $(this).closest('.case_detail_panel_tools').siblings('.case_detail_panel_casenotes');
    target.prepend("

<textarea id='new_folder_name'>New Folder</textarea>

");
    $('#new_folder_name').css({'background-color': '#EDF09F'})
    .mouseenter(function() {
        $(this).val('').focus().css({'background-color': 'white'});
    })
    .keypress(function(e) {
        if (e.which == 13) {
            event.preventDefault();
            var container = $(this).closest('.case_detail_panel_casenotes').siblings('.case_detail_panel_tools').find('a.active').attr('path');
            var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
            var newName = $('#new_folder_name').val();
            var newFolder = null;
            if (container === '')
            {
                newFolder = escape(newName);
            }
            else
            {
                newFolder = container + "/" + escape(newName);
            }
            $.post('lib/php/data/cases_documents_process.php', {'case_id': caseId,'container': container,'new_folder': newFolder,'action': 'newfolder'}, function(data) {
                var serverVals = $.parseJSON(data);
                $('#new_folder_name').parent().siblings('img').wrap('');
                $('#new_folder_name').closest('.folder').attr({'path': newFolder,'data-id': serverVals.id}).droppable();
                $('#new_folder_name').closest('p').html(newName);
                notify(serverVals.message);
            });
        }
    });

});

//User clicks the Home link in the directory path
$('a.doc_trail_home').live('click', function(event) {
    event.preventDefault();
    var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
    var thisPanel = $(this).closest('.case_detail_panel_tools').siblings('.case_detail_panel_casenotes');
    thisPanel.load('lib/php/data/cases_documents_load.php', {'id': caseId,'update': 'yes'}, function() {
        $(this).siblings('.case_detail_panel_tools').find('.path_display').html('');
        //Unescape folder names
        $('.folder p').each(function() {
            var t = unescape($(this).html());
            $(this).html(t);
        });
    });
});

//User clicks one of the other links in the directory path
$('a.doc_trail_item').live('click', function(event) {
    event.preventDefault();
    var container = $(this).html();
    var path = $(this).attr('path');
    var caseId = $(this).closest('.case_detail_panel').data('CaseNumber');
    var thisPanel = $(this).closest('.case_detail_panel_tools').siblings('.case_detail_panel_casenotes');
    var pathDisplay = $(this).parent();

    thisPanel.load('lib/php/data/cases_documents_load.php', {'id': caseId,'update': 'yes','path': path,'container': path}, function() {
        $(this).siblings('.case_detail_panel_tools').find('.path_display').html('');
        var pathString = createTrail(path);
        pathDisplay.html(pathString);
        pathDisplay.find("a[path='" + path + "']").addClass('active');
        //Unescape folder names
        $('.folder p').each(function() {
            var t = unescape($(this).html());
            $(this).html(t);
        });

        //Apply shadow on scroll
        $(this).children('.case_detail_panel_casenotes').bind('scroll', function() {
            var scrollAmount = $(this).scrollTop();
            if (scrollAmount === 0 && $(this).hasClass('csenote_shadow'))
            {
                $(this).removeClass('csenote_shadow');
            }
            else
            {
                $(this).addClass('csenote_shadow');
            }
        });

    });
});
<|endoftext|>


<commit_before>import _ from 'lodash';
import { t } from '../util/locale';
import { areaKeys } from '../core/context';

export function presetPreset(id, preset, fields) {
    preset = _.clone(preset);

    preset.id = id;
    preset.fields = (preset.fields || []).map(getFields);
    preset.geometry = (preset.geometry || []);

    function getFields(f) {
        return fields[f];
    }

    preset.matchGeometry = function(geometry) {
        return preset.geometry.indexOf(geometry) >= 0;
    };

    preset.originalScore = preset.matchScore || 1;

    preset.matchScore = function(entity) {
        var tags = preset.tags,
            score = 0;

        for (var t in tags) {
            if (entity.tags[t] === tags[t]) {
                score += preset.originalScore;
            } else if (tags[t] === '*' && t in entity.tags) {
                score += preset.originalScore / 2;
            } else {
                return -1;
            }
        }

        return score;
    };

    preset.t = function(scope, options) {
        return t('presets.presets.' + id + '.' + scope, options);
    };

    var name = preset.name || '';
    preset.name = function() {
        if (preset.suggestion) {
            id = id.split('/');
            id = id[0] + '/' + id[1];
            return name + ' - ' + t('presets.presets.' + id + '.name');
        }
        return preset.t('name', {'default': name});
    };

    preset.terms = function() {
        return preset.t('terms', {'default': ''}).toLowerCase().trim().split(/\s*,+\s*/);
    };

    preset.isFallback = function() {
        var tagCount = Object.keys(preset.tags).length;
        return tagCount === 0 || (tagCount === 1 && preset.tags.hasOwnProperty('area'));
    };

    var reference = preset.reference || {};
    preset.reference = function(geometry) {
        var key = reference.key || Object.keys(preset.tags)[0],
            value = reference.value || preset.tags[key];

        if (geometry === 'relation' && key === 'type') {
            if (value in preset.tags) {
                key = value;
                value = preset.tags[key];
            } else {
                return { rtype: value };
            }
        }

        if (value === '*') {
            return { key: key };
        } else {
            return { key: key, value: value };
        }
    };

    var removeTags = preset.removeTags || preset.tags;
    preset.removeTags = function(tags, geometry) {
        tags = _.omit(tags, _.keys(removeTags));

        for (var f in preset.fields) {
            var field = preset.fields[f];
            if (field.matchGeometry(geometry) && field.default === tags[field.key]) {
                delete tags[field.key];
            }
        }

        delete tags.area;
        return tags;
    };

    var applyTags = preset.addTags || preset.tags;
    preset.applyTags = function(tags, geometry) {
        var k;

        tags = _.clone(tags);

        for (k in applyTags) {
            if (applyTags[k] === '*') {
                tags[k] = 'yes';
            } else {
                tags[k] = applyTags[k];
            }
        }

        // Add area=yes if necessary.
        // This is necessary if the geometry is already an area (e.g. user drew an area) AND any of:
        // 1. chosen preset could be either an area or a line (`barrier=city_wall`)
        // 2. chosen preset doesn't have a key in areaKeys (`railway=station`)
        if (geometry === 'area') {
            var needsAreaTag = true;
            if (preset.geometry.indexOf('line') === -1) {
                for (k in applyTags) {
                    if (k in areaKeys) {
                        needsAreaTag = false;
                        break;
                    }
                }
            }
            if (needsAreaTag) {
                tags.area = 'yes';
            }
        }

        for (var f in preset.fields) {
            var field = preset.fields[f];
            if (field.matchGeometry(geometry) && field.key && !tags[field.key] && field.default) {
                tags[field.key] = field.default;
            }
        }

        return tags;
    };

    return preset;
}
<commit_msg>Omit `name` tag when looking up preset documentation (closes #4059)<commit_after>import _ from 'lodash';
import { t } from '../util/locale';
import { areaKeys } from '../core/context';

export function presetPreset(id, preset, fields) {
    preset = _.clone(preset);

    preset.id = id;
    preset.fields = (preset.fields || []).map(getFields);
    preset.geometry = (preset.geometry || []);

    function getFields(f) {
        return fields[f];
    }

    preset.matchGeometry = function(geometry) {
        return preset.geometry.indexOf(geometry) >= 0;
    };

    preset.originalScore = preset.matchScore || 1;

    preset.matchScore = function(entity) {
        var tags = preset.tags,
            score = 0;

        for (var t in tags) {
            if (entity.tags[t] === tags[t]) {
                score += preset.originalScore;
            } else if (tags[t] === '*' && t in entity.tags) {
                score += preset.originalScore / 2;
            } else {
                return -1;
            }
        }

        return score;
    };

    preset.t = function(scope, options) {
        return t('presets.presets.' + id + '.' + scope, options);
    };

    var name = preset.name || '';
    preset.name = function() {
        if (preset.suggestion) {
            id = id.split('/');
            id = id[0] + '/' + id[1];
            return name + ' - ' + t('presets.presets.' + id + '.name');
        }
        return preset.t('name', {'default': name});
    };

    preset.terms = function() {
        return preset.t('terms', {'default': ''}).toLowerCase().trim().split(/\s*,+\s*/);
    };

    preset.isFallback = function() {
        var tagCount = Object.keys(preset.tags).length;
        return tagCount === 0 || (tagCount === 1 && preset.tags.hasOwnProperty('area'));
    };

    var reference = preset.reference || {};
    preset.reference = function(geometry) {
        var key = reference.key || Object.keys(_.omit(preset.tags, 'name'))[0],
            value = reference.value || preset.tags[key];

        if (geometry === 'relation' && key === 'type') {
            if (value in preset.tags) {
                key = value;
                value = preset.tags[key];
            } else {
                return { rtype: value };
            }
        }

        if (value === '*') {
            return { key: key };
        } else {
            return { key: key, value: value };
        }
    };

    var removeTags = preset.removeTags || preset.tags;
    preset.removeTags = function(tags, geometry) {
        tags = _.omit(tags, _.keys(removeTags));

        for (var f in preset.fields) {
            var field = preset.fields[f];
            if (field.matchGeometry(geometry) && field.default === tags[field.key]) {
                delete tags[field.key];
            }
        }

        delete tags.area;
        return tags;
    };

    var applyTags = preset.addTags || preset.tags;
    preset.applyTags = function(tags, geometry) {
        var k;

        tags = _.clone(tags);

        for (k in applyTags) {
            if (applyTags[k] === '*') {
                tags[k] = 'yes';
            } else {
                tags[k] = applyTags[k];
            }
        }

        // Add area=yes if necessary.
        // This is necessary if the geometry is already an area (e.g. user drew an area) AND any of:
        // 1. chosen preset could be either an area or a line (`barrier=city_wall`)
        // 2. chosen preset doesn't have a key in areaKeys (`railway=station`)
        if (geometry === 'area') {
            var needsAreaTag = true;
            if (preset.geometry.indexOf('line') === -1) {
                for (k in applyTags) {
                    if (k in areaKeys) {
                        needsAreaTag = false;
                        break;
                    }
                }
            }
            if (needsAreaTag) {
                tags.area = 'yes';
            }
        }

        for (var f in preset.fields) {
            var field = preset.fields[f];
            if (field.matchGeometry(geometry) && field.key && !tags[field.key] && field.default) {
                tags[field.key] = field.default;
            }
        }

        return tags;
    };

    return preset;
}
<|endoftext|>