<commit_before>var DND_DATA = {
  versions: [{'0': 'Original'}
  ],

  species: {
    "0": {
      "": ["Accountant", "Human Resources Generalist", "IT Expert", "Personal Assistant", "Temp"]
    },
  },

  gen_text: [
    "Been There, Done That",
    "Been There, Done That Twice",
    "Nope",
    "Not That",
    "Re-Roll",
    "Re-Roll",
    "Try Again",
    "Try Again",
  ],

  adjective: [
    "Absent-minded",
    "Adventurous",
    "Agreeable",
    "Ambitious",
    "Amicable",
    "Anxious",
    "Apathetic",
    "Argumentative",
    "Assertive",
    "Attentive",
    "Bigoted",
    "Bitchy",
    "Blunt",
    "Boisterous",
    "Bossy",
    "Brave",
    "Broad-minded",
    "Callous",
    "Cautious",
    "Charming",
    "Cheerful",
    "Chipper",
    "Churchy",
    "Churlish",
    "Cold",
    "Compassionate",
    "Composed",
    "Conceited",
    "Condescending",
    "Confident",
    "Conscientious",
    "Considerate",
    "Cool-headed",
    "Courageous",
    "Crabby",
    "Crass",
    "Critical",
    "Cruel",
    "Cunning",
    "Curious",
    "Cynical",
    "Decisive",
    "Delightful",
    "Demure",
    "Dependable",
    "Depressed",
    "Determined",
    "Diligent",
    "Diplomatic",
    "Discerning",
    "Disruptive",
    "Dramatic",
    "Driven",
    "Drunken",
    "Dutiful",
    "Eager",
    "Easy-going",
    "Egotistical",
    "Elderly",
    "Emotional",
    "Enterprising",
    "Enthusiastic",
    "Excitable",
    "Faithful",
    "Fearless",
    "Flamboyant",
    "Flirtatious",
    "Frank",
    "Friendly",
    "Funny",
    "Fussy",
    "Generous",
    "Gentle",
    "Gloomy",
    "Grave",
    "Grouchy",
    "Gruff",
    "Guarded",
    "Hard-working",
    "Hateful",
    "Headstrong",
    "Helpful",
    "Hot-headed",
    "Hypercritical",
    "Impatient",
    "Impetuous",
    "Impulsive",
    "Inconsiderate",
    "Insensitive",
    "Intolerant",
    "Inventive",
    "Irritable",
    "Lazy",
    "Level-headed",
    "Loud",
    "Loyal",
    "Machiavellian",
    "Mean",
    "Melodramatic",
    "Methodical",
    "Meticulous",
    "Miserable",
    "Modest",
    "Moody",
    "Morose",
    "Motivated",
    "Naive",
    "Nosy",
    "Obnoxious",
    "Old-fashioned",
    "Outgoing",
    "Outspoken",
    "Overemotional",
    "Paranoid",
    "Passive-aggressive",
    "Peaceful",
    "Pensive",
    "Philosophical",
    "Plain-speaking",
    "Playful",
    "Plucky",
    "Pompous",
    "Positive",
    "Prejudiced",
    "Pretty chill",
    "Proud",
    "Quick-tempered",
    "Reliable",
    "Reluctant",
    "Resentful",
    "Resourceful",
    "Respectful",
    "Restless",
    "Romantic",
    "Sassy",
    "Selfish",
    "Sensitive",
    "Sentimental",
    "Short-tempered",
    "Snobby",
    "Sombre",
    "Sophisticated",
    "Soulless",
    "Spiteful",
    "Stern",
    "Stoic",
    "Surly",
    "Suspicious",
    "Sweet",
    "Tactless",
    "Talented",
    "Thoughtful",
    "Unbalanced",
    "Unpredictable",
    "Unstable",
    "Warm-hearted",
    "Wary",
    "Well-intentioned",
  ],

  dclass: [
    "Barbarian",
    "Bard",
    "Cleric",
    "Druid",
    "Fighter",
    "Monk",
    "Paladin",
    "Ranger",
    "Rogue",
    "Sorcerer",
    "Warlock",
    "Wizard",
  ],

  location: [
    "Alaska",
    "Amsterdam",
    "Atlanta",
    "Austin",
    "Baghdad",
    "Baltimore",
    "Barcelona",
    "Baton Rogue",
    "Beijing",
    "Berlin",
    "Bolivia",
    "Boston",
    "Boulder",
    "Budapest",
    "Calcutta",
    "Cairo",
    "Cardiff, Wales",
    "Chicago",
    "Cincinnati",
    "Columbus, Ohio",
    "Dallas",
    "Denver",
    "Des Moines",
    "Detroit",
    "Dubai",
    "El Paso",
    "Fargo, North Dakota",
    "Flagstaff",
    "Fresno",
    "Hawaii",
    "Hong Kong",
    "Houston",
    "Iceland",
    "Jackson, Mississippi",
    "Kansas City",
    "Kenya",
    "Lima, Peru",
    "London",
    "Los Angeles",
    "Los Vegas",
    "Lubbock, Texas",
    "Madrid",
    "Manilla, Philippines",
    "Memphis",
    "Mexico City",
    "Miami",
    "Milwaukee",
    "Minneapolis",
    "Moab, Utah",
    "Moldova",
    "Montreal, Canada",
    "Mumbai",
    "Nashville",
    "New Jersey",
    "New York City",
    "New Zealand",
    "North Dakota",
    "Oslo, Norway",
    "Paris",
    "Paris, Texas",
    "Philadelphia",
    "Portland",
    "Ramstein, Germany",
    "Reno",
    "Sacramento",
    "Salem, Oregon",
    "San Antonio",
    "San Diego",
    "San Francisco",
    "San Jose",
    "Seattle",
    "Seoul, Sourth Korea",
    "Sidney, Australia",
    "Singapore",
    "South Africa",
    "South Dakota",
    "São Paulo, Brazil",
    "Tokyo",
    "Toledo",
    "Tornto, Canada",
    "Tucson",
    "Tulsa",
    "Washington, D.C.",
    "rural Alabama",
    "rural Iowa",
    "rural Montana",
    "rural Nebraska",
    "rural Utah",
    "rural Vermont",
    "upstate New York",
  ],

  backstory: [
    "acts shallow but only to hide their insecurities",
    "acts younger than they are, but not in a good way",
    "always gets sloppy drunk at office parties",
    "always gives the bad news first",
    "always gives the good news first",
    "always has Skinny Cow ice cream in the fridge and goes to Zumba once a week",
    "always invites people to Toastmasters",
    "always keeps their promises",
    "always looks bored",
    "always looks hungover",
    "always looks relaxed",
    "always looks tired",
    "always looks their best",
    "always lies when asked what they are doing this weekend",
    "always shows up late",
    "always skips out early",
    "always speaks very formally",
    "always needs to be the centre of attention",
    'always refers to inanimate objects as "she"',
    "always speaks in the third person",
    "always thinks outside the box",
    "always wanted to be an artist",
    "always wants to talk about their weekend",
    'always wears Converses and only listens to "real" hip-hop',
    "argues with their spouse on the phone every day",
    "became a grandparent at 36",
    "believes in an eye for an eye",
    'believe is "dress for success"',
    'clearly partied hard when they were young and still thinks of themself as "cool"',
    "clears their throat all day long",
    "collects those creepy porcelain dolls",
    "collects vinyl, quit cigarettes but still bums them",
    "dresses inappropriately",
    "drives a red Mustang and spends their tax return in Vegas",
    'dropped out of college after a month but got a "degree in life" after backpacking in Costa Rica for 2 weeks',
    "follows 3000 people on Instagram and claims they can get you backstage at any show",
    "follows every sport on TV",
    "from the suburbs but pretends they are from the city",
    "goes backpacking in the Summer",
    "goes to Burning Man every year",
    "has a dish of cheap candy on their desk",
    "has a dish of expensive chocolates on their desk",
    "has a dog instead of a child",
    "has a newborn and hasn't slept in weeks",
    "has a PhD in something useless",
    "has a terrible case or Resting Bitch Face, but is super nice",
    "has five cats at home",
    "has no chin",
    "has Resting Bitch Face",
    "has Seasonal Affective Disorder",
    "has the world's largest ugly sweater collection, but doesn't know it",
    "has two dogs and no kids",
    "has two drinks at lunch",
    "hasn't done any work in years",
    "is a Christian Mom, hates rap, and has five kids",
    "is a huge drama queen",
    "is a jerk",
    "is a morning person",
    "is a wicked swing dancer, great fun at parties, but might be illiterate",
    "is always complaining about how busy they are, but they aren't",
    "is always having a bad day",
    "is always on the phone organization their kids soccer league",
    "is always relentlessly positive",
    "is an alcoholic and drinks a Monster before work every morning",
    "is an extreme couponer and buys porn video tapes on E-Bay",
    "is chill AF and dabs like it's their job",
    "is counting the days until retirement",
    "is in a band",
    "is fat-fit, but thinks they're regular fit",
    "is more of a night person",
    "is not cut out for office life",
    "is not using their college degree",
    "is really nice until you mention religion",
    "is really old-fashioned",
    "is recently divorced, smokes menthols, always asks to see the manager",
    "is married to someone WAY more attractive than them",
    "is super churchy",
    "is super nice and friendly; probably relaxed because they never do any work",
    "is technically polite, but in a really artifical fake way that is hard to trust",
    "is terrible at conversation",
    "is the poster child for Peter Pan Syndrome",
    "is too good work here",
    "is too good work here and will probably leave soon",
    "is too nice",
    "is very concerned about appearances",
    "is very concerned about politics",
    "is WAY too friendly to management",
    "looks like a hipster douchebag, but is actually really nice",
    "looks older than they are",
    "loves shopping and is deeply in debt",
    "loves underground techno and smokes roll-ups with menthol filters",
    "love Tennis and Celine Dion",
    "makes a mean caserole, racist, and already called the police",
    'married rich and is talking about "retiring" at 42',
    "married their highschool sweatheart",
    "mumbles incoherantly all the time",
    "never does any work and makes life harder for everyone around them",
    "never lets a conversation end when it should",
    "never shuts up about rock climbing",
    "only goes on vacation to Disneyland",
    "only talks to people of the opposite sex",
    "owns three rental houses and will probably retire early",
    "part-time yoga instructor, Vegan(ish), and loves Whole Foods",
    "probably has Aspergers, but is really good at their job",
    "really wants to be management",
    "rides horses and won't shut up about it",
    "repeats everything you say",
    "shares global warming articles on FB, drives a Prius, #feelthebern",
    "should have retired years ago",
    "shushes people in church",
    "smiles, but only with their mouth",
    "stills plays beer pong on the weekends",
    "stinks of Axe and Weed, plays CoD Zombies religously",
    "summers in Connecticut, and owns three horses",
    "thinks they are really smart",
    "thinks their child is a genius",
    "thinks their great at office politics, but aren't",
    "used to be a body builder but has settled down and had kids",
    "used to be in good shape",
    "used to be in the military, so they come in early and work harder than everyone else",
    "uses big words to sound smart",
    "was a lumber sexual before it was cool",
    "was clearly born into a rich family and doesn't need this job",
    "was really popular in high school, but is really jaded now",
    'was voted "most likely to become a serial killer" in highschool',
    "was widowed, writes $12 checks, and smells like old people",
    "went to college but doesn't seem like the educated type",
    "won't shut up about their kids",
    "won't stop talking about their kids",
    "worships martinis and everything they stand for",
    "would literally kill someone for a salad right now",
  ]
};

RPG_Char.init(DND_DATA);
<commit_msg>adding basic classes<commit_after>var DND_DATA = {
  versions: [{'0': 'Original'}
  ],

  species: {
    "0": {
      "": ["Accountant", "Human Resources Generalist", "IT Expert", "Personal Assistant", "Temp"]
    },
  },

  gen_text: [
    "Been There, Done That",
    "Been There, Done That Twice",
    "Nope",
    "Not That",
    "Re-Roll",
    "Re-Roll",
    "Try Again",
    "Try Again",
  ],

  adjective: [
    "Absent-minded",
    "Adventurous",
    "Agreeable",
    "Ambitious",
    "Amicable",
    "Anxious",
    "Apathetic",
    "Argumentative",
    "Assertive",
    "Attentive",
    "Bigoted",
    "Bitchy",
    "Blunt",
    "Boisterous",
    "Bossy",
    "Brave",
    "Broad-minded",
    "Callous",
    "Cautious",
    "Charming",
    "Cheerful",
    "Chipper",
    "Churchy",
    "Churlish",
    "Cold",
    "Compassionate",
    "Composed",
    "Conceited",
    "Condescending",
    "Confident",
    "Conscientious",
    "Considerate",
    "Cool-headed",
    "Courageous",
    "Crabby",
    "Crass",
    "Critical",
    "Cruel",
    "Cunning",
    "Curious",
    "Cynical",
    "Decisive",
    "Delightful",
    "Demure",
    "Dependable",
    "Depressed",
    "Determined",
    "Diligent",
    "Diplomatic",
    "Discerning",
    "Disruptive",
    "Dramatic",
    "Driven",
    "Drunken",
    "Dutiful",
    "Eager",
    "Easy-going",
    "Egotistical",
    "Elderly",
    "Emotional",
    "Enterprising",
    "Enthusiastic",
    "Excitable",
    "Faithful",
    "Fearless",
    "Flamboyant",
    "Flirtatious",
    "Frank",
    "Friendly",
    "Funny",
    "Fussy",
    "Generous",
    "Gentle",
    "Gloomy",
    "Grave",
    "Grouchy",
    "Gruff",
    "Guarded",
    "Hard-working",
    "Hateful",
    "Headstrong",
    "Helpful",
    "Hot-headed",
    "Hypercritical",
    "Impatient",
    "Impetuous",
    "Impulsive",
    "Inconsiderate",
    "Insensitive",
    "Intolerant",
    "Inventive",
    "Irritable",
    "Lazy",
    "Level-headed",
    "Loud",
    "Loyal",
    "Machiavellian",
    "Mean",
    "Melodramatic",
    "Methodical",
    "Meticulous",
    "Miserable",
    "Modest",
    "Moody",
    "Morose",
    "Motivated",
    "Naive",
    "Nosy",
    "Obnoxious",
    "Old-fashioned",
    "Outgoing",
    "Outspoken",
    "Overemotional",
    "Paranoid",
    "Passive-aggressive",
    "Peaceful",
    "Pensive",
    "Philosophical",
    "Plain-speaking",
    "Playful",
    "Plucky",
    "Pompous",
    "Positive",
    "Prejudiced",
    "Pretty chill",
    "Proud",
    "Quick-tempered",
    "Reliable",
    "Reluctant",
    "Resentful",
    "Resourceful",
    "Respectful",
    "Restless",
    "Romantic",
    "Sassy",
    "Selfish",
    "Sensitive",
    "Sentimental",
    "Short-tempered",
    "Snobby",
    "Sombre",
    "Sophisticated",
    "Soulless",
    "Spiteful",
    "Stern",
    "Stoic",
    "Surly",
    "Suspicious",
    "Sweet",
    "Tactless",
    "Talented",
    "Thoughtful",
    "Unbalanced",
    "Unpredictable",
    "Unstable",
    "Warm-hearted",
    "Wary",
    "Well-intentioned",
  ],

  dclass: [
    "Accountant",
    "Administrative Assistant",
    "Engineer",
    "HR Generalist",
    "IT Specialist",
    "Temp",
  ],

  location: [
    "Alaska",
    "Amsterdam",
    "Atlanta",
    "Austin",
    "Baghdad",
    "Baltimore",
    "Barcelona",
    "Baton Rogue",
    "Beijing",
    "Berlin",
    "Bolivia",
    "Boston",
    "Boulder",
    "Budapest",
    "Calcutta",
    "Cairo",
    "Cardiff, Wales",
    "Chicago",
    "Cincinnati",
    "Columbus, Ohio",
    "Dallas",
    "Denver",
    "Des Moines",
    "Detroit",
    "Dubai",
    "El Paso",
    "Fargo, North Dakota",
    "Flagstaff",
    "Fresno",
    "Hawaii",
    "Hong Kong",
    "Houston",
    "Iceland",
    "Jackson, Mississippi",
    "Kansas City",
    "Kenya",
    "Lima, Peru",
    "London",
    "Los Angeles",
    "Los Vegas",
    "Lubbock, Texas",
    "Madrid",
    "Manilla, Philippines",
    "Memphis",
    "Mexico City",
    "Miami",
    "Milwaukee",
    "Minneapolis",
    "Moab, Utah",
    "Moldova",
    "Montreal, Canada",
    "Mumbai",
    "Munich, Germany",
    "Nashville",
    "New Jersey",
    "New York City",
    "New Zealand",
    "North Dakota",
    "Oslo, Norway",
    "Paris",
    "Paris, Texas",
    "Philadelphia",
    "Portland",
    "Ramstein, Germany",
    "Reno",
    "rural Alabama",
    "rural China",
    "rural Iowa",
    "rural Minnesota",
    "rural Montana",
    "rural Nebraska",
    "rural Utah",
    "rural Vermont",
    "Sacramento",
    "Salem, Oregon",
    "San Antonio",
    "San Diego",
    "San Francisco",
    "San Jose",
    "Scotland",
    "Seattle",
    "Seoul, Sourth Korea",
    "Sidney, Australia",
    "Singapore",
    "South Africa",
    "South Dakota",
    "São Paulo, Brazil",
    "Sweden",
    "Tokyo",
    "Toledo",
    "Tornto, Canada",
    "Tucson",
    "Tulsa",
    "upstate New York",
    "Washington, D.C.",
  ],

  backstory: [
    "acts shallow but only to hide their insecurities",
    "acts younger than they are, but not in a good way",
    "always gets sloppy drunk at office parties",
    "always gives the bad news first",
    "always gives the good news first",
    "always has Skinny Cow ice cream in the fridge and goes to Zumba once a week",
    "always invites people to Toastmasters",
    "always keeps their promises",
    "always looks bored",
    "always looks hungover",
    "always looks relaxed",
    "always looks tired",
    "always looks their best",
    "always lies when asked what they are doing this weekend",
    "always shows up late",
    "always skips out early",
    "always speaks very formally",
    "always needs to be the centre of attention",
    'always refers to inanimate objects as "she"',
    "always speaks in the third person",
    "always thinks outside the box",
    "always wanted to be an artist",
    "always wants to talk about their weekend",
    'always wears Converses and only listens to "real" hip-hop',
    "argues with their spouse on the phone every day",
    "became a grandparent at 36",
    "believes in an eye for an eye",
    'believes in "dress for success"',
    "brings in amazing baked goods all the time but never eats them",
    'clearly partied hard when they were young and still thinks of themself as "cool"',
    "clears their throat all day long",
    "collects those creepy porcelain dolls",
    "collects vinyl, quit cigarettes but still bums them",
    "dresses like they are 20 years older than they are",
    "dresses like they are 20 years younger than they are",
    "drives a red Mustang and spends their tax return in Vegas",
    'dropped out of college after a month but got a "degree in life" after backpacking in Costa Rica for 2 weeks',
    "follows 3000 people on Instagram and claims they can get you backstage at any show",
    "follows every sport on TV",
    "from the suburbs but pretends they are from the city",
    "goes backpacking in the Summer",
    "goes to Burning Man every year",
    "has a dish of cheap candy on their desk",
    "has a dish of expensive chocolates on their desk",
    "has a dog instead of a child",
    "has a newborn and hasn't slept in weeks",
    "has a PhD in something useless",
    "has a terrible case or Resting Bitch Face, but is super nice",
    "has five cats at home",
    "has no chin",
    "has Resting Bitch Face",
    "has Seasonal Affective Disorder",
    "has the world's largest ugly sweater collection, but doesn't know it",
    "has two dogs and no kids",
    "has two drinks at lunch",
    "hasn't done any work in years",
    "is a conceited douchebag, but you have no idea why",
    "is a Christian Mom, hates rap, and has five kids",
    "is a huge drama queen",
    "is a jerk",
    "is a morning person",
    "is a wicked swing dancer, great fun at parties, but might be illiterate",
    "is always complaining about how busy they are, but they aren't",
    "is always drinking a protein shake",
    "is always having a bad day",
    "is always on the phone organization their kids soccer league",
    "is always relentlessly positive",
    "is an alcoholic and drinks a Monster before work every morning",
    "is an extreme couponer and buys porn video tapes on E-Bay",
    "is chill AF and dabs like it's their job",
    "is counting the days until retirement",
    "is in a band",
    "is fat-fit, but thinks they're regular fit",
    "is more of a night person",
    "is painfully thin",
    "is not cut out for office life",
    "is not using their college degree",
    "is really nice until you mention religion",
    "is really old-fashioned",
    "is recently divorced, smokes menthols, always asks to see the manager",
    "is married to someone WAY more attractive than them",
    "is super churchy",
    "is super nice and friendly; probably relaxed because they never do any work",
    "is technically polite, but in a really artifical fake way that is hard to trust",
    "is terrible at conversation",
    "is the poster child for Peter Pan Syndrome",
    "is too good work here",
    "is too good work here and will probably leave soon",
    "is too nice",
    "is very concerned about appearances",
    "is very concerned about politics",
    "is WAY too friendly to management",
    "looks like a hipster douchebag, but is actually really nice",
    "looks older than they are",
    "loves shopping and is deeply in debt",
    "loves underground techno and smokes roll-ups with menthol filters",
    "love Tennis and Celine Dion",
    "makes a mean caserole, racist, and already called the police",
    'married rich and is talking about "retiring" at 42',
    "married their highschool sweatheart",
    "mumbles incoherantly all the time",
    "never does any work and makes life harder for everyone around them",
    "never lets a conversation end when it should",
    "never shuts up about rock climbing",
    "only goes on vacation to Disneyland",
    "only talks to people of the opposite sex",
    "opinionated, unstable, life-time NRA member",
    "owns three rental houses and will probably retire early",
    "part-time yoga instructor, Vegan(ish), and loves Whole Foods",
    "probably has Aspergers, but is really good at their job",
    "really wants to be management",
    "rides horses and won't shut up about it",
    "repeats everything you say",
    "shares global warming articles on FB, drives a Prius, #feelthebern",
    "should have retired years ago",
    "shushes people in church",
    "smiles, but only with their mouth",
    "stills plays beer pong on the weekends",
    "stinks of Axe and Weed, plays CoD Zombies religously",
    "summers in Connecticut, and owns three horses",
    "thinks they are really smart",
    "thinks their child is a genius",
    "thinks their great at office politics, but aren't",
    "thinks their PhD makes them smart, it doesn't",
    "used to be a body builder but has settled down and had kids",
    "used to be in good shape",
    "used to be in the military, so they come in early and work harder than everyone else",
    "uses big words to sound smart",
    "was a lumber sexual before it was cool",
    "was clearly born into a rich family and doesn't need this job",
    "was really popular in high school, but is really jaded now",
    'was voted "most likely to become a serial killer" in highschool',
    "was widowed, writes $12 checks, and smells like old people",
    "went to college but doesn't seem like the educated type",
    "won't shut up about their kids",
    "won't stop talking about their kids",
    "worships martinis and everything they stand for",
    "would literally kill someone for a salad right now",
  ]
};

RPG_Char.init(DND_DATA);
<|endoftext|>


<commit_before>/*
*     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
*     S.A.Unipersonal (Telefonica I+D)
*
*     This file is part of Morfeo EzWeb Platform.
*
*     Morfeo EzWeb Platform is free software: you can redistribute it and/or modify
*     it under the terms of the GNU Affero General Public License as published by
*     the Free Software Foundation, either version 3 of the License, or
*     (at your option) any later version.
*
*     Morfeo EzWeb Platform is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU Affero General Public License for more details.
*
*     You should have received a copy of the GNU Affero General Public License
*     along with Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
*
*     Info about members and contributors of the MORFEO project
*     is available at
*
*     http://morfeo-project.org
 */

/*global Wirecloud*/

var OpManagerFactory = function () {

    // *********************************
    // SINGLETON INSTANCE
    // *********************************
    var instance = null;

    function OpManager () {

        // ****************
        // CALLBACK METHODS
        // ****************

        var loadEnvironment = function (transport) {
            // JSON-coded user tabspaces
            var response = transport.responseText;
            var workspaces = JSON.parse(response);

            for (var i = 0; i < workspaces.length; i++) {
                var workspace = workspaces[i];

                this.workspaceInstances[workspace.id] = workspace;
                if (!(workspace.creator in this.workspacesByUserAndName)) {
                    this.workspacesByUserAndName[workspace.creator] = {};
                }
                this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;
            }

            HistoryManager.init();
            var state = HistoryManager.getCurrentState();
            this.changeActiveWorkspace(this.workspacesByUserAndName[state.workspace_creator][state.workspace_name]);
        }

        var onError = function (transport, e) {
            var msg;
            try {
                msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error loading Wirecloud Platform: %(errorMsg)s."), transport, e);
                LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            } catch (e) {
                if (msg != null) {
                    alert(msg);
                } else {
                    alert (gettext("Error loading Wirecloud Platform"));
                }
            }
        }

        /*****WORKSPACE CALLBACK***/
        var createWSSuccess = function(onSuccess, response) {
            var workspace = JSON.parse(response.responseText);
            this.workspaceInstances[workspace.id] = workspace;
            this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;
            this.changeActiveWorkspace(workspace);

            if (typeof onSuccess === 'function') {
                try {
                    onSuccess(workspace);
                } catch (e) {}
            }
        };

        var createWSError = function(onFailure, response) {
            var msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error creating a workspace: %(errorMsg)s."), response);

            if (typeof onFailure === 'function') {
                try {
                    onFailure(msg);
                } catch (e) {}
            }
        };

        // *********************************
        // PRIVATE VARIABLES AND FUNCTIONS
        // *********************************

        // Singleton modules
        this.showcaseModule = null;
        this.catalogue = null;
        this.logs = null;
        this.platformPreferences = null;

        this.loadCompleted = false;

        // Variables for controlling the collection of wiring and dragboard instances of a user
        this.workspaceInstances = {};
        this.workspacesByUserAndName = {};

        this.activeWorkspace = null;

        // ****************
        // PUBLIC METHODS
        // ****************

        OpManager.prototype.mergeMashupResource = function(resource) {

            var mergeOk = function(transport) {
                LayoutManagerFactory.getInstance().logStep('');
                this.changeActiveWorkspace(this.activeWorkspace);
            }
            var mergeError = function(transport, e) {
                var layoutManager, msg;

                msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error merging workspace: %(errorMsg)s."), transport, e);

                layoutManager = LayoutManagerFactory.getInstance();
                layoutManager.logStep('');
                layoutManager._notifyPlatformReady();

                layoutManager.showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            }

            LayoutManagerFactory.getInstance()._startComplexTask(gettext("Adding the mashup"), 1);
            LayoutManagerFactory.getInstance().logSubTask(gettext("Merging with current workspace"));

            var active_ws_id = this.activeWorkspace.id;
            var mergeURL = Wirecloud.URLs.WORKSPACE_MERGE.evaluate({to_ws_id: active_ws_id});

            Wirecloud.io.makeRequest(mergeURL, {
                method: 'POST',
                contentType: 'application/json',
                requestHeaders: {'Accept': 'application/json'},
                postBody: JSON.stringify({'mashup': resource.getURI()}),
                onSuccess: mergeOk.bind(this),
                onFailure: mergeError.bind(this),
                onException: mergeError.bind(this)
            });
        };

        OpManager.prototype.addWorkspaceFromMashup = function addWorkspaceFromMashup(resource, options) {

            options = Wirecloud.Utils.merge({
                allow_renaming: true,
                dry_run: false
            }, options);

            var cloneOk = function(transport) {
                var response, wsInfo, opManager, workspace = null;

                if (transport.status === 201) {
                    response = transport.responseText;
                    wsInfo = JSON.parse(response);
                    opManager = OpManagerFactory.getInstance();
                    opManager.workspaceInstances[wsInfo.id] = workspace;
                }

                if (typeof options.onSuccess === 'function') {
                    try {
                        options.onSuccess(workspace);
                    } catch (e) {}
                }
            };

            var cloneError = function(transport, e) {
                var msg, details;

                msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error adding the workspace: %(errorMsg)s."), transport, e);

                if (typeof options.onFailure === 'function') {
                    try {
                        if (transport.status === 422) {
                            details = JSON.parse(transport.responseText).details;
                        }
                    } catch (e) {}

                    try {
                        options.onFailure(msg, details);
                    } catch (e) {}
                }
            };

            Wirecloud.io.makeRequest(Wirecloud.URLs.WORKSPACE_COLLECTION, {
                method: 'POST',
                contentType: 'application/json',
                requestHeaders: {'Accept': 'application/json'},
                postBody: JSON.stringify({
                    'allow_renaming': options.allow_renaming,
                    'mashup': resource.getURI(),
                    'dry_run': options.dry_run
                }),
                onSuccess: cloneOk.bind(this),
                onFailure: cloneError.bind(this)
            });
        };

        OpManager.prototype.showPlatformPreferences = function () {
            PreferencesManagerFactory.getInstance().show();
        }

        OpManager.prototype.changeActiveWorkspace = function changeActiveWorkspace(workspace, initial_tab) {
            var state, steps = this.activeWorkspace != null ? 2 : 1;

            LayoutManagerFactory.getInstance()._startComplexTask(gettext("Changing current workspace"), steps);

            if (this.activeWorkspace != null) {
                this.activeWorkspace.unload();
            }

            state = {
                workspace_creator: workspace.creator,
                workspace_name: workspace.name,
                view: "workspace"
            };
            if (initial_tab) {
                state.tab = initial_tab;
            }
            HistoryManager.pushState(state);

            LayoutManagerFactory.getInstance().logSubTask(gettext("Downloading workspace data"), 1);
            var workspaceUrl = Wirecloud.URLs.WORKSPACE_ENTRY.evaluate({'workspace_id': workspace.id});
            Wirecloud.io.makeRequest(workspaceUrl, {
                method: 'GET',
                requestHeaders: {'Accept': 'application/json'},
                onSuccess: function (response) {
                    var workspace_data = JSON.parse(response.responseText);
                    this.activeWorkspace = new Workspace(workspace_data);
                    this.activeWorkspace.contextManager.addCallback(function (updated_attributes) {
                        var workspace, old_name;

                        if ('name' in updated_attributes) {
                            workspace = this.workspaceInstances[this.activeWorkspace.id];
                            old_name = workspace.name;
                            delete this.workspacesByUserAndName[workspace.creator][old_name];

                            workspace.name = updated_attributes.name;
                            this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;
                        }
                    }.bind(this));

                    // FIXME
                    LayoutManagerFactory.getInstance().mainLayout.repaint();
                    LayoutManagerFactory.getInstance().header._notifyWorkspaceLoaded(this.activeWorkspace);
                    // END FIXME
                }.bind(this)
            });
        }

        OpManager.prototype.logout = function logout() {
            window.location = Wirecloud.URLs.LOGOUT_VIEW;
        }

        OpManager.prototype.addInstance = function (widget, options) {
            if (!this.loadCompleted) {
                return;
            }

            this.activeWorkspace.getVisibleTab().getDragboard().addInstance(widget, options);
        };

        OpManager.prototype.removeInstance = function (iWidgetId, orderFromServer) {
            if (!this.loadCompleted)
                return;

            this.activeWorkspace.removeIWidget(iWidgetId, orderFromServer);
        }

        /**
         * Loads the Wirecloud Platform.
         */
        OpManager.prototype.loadEnviroment = function () {
            // Init Layout Manager
            var layoutManager = LayoutManagerFactory.getInstance();
            layoutManager.resizeWrapper();
            layoutManager._startComplexTask(gettext('Loading Wirecloud Platform'), 3);
            layoutManager.logSubTask(gettext('Retrieving Wirecloud code'));
            layoutManager.logStep('');

            window.addEventListener(
                          "beforeunload",
                          this.unloadEnvironment.bind(this),
                          true);

            Wirecloud.io.makeRequest(Wirecloud.URLs.PLATFORM_CONTEXT_COLLECTION, {
                method: 'GET',
                requestHeaders: {'Accept': 'application/json'},
                onSuccess: function (transport) {
                    OpManagerFactory.getInstance().contextManager = new Wirecloud.ContextManager(this, JSON.parse(transport.responseText));
                    LayoutManagerFactory.getInstance().header._initUserMenu();
                    OpManagerFactory.getInstance().continueLoadingGlobalModules(Modules.prototype.CONTEXT);
                }
            });
        }

        /**
         * Unloads the Wirecloud Platform. This method is called, by default, when
         * the unload event is captured.
         */
        OpManager.prototype.unloadEnvironment = function() {
            var layoutManager = LayoutManagerFactory.getInstance();
            layoutManager.hideCover();
            layoutManager._startComplexTask(gettext('Unloading Wirecloud Platform'));

            if (this.activeWorkspace) {
                this.activeWorkspace.unload();
            }

            //TODO: unloadCatalogue
        }

        OpManager.prototype.iwidgetLoaded = function (iwidgetId) {
            this.activeWorkspace.iwidgetLoaded(iwidgetId);
        }

        OpManager.prototype.iwidgetUnloaded = function (iwidgetId) {
            this.activeWorkspace.iwidgetUnloaded(iwidgetId);
        }

        OpManager.prototype.checkForWidgetUpdates = function () {
            this.activeWorkspace.checkForWidgetUpdates();
        }

        OpManager.prototype.showActiveWorkspace = function (refreshMenu) {
            // TODO
        }

        OpManager.prototype.preferencesChanged = function (modifiedValues) {
            if ('language' in modifiedValues) {
                window.location.reload();
            }
        };

        OpManager.prototype.continueLoadingGlobalModules = function (module) {
            // Asynchronous load of modules
            // Each singleton module notifies OpManager it has finished loading!
            var preferencesManager;

            switch (module) {
            case Modules.prototype.CONTEXT:

                Wirecloud.io.makeRequest(Wirecloud.URLs.THEME_ENTRY.evaluate({name: this.contextManager.get('theme')}), {
                    method: 'GET',
                    requestHeaders: {'Accept': 'application/json'},
                    onSuccess: function (transport) {
                        Wirecloud.currentTheme = new Wirecloud.ui.Theme(JSON.parse(transport.responseText));
                        this.continueLoadingGlobalModules(Modules.prototype.THEME_MANAGER);
                    }.bind(this)
                });
                break;

            case Modules.prototype.THEME_MANAGER:
                this.platformPreferences = PreferencesManagerFactory.getInstance();
                break;

            case Modules.prototype.PLATFORM_PREFERENCES:
                preferencesManager = PreferencesManagerFactory.getInstance();
                preferencesManager.getPlatformPreferences().addCommitHandler(this.preferencesChanged.bind(this), 'post-commit');
                Wirecloud.LocalCatalogue.reload({
                    onSuccess: function () {
                        this.continueLoadingGlobalModules(Modules.prototype.SHOWCASE);
                    }.bind(this),
                    onFailure: function () {
                        var msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error retrieving available resources: %(errorMsg)s."), transport, e);
                        LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
                    }
                });
                break;

            case Modules.prototype.SHOWCASE:
            case Modules.prototype.CATALOGUE:
                // All singleton modules has been loaded!
                // It's time for loading tabspace information!
                this.loadActiveWorkspace();
                break;

            case Modules.prototype.ACTIVE_WORKSPACE:
                var layoutManager = LayoutManagerFactory.getInstance();
                layoutManager.logSubTask(gettext("Activating current Workspace"));

                this.showActiveWorkspace();

                layoutManager.logStep('');
                layoutManager._notifyPlatformReady();
                this.loadCompleted = true;
            }
        }

        OpManager.prototype.loadActiveWorkspace = function () {
            // Asynchronous load of modules
            // Each singleton module notifies OpManager it has finished loading!

            Wirecloud.io.makeRequest(Wirecloud.URLs.WORKSPACE_COLLECTION, {
                method: 'GET',
                requestHeaders: {'Accept': 'application/json'},
                onSuccess: loadEnvironment.bind(this),
                onFailure: onError.bind(this)
            });
        }

        OpManager.prototype.logIWidgetError = function(iWidgetId, msg, level) {
            var iWidget = this.activeWorkspace.getIWidget(iWidgetId);
            if (iWidget == null) {
                var msg2 = gettext("Some pice of code tried to notify an error in the iWidget %(iWidgetId)s when it did not exist or it was not loaded yet. This is an error in Wirecloud Platform, please notify it.\nError Message: %(errorMsg)s");
                msg2 = interpolate(msg2, {iWidgetId: iWidgetId, errorMsg: msg}, true);
                Wirecloud.GlobalLogManager.log(msg2);
                return;
            }

            iWidget.log(msg, level);
        }

        OpManager.prototype.drawAttention = function(iWidgetId) {
            this.activeWorkspace.drawAttention(iWidgetId);
        };

        //Operations on workspaces

        OpManager.prototype.workspaceExists = function (newName) {
            var workspaces;

            workspaces = Object.keys(this.workspacesByUserAndName[this.contextManager.get('username')]);
            return workspaces.indexOf(newName) !== -1;
        }

        OpManager.prototype.addWorkspace = function addWorkspace(newName, options) {
            if (options == null) {
                options = {};
            }

            Wirecloud.io.makeRequest(Wirecloud.URLs.WORKSPACE_COLLECTION, {
                method: 'POST',
                contentType: 'application/json',
                requestHeaders: {'Accept': 'application/json'},
                postBody: JSON.stringify({
                    allow_renaming: !!options.allow_renaming,
                    name: newName
                }),
                onSuccess: createWSSuccess.bind(this, options.onSuccess),
                onFailure: createWSError.bind(this, options.onFailure)
            });
        };

        OpManager.prototype.removeWorkspace = function(workspace) {
            // Removing reference
            delete this.workspacesByUserAndName[workspace.workspaceState.creator][workspace.workspaceState.name];
            delete this.workspaceInstances[workspace.id];

            // Set the first workspace as current
            var username = this.contextManager.get('username');
            this.changeActiveWorkspace(Wirecloud.Utils.values(this.workspacesByUserAndName[username])[0]);
        };

    }

    // *********************************
    // SINGLETON GET INSTANCE
    // *********************************
    return new function() {
        this.getInstance = function() {
            if (instance == null) {
                instance = new OpManager();
            }
            return instance;
        }
    }
}();

<commit_msg>Fix bug creating workspaces from catalogue<commit_after>/*
*     (C) Copyright 2008 Telefonica Investigacion y Desarrollo
*     S.A.Unipersonal (Telefonica I+D)
*
*     This file is part of Morfeo EzWeb Platform.
*
*     Morfeo EzWeb Platform is free software: you can redistribute it and/or modify
*     it under the terms of the GNU Affero General Public License as published by
*     the Free Software Foundation, either version 3 of the License, or
*     (at your option) any later version.
*
*     Morfeo EzWeb Platform is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU Affero General Public License for more details.
*
*     You should have received a copy of the GNU Affero General Public License
*     along with Morfeo EzWeb Platform.  If not, see <http://www.gnu.org/licenses/>.
*
*     Info about members and contributors of the MORFEO project
*     is available at
*
*     http://morfeo-project.org
 */

/*global Wirecloud*/

var OpManagerFactory = function () {

    // *********************************
    // SINGLETON INSTANCE
    // *********************************
    var instance = null;

    function OpManager () {

        // ****************
        // CALLBACK METHODS
        // ****************

        var loadEnvironment = function (transport) {
            // JSON-coded user tabspaces
            var response = transport.responseText;
            var workspaces = JSON.parse(response);

            for (var i = 0; i < workspaces.length; i++) {
                var workspace = workspaces[i];

                this.workspaceInstances[workspace.id] = workspace;
                if (!(workspace.creator in this.workspacesByUserAndName)) {
                    this.workspacesByUserAndName[workspace.creator] = {};
                }
                this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;
            }

            HistoryManager.init();
            var state = HistoryManager.getCurrentState();
            this.changeActiveWorkspace(this.workspacesByUserAndName[state.workspace_creator][state.workspace_name]);
        }

        var onError = function (transport, e) {
            var msg;
            try {
                msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error loading Wirecloud Platform: %(errorMsg)s."), transport, e);
                LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            } catch (e) {
                if (msg != null) {
                    alert(msg);
                } else {
                    alert (gettext("Error loading Wirecloud Platform"));
                }
            }
        }

        /*****WORKSPACE CALLBACK***/
        var createWSSuccess = function(onSuccess, response) {
            var workspace = JSON.parse(response.responseText);
            this.workspaceInstances[workspace.id] = workspace;
            this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;
            this.changeActiveWorkspace(workspace);

            if (typeof onSuccess === 'function') {
                try {
                    onSuccess(workspace);
                } catch (e) {}
            }
        };

        var createWSError = function(onFailure, response) {
            var msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error creating a workspace: %(errorMsg)s."), response);

            if (typeof onFailure === 'function') {
                try {
                    onFailure(msg);
                } catch (e) {}
            }
        };

        // *********************************
        // PRIVATE VARIABLES AND FUNCTIONS
        // *********************************

        // Singleton modules
        this.showcaseModule = null;
        this.catalogue = null;
        this.logs = null;
        this.platformPreferences = null;

        this.loadCompleted = false;

        // Variables for controlling the collection of wiring and dragboard instances of a user
        this.workspaceInstances = {};
        this.workspacesByUserAndName = {};

        this.activeWorkspace = null;

        // ****************
        // PUBLIC METHODS
        // ****************

        OpManager.prototype.mergeMashupResource = function(resource) {

            var mergeOk = function(transport) {
                LayoutManagerFactory.getInstance().logStep('');
                this.changeActiveWorkspace(this.activeWorkspace);
            }
            var mergeError = function(transport, e) {
                var layoutManager, msg;

                msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error merging workspace: %(errorMsg)s."), transport, e);

                layoutManager = LayoutManagerFactory.getInstance();
                layoutManager.logStep('');
                layoutManager._notifyPlatformReady();

                layoutManager.showMessageMenu(msg, Constants.Logging.ERROR_MSG);
            }

            LayoutManagerFactory.getInstance()._startComplexTask(gettext("Adding the mashup"), 1);
            LayoutManagerFactory.getInstance().logSubTask(gettext("Merging with current workspace"));

            var active_ws_id = this.activeWorkspace.id;
            var mergeURL = Wirecloud.URLs.WORKSPACE_MERGE.evaluate({to_ws_id: active_ws_id});

            Wirecloud.io.makeRequest(mergeURL, {
                method: 'POST',
                contentType: 'application/json',
                requestHeaders: {'Accept': 'application/json'},
                postBody: JSON.stringify({'mashup': resource.getURI()}),
                onSuccess: mergeOk.bind(this),
                onFailure: mergeError.bind(this),
                onException: mergeError.bind(this)
            });
        };

        OpManager.prototype.addWorkspaceFromMashup = function addWorkspaceFromMashup(resource, options) {

            options = Wirecloud.Utils.merge({
                allow_renaming: true,
                dry_run: false
            }, options);

            var cloneOk = function(response) {
                var workspace = null;

                if ([201, 204].indexOf(response.status) === -1) {
                    cloneError(response);
                }

                if (response.status === 201) {
                    workspace = JSON.parse(response.responseText);
                    this.workspaceInstances[workspace.id] = workspace;
                    this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;

                }

                if (typeof options.onSuccess === 'function') {
                    try {
                        options.onSuccess(workspace);
                    } catch (e) {}
                }
            };

            var cloneError = function(transport, e) {
                var msg, details;

                msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error adding the workspace: %(errorMsg)s."), transport, e);

                if (typeof options.onFailure === 'function') {
                    try {
                        if (transport.status === 422) {
                            details = JSON.parse(transport.responseText).details;
                        }
                    } catch (e) {}

                    try {
                        options.onFailure(msg, details);
                    } catch (e) {}
                }
            };

            Wirecloud.io.makeRequest(Wirecloud.URLs.WORKSPACE_COLLECTION, {
                method: 'POST',
                contentType: 'application/json',
                requestHeaders: {'Accept': 'application/json'},
                postBody: JSON.stringify({
                    'allow_renaming': options.allow_renaming,
                    'mashup': resource.getURI(),
                    'dry_run': options.dry_run
                }),
                onSuccess: cloneOk.bind(this),
                onFailure: cloneError.bind(this)
            });
        };

        OpManager.prototype.showPlatformPreferences = function () {
            PreferencesManagerFactory.getInstance().show();
        }

        OpManager.prototype.changeActiveWorkspace = function changeActiveWorkspace(workspace, initial_tab) {
            var state, steps = this.activeWorkspace != null ? 2 : 1;

            LayoutManagerFactory.getInstance()._startComplexTask(gettext("Changing current workspace"), steps);

            if (this.activeWorkspace != null) {
                this.activeWorkspace.unload();
            }

            state = {
                workspace_creator: workspace.creator,
                workspace_name: workspace.name,
                view: "workspace"
            };
            if (initial_tab) {
                state.tab = initial_tab;
            }
            HistoryManager.pushState(state);

            LayoutManagerFactory.getInstance().logSubTask(gettext("Downloading workspace data"), 1);
            var workspaceUrl = Wirecloud.URLs.WORKSPACE_ENTRY.evaluate({'workspace_id': workspace.id});
            Wirecloud.io.makeRequest(workspaceUrl, {
                method: 'GET',
                requestHeaders: {'Accept': 'application/json'},
                onSuccess: function (response) {
                    var workspace_data = JSON.parse(response.responseText);
                    this.activeWorkspace = new Workspace(workspace_data);
                    this.activeWorkspace.contextManager.addCallback(function (updated_attributes) {
                        var workspace, old_name;

                        if ('name' in updated_attributes) {
                            workspace = this.workspaceInstances[this.activeWorkspace.id];
                            old_name = workspace.name;
                            delete this.workspacesByUserAndName[workspace.creator][old_name];

                            workspace.name = updated_attributes.name;
                            this.workspacesByUserAndName[workspace.creator][workspace.name] = workspace;
                        }
                    }.bind(this));

                    // FIXME
                    LayoutManagerFactory.getInstance().mainLayout.repaint();
                    LayoutManagerFactory.getInstance().header._notifyWorkspaceLoaded(this.activeWorkspace);
                    // END FIXME
                }.bind(this)
            });
        }

        OpManager.prototype.logout = function logout() {
            window.location = Wirecloud.URLs.LOGOUT_VIEW;
        }

        OpManager.prototype.addInstance = function (widget, options) {
            if (!this.loadCompleted) {
                return;
            }

            this.activeWorkspace.getVisibleTab().getDragboard().addInstance(widget, options);
        };

        OpManager.prototype.removeInstance = function (iWidgetId, orderFromServer) {
            if (!this.loadCompleted)
                return;

            this.activeWorkspace.removeIWidget(iWidgetId, orderFromServer);
        }

        /**
         * Loads the Wirecloud Platform.
         */
        OpManager.prototype.loadEnviroment = function () {
            // Init Layout Manager
            var layoutManager = LayoutManagerFactory.getInstance();
            layoutManager.resizeWrapper();
            layoutManager._startComplexTask(gettext('Loading Wirecloud Platform'), 3);
            layoutManager.logSubTask(gettext('Retrieving Wirecloud code'));
            layoutManager.logStep('');

            window.addEventListener(
                          "beforeunload",
                          this.unloadEnvironment.bind(this),
                          true);

            Wirecloud.io.makeRequest(Wirecloud.URLs.PLATFORM_CONTEXT_COLLECTION, {
                method: 'GET',
                requestHeaders: {'Accept': 'application/json'},
                onSuccess: function (transport) {
                    OpManagerFactory.getInstance().contextManager = new Wirecloud.ContextManager(this, JSON.parse(transport.responseText));
                    LayoutManagerFactory.getInstance().header._initUserMenu();
                    OpManagerFactory.getInstance().continueLoadingGlobalModules(Modules.prototype.CONTEXT);
                }
            });
        }

        /**
         * Unloads the Wirecloud Platform. This method is called, by default, when
         * the unload event is captured.
         */
        OpManager.prototype.unloadEnvironment = function() {
            var layoutManager = LayoutManagerFactory.getInstance();
            layoutManager.hideCover();
            layoutManager._startComplexTask(gettext('Unloading Wirecloud Platform'));

            if (this.activeWorkspace) {
                this.activeWorkspace.unload();
            }

            //TODO: unloadCatalogue
        }

        OpManager.prototype.iwidgetLoaded = function (iwidgetId) {
            this.activeWorkspace.iwidgetLoaded(iwidgetId);
        }

        OpManager.prototype.iwidgetUnloaded = function (iwidgetId) {
            this.activeWorkspace.iwidgetUnloaded(iwidgetId);
        }

        OpManager.prototype.checkForWidgetUpdates = function () {
            this.activeWorkspace.checkForWidgetUpdates();
        }

        OpManager.prototype.showActiveWorkspace = function (refreshMenu) {
            // TODO
        }

        OpManager.prototype.preferencesChanged = function (modifiedValues) {
            if ('language' in modifiedValues) {
                window.location.reload();
            }
        };

        OpManager.prototype.continueLoadingGlobalModules = function (module) {
            // Asynchronous load of modules
            // Each singleton module notifies OpManager it has finished loading!
            var preferencesManager;

            switch (module) {
            case Modules.prototype.CONTEXT:

                Wirecloud.io.makeRequest(Wirecloud.URLs.THEME_ENTRY.evaluate({name: this.contextManager.get('theme')}), {
                    method: 'GET',
                    requestHeaders: {'Accept': 'application/json'},
                    onSuccess: function (transport) {
                        Wirecloud.currentTheme = new Wirecloud.ui.Theme(JSON.parse(transport.responseText));
                        this.continueLoadingGlobalModules(Modules.prototype.THEME_MANAGER);
                    }.bind(this)
                });
                break;

            case Modules.prototype.THEME_MANAGER:
                this.platformPreferences = PreferencesManagerFactory.getInstance();
                break;

            case Modules.prototype.PLATFORM_PREFERENCES:
                preferencesManager = PreferencesManagerFactory.getInstance();
                preferencesManager.getPlatformPreferences().addCommitHandler(this.preferencesChanged.bind(this), 'post-commit');
                Wirecloud.LocalCatalogue.reload({
                    onSuccess: function () {
                        this.continueLoadingGlobalModules(Modules.prototype.SHOWCASE);
                    }.bind(this),
                    onFailure: function () {
                        var msg = Wirecloud.GlobalLogManager.formatAndLog(gettext("Error retrieving available resources: %(errorMsg)s."), transport, e);
                        LayoutManagerFactory.getInstance().showMessageMenu(msg, Constants.Logging.ERROR_MSG);
                    }
                });
                break;

            case Modules.prototype.SHOWCASE:
            case Modules.prototype.CATALOGUE:
                // All singleton modules has been loaded!
                // It's time for loading tabspace information!
                this.loadActiveWorkspace();
                break;

            case Modules.prototype.ACTIVE_WORKSPACE:
                var layoutManager = LayoutManagerFactory.getInstance();
                layoutManager.logSubTask(gettext("Activating current Workspace"));

                this.showActiveWorkspace();

                layoutManager.logStep('');
                layoutManager._notifyPlatformReady();
                this.loadCompleted = true;
            }
        }

        OpManager.prototype.loadActiveWorkspace = function () {
            // Asynchronous load of modules
            // Each singleton module notifies OpManager it has finished loading!

            Wirecloud.io.makeRequest(Wirecloud.URLs.WORKSPACE_COLLECTION, {
                method: 'GET',
                requestHeaders: {'Accept': 'application/json'},
                onSuccess: loadEnvironment.bind(this),
                onFailure: onError.bind(this)
            });
        }

        OpManager.prototype.logIWidgetError = function(iWidgetId, msg, level) {
            var iWidget = this.activeWorkspace.getIWidget(iWidgetId);
            if (iWidget == null) {
                var msg2 = gettext("Some pice of code tried to notify an error in the iWidget %(iWidgetId)s when it did not exist or it was not loaded yet. This is an error in Wirecloud Platform, please notify it.\nError Message: %(errorMsg)s");
                msg2 = interpolate(msg2, {iWidgetId: iWidgetId, errorMsg: msg}, true);
                Wirecloud.GlobalLogManager.log(msg2);
                return;
            }

            iWidget.log(msg, level);
        }

        OpManager.prototype.drawAttention = function(iWidgetId) {
            this.activeWorkspace.drawAttention(iWidgetId);
        };

        //Operations on workspaces

        OpManager.prototype.workspaceExists = function (newName) {
            var workspaces;

            workspaces = Object.keys(this.workspacesByUserAndName[this.contextManager.get('username')]);
            return workspaces.indexOf(newName) !== -1;
        }

        OpManager.prototype.addWorkspace = function addWorkspace(newName, options) {
            if (options == null) {
                options = {};
            }

            Wirecloud.io.makeRequest(Wirecloud.URLs.WORKSPACE_COLLECTION, {
                method: 'POST',
                contentType: 'application/json',
                requestHeaders: {'Accept': 'application/json'},
                postBody: JSON.stringify({
                    allow_renaming: !!options.allow_renaming,
                    name: newName
                }),
                onSuccess: createWSSuccess.bind(this, options.onSuccess),
                onFailure: createWSError.bind(this, options.onFailure)
            });
        };

        OpManager.prototype.removeWorkspace = function(workspace) {
            // Removing reference
            delete this.workspacesByUserAndName[workspace.workspaceState.creator][workspace.workspaceState.name];
            delete this.workspaceInstances[workspace.id];

            // Set the first workspace as current
            var username = this.contextManager.get('username');
            this.changeActiveWorkspace(Wirecloud.Utils.values(this.workspacesByUserAndName[username])[0]);
        };

    }

    // *********************************
    // SINGLETON GET INSTANCE
    // *********************************
    return new function() {
        this.getInstance = function() {
            if (instance == null) {
                instance = new OpManager();
            }
            return instance;
        }
    }
}();

<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');

module.exports = Pages;

function Pages(conf) {
  conf = conf || {};

  this.openWord = conf.openWord || Pages.DEFAULT_OPEN_WORD;
  this.closeWord = conf.closeWord || Pages.DEFAULT_CLOSE_WORD;
  this.renderArgName = conf.renderArgName || Pages.DEFAULT_RENDER_ARG_NAME;
  this.workDir = conf.workDir && resolvePath(conf.workDir) || Pages.DEFAULT_WORK_DIR;
  this.srcPath = null;
  this.dstPath = null;
  this.name = null;

  if (conf.srcPath) {
    this.loadFileSync(conf.srcPath);
  }
}

Pages.create =
Pages.newInstance = function(conf) {
  return new Pages(conf);
};

Pages.DEFAULT_OPEN_WORD  = '<?';
Pages.DEFAULT_CLOSE_WORD = '?>';
Pages.DEFAULT_RENDER_ARG_NAME = 'arg';
Pages.DEFAULT_WORK_DIR = joinPath(__dirname, 'work');
Pages.cache = [];

Pages.prototype.reloadFileSync = function() {
  if (!this.srcPath) return;
  this.clear();
  this.loadFileSync(this.srcPath);
};

Pages.prototype.clear = function() {
  this.deleteCache();
  this.deleteModule();
};

Pages.prototype.loadFileSync = function(srcPath) {
  if (!srcPath) return;
  this.srcPath = resolvePath(srcPath);
  this.name = this.makeName(this.srcPath);
  this.dstPath = this.makeDstPath(this.workDir, this.name);
  if (this.isCached()) return;
  this.setCache(
    this.setModuleSync(
      this.createJsFileSync(
        this.parse(
          stripBOM(fs.readFileSync(this.srcPath, 'utf8'))))));
};

Pages.prototype.makeName = function(filePath) {
  return filePath && filePath.
    replace(/[\/\\]/g, '__').
    replace(/[:]/g, '-');
};

Pages.prototype.makeDstPath = function(workDir, name) {
  return joinPath(workDir, name) + '.js';
};

Pages.prototype.setCache = function(mdl, name) {
  name = name || this.name;
  if (name && mdl && mdl.render) {
    Pages.cache[name] = mdl.render;
  }
};

Pages.prototype.deleteCache = function(name) {
  name = name || this.name;
  if (name && Pages.cache[name]) {
    delete Pages.cache[name];
  }
};

Pages.prototype.isCached = function(name) {
  name = name || this.name;
  return !!Pages.cache[name];
};

Pages.prototype.setModuleSync = function(filePath) {
  filePath = filePath || this.dstPath;
  var mdl = null;
  try {
    mdl = require(filePath);
  } catch(e) {
    throw new Error(filePath + "\n" + e.stack);
  }
  return mdl;
};

Pages.prototype.deleteModule = function(filePath) {
  filePath = filePath || this.dstPath;
  if (filePath && require.cache[filePath]) {
    delete require.cache[filePath];
  }
};

Pages.prototype.createJsFileSync = function(buf, name, workDir) {
  name = name || this.name;
  workDir = workDir || this.workDir;
  if (!fs.existsSync(workDir)) {
    fs.mkdirSync(workDir, parseInt('755', 8));
  }
  var filePath = this.makeDstPath(workDir, name);
  fs.writeFileSync(filePath, buf);
  return filePath;
};

Pages.prototype.parse = function(src) {
  src = this.closeWord + src + this.openWord;

  var buf = "exports.render = function(" + this.renderArgName + "){\n  var renderStr = '';\n";
  for (var i=0, len=src.length; i<len;) {
    var start, end, str;
    start = src.indexOf(this.closeWord, i) + this.closeWord.length;
    end = src.indexOf(this.openWord, start);
    if (end == -1) break;
    str = src.substring(start, end).
      replace(/\\/g, '\\\\').
      replace(/'/g, "\\'").
      replace(/\t/g, '\\t').
      replace(/\r/g, '\\r').
      replace(/\n/g, '\\n');
    if (str != '') {
      buf += "  renderStr += '" + str + "';\n";
    }
    start = end + this.openWord.length;
    end = src.indexOf(this.closeWord, start);
    if (end == -1) break;
    str = src.substring(start, end);
    switch (str.substring(0, 1)) {
      case '-':
        buf += "  renderStr += " + str.substring(1) + ";\n";
        break;
      case '=':
        buf += "  renderStr += escape(" + str.substring(1) + ");\n";
        break;
      default:
        buf += str + "\n";
    }
    i = end;
  }
  buf += "  return renderStr;\n};\n";
  buf +=
    "function escape(val){\n" +
    "  if (val == null) {\n" +
    "    return '';\n" +
    "  } else if (typeof val == 'string') {\n" +
    "    if (!/[&\"<>]/.test(val)) return val;\n" +
    "    return val.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n" +
    "  } else {\n" +
    "    return val.toString();\n" +
    "  }\n" +
    "}\n";
  return buf;
};

Pages.prototype.render = function(arg) {
  var func = Pages.cache[this.name];
  return func ? func(arg) : '';
};

function stripBOM(dat) {
  return (dat.charCodeAt(0) === 0xFEFF) ? dat.slice(1) : dat;
}

function resolvePath(str) {
  return (str[0] == path.sep) ? str : path.resolve(str);
}

function joinPath(str1, str2) {
  return str1 + path.sep + str2;
}
<commit_msg>refactor parse method<commit_after>'use strict';
var fs = require('fs');
var path = require('path');

module.exports = Pages;

function Pages(conf) {
  conf = conf || {};

  this.openWord = conf.openWord || Pages.DEFAULT_OPEN_WORD;
  this.closeWord = conf.closeWord || Pages.DEFAULT_CLOSE_WORD;
  this.renderArgName = conf.renderArgName || Pages.DEFAULT_RENDER_ARG_NAME;
  this.workDir = conf.workDir && resolvePath(conf.workDir) || Pages.DEFAULT_WORK_DIR;
  this.srcPath = null;
  this.dstPath = null;
  this.name = null;

  if (conf.srcPath) {
    this.loadFileSync(conf.srcPath);
  }
}

Pages.create =
Pages.newInstance = function(conf) {
  return new Pages(conf);
};

Pages.DEFAULT_OPEN_WORD  = '<?';
Pages.DEFAULT_CLOSE_WORD = '?>';
Pages.DEFAULT_RENDER_ARG_NAME = 'arg';
Pages.DEFAULT_WORK_DIR = joinPath(__dirname, 'work');
Pages.cache = [];

Pages.prototype.reloadFileSync = function() {
  if (!this.srcPath) return;
  this.clear();
  this.loadFileSync(this.srcPath);
};

Pages.prototype.clear = function() {
  this.deleteCache();
  this.deleteModule();
};

Pages.prototype.loadFileSync = function(srcPath) {
  if (!srcPath) return;
  this.srcPath = resolvePath(srcPath);
  this.name = this.makeName(this.srcPath);
  this.dstPath = this.makeDstPath(this.workDir, this.name);
  if (this.isCached()) return;
  this.setCache(
    this.setModuleSync(
      this.createJsFileSync(
        this.parse(
          stripBOM(fs.readFileSync(this.srcPath, 'utf8'))))));
};

Pages.prototype.makeName = function(filePath) {
  return filePath && filePath.
    replace(/[\/\\]/g, '__').
    replace(/[:]/g, '-');
};

Pages.prototype.makeDstPath = function(workDir, name) {
  return joinPath(workDir, name) + '.js';
};

Pages.prototype.setCache = function(mdl, name) {
  name = name || this.name;
  if (name && mdl && mdl.render) {
    Pages.cache[name] = mdl.render;
  }
};

Pages.prototype.deleteCache = function(name) {
  name = name || this.name;
  if (name && Pages.cache[name]) {
    delete Pages.cache[name];
  }
};

Pages.prototype.isCached = function(name) {
  name = name || this.name;
  return !!Pages.cache[name];
};

Pages.prototype.setModuleSync = function(filePath) {
  filePath = filePath || this.dstPath;
  var mdl = null;
  try {
    mdl = require(filePath);
  } catch(e) {
    throw new Error(filePath + "\n" + e.stack);
  }
  return mdl;
};

Pages.prototype.deleteModule = function(filePath) {
  filePath = filePath || this.dstPath;
  if (filePath && require.cache[filePath]) {
    delete require.cache[filePath];
  }
};

Pages.prototype.createJsFileSync = function(buf, name, workDir) {
  name = name || this.name;
  workDir = workDir || this.workDir;
  if (!fs.existsSync(workDir)) {
    fs.mkdirSync(workDir, parseInt('755', 8));
  }
  var filePath = this.makeDstPath(workDir, name);
  fs.writeFileSync(filePath, buf);
  return filePath;
};

Pages.prototype.parse = function(src) {
  src = this.closeWord + src + this.openWord;

  var buf = "exports.render = function(" + this.renderArgName + "){\n  var __rs = '';\n";
  for (var i=0, len=src.length; i<len;) {
    var start, end, str;
    start = src.indexOf(this.closeWord, i) + this.closeWord.length;
    end = src.indexOf(this.openWord, start);
    if (end == -1) break;
    str = src.substring(start, end).
      replace(/\\/g, '\\\\').
      replace(/'/g, "\\'").
      replace(/\t/g, '\\t').
      replace(/\r/g, '\\r').
      replace(/\n/g, '\\n');
    if (str != '') {
      buf += "  __rs += '" + str + "';\n";
    }
    start = end + this.openWord.length;
    end = src.indexOf(this.closeWord, start);
    if (end == -1) break;
    str = src.substring(start, end);
    switch (str.substring(0, 1)) {
      case '-':
        buf += "  __rs += " + str.substring(1) + ";\n";
        break;
      case '=':
        buf += "  __rs += escape(" + str.substring(1) + ");\n";
        break;
      default:
        buf += str + "\n";
    }
    i = end;
  }
  buf += "  return __rs;\n};\n";
  buf +=
    "function escape(val){\n" +
    "  if (val == null) {\n" +
    "    return '';\n" +
    "  } else if (typeof val == 'string') {\n" +
    "    if (!/[&\"<>]/.test(val)) return val;\n" +
    "    return val.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n" +
    "  } else {\n" +
    "    return val.toString();\n" +
    "  }\n" +
    "}\n";
  return buf;
};

Pages.prototype.render = function(arg) {
  var func = Pages.cache[this.name];
  return func ? func(arg) : '';
};

function stripBOM(dat) {
  return (dat.charCodeAt(0) === 0xFEFF) ? dat.slice(1) : dat;
}

function resolvePath(str) {
  return (str[0] == path.sep) ? str : path.resolve(str);
}

function joinPath(str1, str2) {
  return str1 + path.sep + str2;
}
<|endoftext|>


<commit_before>/*
Language: PowerShell
Author: David Mohundro <david@mohundro.com>
Contributors: Nicholas Blumhardt <nblumhardt@nblumhardt.com>, Victor Zhou <OiCMudkips@users.noreply.github.com>
*/

function(hljs) {
  var BACKTICK_ESCAPE = {
    begin: '`[\\s\\S]',
    relevance: 0
  };
  var VAR = {
    className: 'variable',
    variants: [
      {begin: /\$[\w\d][\w\d_:]*/}
    ]
  };
  var LITERAL = {
    className: 'literal',
    begin: /\$(null|true|false)\b/
  };
  var QUOTE_STRING = {
    className: 'string',
    variants: [
      { begin: /"/, end: /"/ },
      { begin: /@"/, end: /^"@/ }
    ],
    contains: [
      BACKTICK_ESCAPE,
      VAR,
      {
        className: 'variable',
        begin: /\$[A-z]/, end: /[^A-z]/
      }
    ]
  };
  var APOS_STRING = {
    className: 'string',
    variants: [
      { begin: /'/, end: /'/ },
      { begin: /@'/, end: /^'@/ }
    ]
  };

  var PS_HELPTAGS = {
    className: 'doctag',
    variants: [
      /* no paramater help tags */
      { begin: '\\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)' },
      /* one parameter help tags */
      { begin: '\\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\\w+\\S+' }
    ]
  };

  var PS_COMMENT = hljs.inherit(
    hljs.COMMENT(null, null),
    {
      variants: [
        /* single-line comment */
        { begin: /#/, end: /$/ },
        /* multi-line comment */
        { begin: /<#/, end: /#>/ }
      ],
      contains: [PS_HELPTAGS]
    }
  );

  return {
    aliases: ['ps'],
    lexemes: /-?[A-z\.\-]+/,
    case_insensitive: true,
    keywords: {
      keyword: 'if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch',
      built_in: 'Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning',
      nomarkup: '-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace'
    },
    contains: [
      BACKTICK_ESCAPE,
      hljs.NUMBER_MODE,
      QUOTE_STRING,
      APOS_STRING,
      LITERAL,
      VAR,
      PS_COMMENT
    ]
  };
}
<commit_msg>fix whitespace detection<commit_after>/*
Language: PowerShell
Author: David Mohundro <david@mohundro.com>
Contributors: Nicholas Blumhardt <nblumhardt@nblumhardt.com>, Victor Zhou <OiCMudkips@users.noreply.github.com>
*/

function(hljs) {
  var BACKTICK_ESCAPE = {
    begin: '`[\\s\\S]',
    relevance: 0
  };
  var VAR = {
    className: 'variable',
    variants: [
      {begin: /\$[\w\d][\w\d_:]*/}
    ]
  };
  var LITERAL = {
    className: 'literal',
    begin: /\$(null|true|false)\b/
  };
  var QUOTE_STRING = {
    className: 'string',
    variants: [
      { begin: /"/, end: /"/ },
      { begin: /@"/, end: /^"@/ }
    ],
    contains: [
      BACKTICK_ESCAPE,
      VAR,
      {
        className: 'variable',
        begin: /\$[A-z]/, end: /[^A-z]/
      }
    ]
  };
  var APOS_STRING = {
    className: 'string',
    variants: [
      { begin: /'/, end: /'/ },
      { begin: /@'/, end: /^'@/ }
    ]
  };

  var PS_HELPTAGS = {
    className: 'doctag',
    variants: [
      /* no paramater help tags */
      { begin: '\\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)' },
      /* one parameter help tags */
      { begin: '\\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\\s+\\S+' }
    ]
  };

  var PS_COMMENT = hljs.inherit(
    hljs.COMMENT(null, null),
    {
      variants: [
        /* single-line comment */
        { begin: /#/, end: /$/ },
        /* multi-line comment */
        { begin: /<#/, end: /#>/ }
      ],
      contains: [PS_HELPTAGS]
    }
  );

  return {
    aliases: ['ps'],
    lexemes: /-?[A-z\.\-]+/,
    case_insensitive: true,
    keywords: {
      keyword: 'if else foreach return function do while until elseif begin for trap data dynamicparam end break throw param continue finally in switch exit filter try process catch',
      built_in: 'Add-Content Add-History Add-Member Add-PSSnapin Clear-Content Clear-Item Clear-Item Property Clear-Variable Compare-Object ConvertFrom-SecureString Convert-Path ConvertTo-Html ConvertTo-SecureString Copy-Item Copy-ItemProperty Export-Alias Export-Clixml Export-Console Export-Csv ForEach-Object Format-Custom Format-List Format-Table Format-Wide Get-Acl Get-Alias Get-AuthenticodeSignature Get-ChildItem Get-Command Get-Content Get-Credential Get-Culture Get-Date Get-EventLog Get-ExecutionPolicy Get-Help Get-History Get-Host Get-Item Get-ItemProperty Get-Location Get-Member Get-PfxCertificate Get-Process Get-PSDrive Get-PSProvider Get-PSSnapin Get-Service Get-TraceSource Get-UICulture Get-Unique Get-Variable Get-WmiObject Group-Object Import-Alias Import-Clixml Import-Csv Invoke-Expression Invoke-History Invoke-Item Join-Path Measure-Command Measure-Object Move-Item Move-ItemProperty New-Alias New-Item New-ItemProperty New-Object New-PSDrive New-Service New-TimeSpan New-Variable Out-Default Out-File Out-Host Out-Null Out-Printer Out-String Pop-Location Push-Location Read-Host Remove-Item Remove-ItemProperty Remove-PSDrive Remove-PSSnapin Remove-Variable Rename-Item Rename-ItemProperty Resolve-Path Restart-Service Resume-Service Select-Object Select-String Set-Acl Set-Alias Set-AuthenticodeSignature Set-Content Set-Date Set-ExecutionPolicy Set-Item Set-ItemProperty Set-Location Set-PSDebug Set-Service Set-TraceSource Set-Variable Sort-Object Split-Path Start-Service Start-Sleep Start-Transcript Stop-Process Stop-Service Stop-Transcript Suspend-Service Tee-Object Test-Path Trace-Command Update-FormatData Update-TypeData Where-Object Write-Debug Write-Error Write-Host Write-Output Write-Progress Write-Verbose Write-Warning',
      nomarkup: '-ne -eq -lt -gt -ge -le -not -like -notlike -match -notmatch -contains -notcontains -in -notin -replace'
    },
    contains: [
      BACKTICK_ESCAPE,
      hljs.NUMBER_MODE,
      QUOTE_STRING,
      APOS_STRING,
      LITERAL,
      VAR,
      PS_COMMENT
    ]
  };
}
<|endoftext|>


<commit_before>function emailFormHandler() {
  var sendEmailBtn = document.getElementById('squatch-send-email');
  var emailInput = document.getElementById('squatch-user-email');

  handleClicks(sendEmailBtn, function() {
    if (!isValidEmail(emailInput.value)) {
      my_addClass(emailInput, 'invalid');
      emailInput.onkeypress = function() {
        if (isValidEmail(this.value)) {
          my_removeClass(this, 'invalid');
          my_addClass(this, 'valid');
        }
      }
    } else {
      my_removeClass(emailInput, 'invalid');

      if (window.frameElement && window.frameElement.squatchJsApi) {
        var widget = window.frameElement.squatchJsApi;

        if (window.parent.squatch && window.parent.squatch.widgets().eventBus) {
          window.parent.squatch.widgets().eventBus.dispatch('submit_email', this, widget, emailInput.value);
        } else {
          window.frameElement.squatchJsApi.reload(emailInput.value);
        }
      }
    }
  });
}

function messengerHandler() {
  var messengerBtn = document.getElementsByClassName('messengerShare')[0];

  if (!messengerBtn) return;

  var messengerUrl = 'https://www.facebook.com/dialog/send?app_id=' + squatch.user.facebook.appId + '&link=' + squatch.user.facebook.link + '&redirect_uri=' + squatch.user.facebook.redirectUrl;
  messengerBtn.href = messengerUrl;

  handleClicks(messengerBtn, function(e) {
    // If it's not mobile, don't use href link
    if (e.type != 'touchstart') {
      e.preventDefault();

      var url = messengerUrl + "&display=popup";
      window.open(url, 'fb-messenger', 'status=0,width=620,height=400');
    }

    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'MESSENGER');
    }
  });
}

function smsHandler() {
  var smsBtn = document.getElementsByClassName('smsShare')[0];

  if (!smsBtn) return;

  // Test url
  var smsUrl = 'sms:?&body=bodytext';
  smsBtn.href = smsUrl;

  var md = new MobileDetect('Version/4.0 Mobile Safari/534.30');
  var UA = md.userAgent();

  if (UA === 'Safari') {
    smsBtn.target = '_parent';
  }
}

function facebookHandler() {
  var facebookBtn = document.getElementsByClassName('fbShare')[0];

  if (!facebookBtn) return;

  var pictureString = (squatch.user.facebook.shareImage == "" || squatch.user.facebook.shareImage === null) ? "" : "&picture="+squatch.user.facebook.shareImage;
  var fbUrl = "https://www.facebook.com/dialog/feed?app_id=" + squatch.user.facebook.appId + "&link=" + squatch.user.facebook.link + "&name=" + squatch.user.facebook.title + "&description=" + squatch.user.facebook.summary + pictureString+ "&redirect_uri=" + squatch.user.facebook.redirectUrl;
  facebookBtn.href = fbUrl;

  handleClicks(facebookBtn, function(e) {
    // If it's not mobile, don't use href link
    if (e.type != 'touchstart') {
      e.preventDefault();

      var url = fbUrl + "&display=popup";
      window.open(url, 'fb', 'status=0,width=620,height=400');
    }

    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'FACEBOOK');
    }
  });
}

function twitterHandler() {
  var twitterBtn = document.getElementsByClassName('twShare')[0];
  var twUrl = "https://twitter.com/intent/tweet?source=webclient&text=" + squatch.user.twitter.message;

  if (!twitterBtn) return;
  twitterBtn.href = twUrl;

  handleClicks(twitterBtn, function(e) {
    if (e.type != 'touchstart') {
      e.preventDefault();
      window.open(twUrl, 'twitter', 'status=1,width=575,height=400');
    }

    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'TWITTER');
    }
  });
}

function emailHandler() {
  var emailBtn = document.getElementsByClassName('emailShare')[0];
  var emailUrl = squatch.user.email.share.mailToLink;

  if(!emailBtn) return;
  // emailBtn.href = emailUrl;

  var md = new MobileDetect('Version/4.0 Mobile Safari/534.30');
  var UA = md.userAgent();

  emailBtn.href = emailUrl;

  if (UA === 'Safari') {
    emailBtn.target = '_parent';
  } else {
    handleClicks(emailBtn, function(e) {
      if (e.type != 'touchstart') {
        e.preventDefault();

        var mailurl = emailUrl;
        mailTo(mailurl);
      }

      if (window.frameElement && window.frameElement.squatchJsApi) {
        window.frameElement.squatchJsApi._shareEvent(window.squatch, 'EMAIL');
      }
    });
  }
}
<commit_msg>JC - add analytics to new buttons<commit_after>function emailFormHandler() {
  var sendEmailBtn = document.getElementById('squatch-send-email');
  var emailInput = document.getElementById('squatch-user-email');

  handleClicks(sendEmailBtn, function() {
    if (!isValidEmail(emailInput.value)) {
      my_addClass(emailInput, 'invalid');
      emailInput.onkeypress = function() {
        if (isValidEmail(this.value)) {
          my_removeClass(this, 'invalid');
          my_addClass(this, 'valid');
        }
      }
    } else {
      my_removeClass(emailInput, 'invalid');

      if (window.frameElement && window.frameElement.squatchJsApi) {
        var widget = window.frameElement.squatchJsApi;

        if (window.parent.squatch && window.parent.squatch.widgets().eventBus) {
          window.parent.squatch.widgets().eventBus.dispatch('submit_email', this, widget, emailInput.value);
        } else {
          window.frameElement.squatchJsApi.reload(emailInput.value);
        }
      }
    }
  });
}

function messengerHandler() {
  var messengerBtn = document.getElementsByClassName('messengerShare')[0];

  if (!messengerBtn) return;

  var messengerUrl = 'https://www.facebook.com/dialog/send?app_id=' + squatch.user.facebook.appId + '&link=' + squatch.user.facebook.link + '&redirect_uri=' + squatch.user.facebook.redirectUrl;
  messengerBtn.href = messengerUrl;

  handleClicks(messengerBtn, function(e) {
    // If it's not mobile, don't use href link
    if (e.type != 'touchstart') {
      e.preventDefault();

      var url = messengerUrl + "&display=popup";
      window.open(url, 'fb-messenger', 'status=0,width=620,height=400');
    }

    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'MESSENGER');
    }
  });
}

function smsHandler() {
  var smsBtn = document.getElementsByClassName('smsShare')[0];

  if (!smsBtn) return;

  // Test url
  var smsUrl = 'sms:?&body=bodytext';
  smsBtn.href = smsUrl;

  var md = new MobileDetect('Version/4.0 Mobile Safari/534.30');
  var UA = md.userAgent();

  if (UA === 'Safari') {
    smsBtn.target = '_parent';
  }

  handleClicks(smsBtn, function(e) {
    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'SMS');
    }
  });
}

function facebookHandler() {
  var facebookBtn = document.getElementsByClassName('fbShare')[0];

  if (!facebookBtn) return;

  var pictureString = (squatch.user.facebook.shareImage == "" || squatch.user.facebook.shareImage === null) ? "" : "&picture="+squatch.user.facebook.shareImage;
  var fbUrl = "https://www.facebook.com/dialog/feed?app_id=" + squatch.user.facebook.appId + "&link=" + squatch.user.facebook.link + "&name=" + squatch.user.facebook.title + "&description=" + squatch.user.facebook.summary + pictureString+ "&redirect_uri=" + squatch.user.facebook.redirectUrl;
  facebookBtn.href = fbUrl;

  handleClicks(facebookBtn, function(e) {
    // If it's not mobile, don't use href link
    if (e.type != 'touchstart') {
      e.preventDefault();

      var url = fbUrl + "&display=popup";
      window.open(url, 'fb', 'status=0,width=620,height=400');
    }

    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'FACEBOOK');
    }
  });
}

function twitterHandler() {
  var twitterBtn = document.getElementsByClassName('twShare')[0];
  var twUrl = "https://twitter.com/intent/tweet?source=webclient&text=" + squatch.user.twitter.message;

  if (!twitterBtn) return;
  twitterBtn.href = twUrl;

  handleClicks(twitterBtn, function(e) {
    if (e.type != 'touchstart') {
      e.preventDefault();
      window.open(twUrl, 'twitter', 'status=1,width=575,height=400');
    }

    if (window.frameElement && window.frameElement.squatchJsApi) {
      window.frameElement.squatchJsApi._shareEvent(window.squatch, 'TWITTER');
    }
  });
}

function emailHandler() {
  var emailBtn = document.getElementsByClassName('emailShare')[0];
  var emailUrl = squatch.user.email.share.mailToLink;

  if(!emailBtn) return;
  // emailBtn.href = emailUrl;

  var md = new MobileDetect('Version/4.0 Mobile Safari/534.30');
  var UA = md.userAgent();

  emailBtn.href = emailUrl;

  if (UA === 'Safari') {
    emailBtn.target = '_parent';

    handleClicks(emailBtn, function(e) {
      if (window.frameElement && window.frameElement.squatchJsApi) {
        window.frameElement.squatchJsApi._shareEvent(window.squatch, 'EMAIL');
      }
    });
  } else {
    handleClicks(emailBtn, function(e) {
      if (e.type != 'touchstart') {
        e.preventDefault();

        var mailurl = emailUrl;
        mailTo(mailurl);
      }

      if (window.frameElement && window.frameElement.squatchJsApi) {
        window.frameElement.squatchJsApi._shareEvent(window.squatch, 'EMAIL');
      }
    });
  }
}
<|endoftext|>


<commit_before>import React from "react"
import { roundingNumber } from "../../utils/converter"
import BLOCKCHAIN_INFO from "../../../../env"
import { Link } from 'react-router-dom'
import ReactTooltip from 'react-tooltip'
import {CopyToClipboard} from 'react-copy-to-clipboard'
import AnalyzeLogModal from './AnalyzeLogModal'

const TransactionLoadingView = (props) => {
  if (props.broadcasting) {
    var classPending = !props.error ? " pulse" : ""
    return (

                <Link to="/exchange" className={props.type === "exchange" ? "disable" : ""}>{props.translate("transaction.exchange") || "Exchange"}</Link>
                <Link to="/transfer" className={props.type === "transfer" ? "disable" : ""}>{props.translate("transaction.transfer") || "Transfer"}</Link>

              {props.error?
                props.translate("error.failed") || 'Failed!'
                : props.translate("transaction.broadcasting") || 'Broadcasting'}

                {!props.error &&

{props.translate("transaction.broadcasting_blockchain") || "Broadcasting the transaction to the blockchain"}

                }
                {props.error &&

{props.translate("transaction.cound_not_broadcast") || "Couldn't broadcast your transaction to the blockchain"}

{props.error}

                }

                  {!props.error ?  : }

              {props.type === "exchange"?
                props.translate("transaction.new_ex") || "New exchange"
                : props.translate("transaction.new_tx") || "New transfer"}

    )
  }

  var handleAnalyze = (e) => {
    props.analyze.action(e)
    props.toogleModal()
  }

  var getTooltipCopy = () => {
    return props.isCopied ?
      (props.translate("transaction.copied") || "Copied!") :
      (props.translate("transaction.copy_tx") || "Copy transaction hash")
  }

  var classPending = props.status === "pending" ? " pulse" : ""
  var analyzeBtn = ""

  if (props.type === "exchange") {
    analyzeBtn = (
       handleAnalyze(e)}>
        {props.translate('transaction.analyze') || "Show reasons"}

    )
  }
  return (

              <Link to="/exchange" className={props.type === "exchange" ? "disable" : ""}>{props.translate("transaction.exchange") || "Exchange"}</Link>
              <Link to="/transfer" className={props.type === "transfer" ? "disable" : ""}>{props.translate("transaction.transfer") || "Transfer"}</Link>

              {props.status === "success" && (props.translate('transaction.done') || "Done!")}
              {props.status === "failed" && (props.translate('transaction.failed') || "Failed!")}
              {props.status === "pending" && (props.translate('transaction.broadcasted') || "Broadcasted")}

              {props.translate("transaction.transaction") || "Transaction"}

                {props.txHash.slice(0, 12)} ... {props.txHash.slice(-10)}

                <CopyToClipboard text={props.txHash}>

                </CopyToClipboard>

              <ReactTooltip getContent={[() => getTooltipCopy()]} place="bottom" id="copy-tx-tip" type="light"/>

              {props.status === "success" &&

                    {props.type === "exchange" &&
                      (props.translate("transaction.success_ex_msg", {source: props.balanceInfo.sourceSymbol, dest: props.balanceInfo.destSymbol})
                      ||`Successfully exchanged from ${props.balanceInfo.sourceSymbol} to ${props.balanceInfo.destSymbol}`)
                    }
                    {props.type === "transfer" &&
                      (props.translate("transaction.success_tx_msg", {token: props.balanceInfo.tokenSymbol, address: props.address}) ||
                      `Successfully transferred ${props.balanceInfo.tokenSymbol} to ${props.address}`)
                    }

                  {props.type === "exchange" &&

                        {props.balanceInfo.sourceSymbol}
                        {roundingNumber(props.balanceInfo.sourceAmount.prevValue)}

                        {roundingNumber(props.balanceInfo.sourceAmount.nextValue)}

                        {props.balanceInfo.destSymbol}
                        {roundingNumber(props.balanceInfo.destAmount.prevValue)}

                        {roundingNumber(props.balanceInfo.destAmount.nextValue)}

                  }
                  {props.type === "transfer" &&

                        {props.balanceInfo.tokenSymbol}
                        {roundingNumber(props.balanceInfo.amount.prev)}

                        {roundingNumber(props.balanceInfo.amount.next)}

                  }

              }
              {props.status === "failed" &&

                    {props.translate("transaction.transaction_error") || "Transaction error"}

                  {/*
{props.translate(props.error) || "Warning! Error encountered during contract execution"}
 */}
                  {analyzeBtn}
                  <AnalyzeLogModal analyze={props.analyze}
                    onRequestClose={props.toogleModal}
                    isOpen={props.isOpenModal}
                    translate={props.translate}
                  />
                  {/* {props.type==="exchange" && (

                      props.analyze.action(e)}>Analyze

                  )} */}

              }
              {props.status === "pending" &&

{props.translate("transaction.waiting_transaction") || "Waiting for your transaction to be mined"}

              }

            {classPending != "" ? (

                  {!props.error ?  : }

            ) : ''
            }

            {props.type === "exchange"?
                props.translate("transaction.new_ex") || "New exchange"
                : props.translate("transaction.new_tx") || "New transfer"}

  )
}

export default TransactionLoadingView
<commit_msg>fix position of tolltip<commit_after>import React from "react"
import { roundingNumber } from "../../utils/converter"
import BLOCKCHAIN_INFO from "../../../../env"
import { Link } from 'react-router-dom'
import ReactTooltip from 'react-tooltip'
import {CopyToClipboard} from 'react-copy-to-clipboard'
import AnalyzeLogModal from './AnalyzeLogModal'

const TransactionLoadingView = (props) => {
  if (props.broadcasting) {
    var classPending = !props.error ? " pulse" : ""
    return (

                <Link to="/exchange" className={props.type === "exchange" ? "disable" : ""}>{props.translate("transaction.exchange") || "Exchange"}</Link>
                <Link to="/transfer" className={props.type === "transfer" ? "disable" : ""}>{props.translate("transaction.transfer") || "Transfer"}</Link>

              {props.error?
                props.translate("error.failed") || 'Failed!'
                : props.translate("transaction.broadcasting") || 'Broadcasting'}

                {!props.error &&

{props.translate("transaction.broadcasting_blockchain") || "Broadcasting the transaction to the blockchain"}

                }
                {props.error &&

{props.translate("transaction.cound_not_broadcast") || "Couldn't broadcast your transaction to the blockchain"}

{props.error}

                }

                  {!props.error ?  : }

              {props.type === "exchange"?
                props.translate("transaction.new_ex") || "New exchange"
                : props.translate("transaction.new_tx") || "New transfer"}

    )
  }

  var handleAnalyze = (e) => {
    props.analyze.action(e)
    props.toogleModal()
  }

  var getTooltipCopy = () => {
    return props.isCopied ?
      (props.translate("transaction.copied") || "Copied!") :
      (props.translate("transaction.copy_tx") || "Copy transaction hash")
  }

  var classPending = props.status === "pending" ? " pulse" : ""
  var analyzeBtn = ""

  if (props.type === "exchange") {
    analyzeBtn = (
       handleAnalyze(e)}>
        {props.translate('transaction.analyze') || "Show reasons"}

    )
  }
  return (

              <Link to="/exchange" className={props.type === "exchange" ? "disable" : ""}>{props.translate("transaction.exchange") || "Exchange"}</Link>
              <Link to="/transfer" className={props.type === "transfer" ? "disable" : ""}>{props.translate("transaction.transfer") || "Transfer"}</Link>

              {props.status === "success" && (props.translate('transaction.done') || "Done!")}
              {props.status === "failed" && (props.translate('transaction.failed') || "Failed!")}
              {props.status === "pending" && (props.translate('transaction.broadcasted') || "Broadcasted")}

              {props.translate("transaction.transaction") || "Transaction"}

                {props.txHash.slice(0, 12)} ... {props.txHash.slice(-10)}

                <CopyToClipboard text={props.txHash}>

                </CopyToClipboard>

              <ReactTooltip getContent={[() => getTooltipCopy()]} place="right" id="copy-tx-tip" type="light"/>

              {props.status === "success" &&

                    {props.type === "exchange" &&
                      (props.translate("transaction.success_ex_msg", {source: props.balanceInfo.sourceSymbol, dest: props.balanceInfo.destSymbol})
                      ||`Successfully exchanged from ${props.balanceInfo.sourceSymbol} to ${props.balanceInfo.destSymbol}`)
                    }
                    {props.type === "transfer" &&
                      (props.translate("transaction.success_tx_msg", {token: props.balanceInfo.tokenSymbol, address: props.address}) ||
                      `Successfully transferred ${props.balanceInfo.tokenSymbol} to ${props.address}`)
                    }

                  {props.type === "exchange" &&

                        {props.balanceInfo.sourceSymbol}
                        {roundingNumber(props.balanceInfo.sourceAmount.prevValue)}

                        {roundingNumber(props.balanceInfo.sourceAmount.nextValue)}

                        {props.balanceInfo.destSymbol}
                        {roundingNumber(props.balanceInfo.destAmount.prevValue)}

                        {roundingNumber(props.balanceInfo.destAmount.nextValue)}

                  }
                  {props.type === "transfer" &&

                        {props.balanceInfo.tokenSymbol}
                        {roundingNumber(props.balanceInfo.amount.prev)}

                        {roundingNumber(props.balanceInfo.amount.next)}

                  }

              }
              {props.status === "failed" &&

                    {props.translate("transaction.transaction_error") || "Transaction error"}

                  {/*
{props.translate(props.error) || "Warning! Error encountered during contract execution"}
 */}
                  {analyzeBtn}
                  <AnalyzeLogModal analyze={props.analyze}
                    onRequestClose={props.toogleModal}
                    isOpen={props.isOpenModal}
                    translate={props.translate}
                  />
                  {/* {props.type==="exchange" && (

                      props.analyze.action(e)}>Analyze

                  )} */}

              }
              {props.status === "pending" &&

{props.translate("transaction.waiting_transaction") || "Waiting for your transaction to be mined"}

              }

            {classPending != "" ? (

                  {!props.error ?  : }

            ) : ''
            }

            {props.type === "exchange"?
                props.translate("transaction.new_ex") || "New exchange"
                : props.translate("transaction.new_tx") || "New transfer"}

  )
}

export default TransactionLoadingView
<|endoftext|>