<commit_before>var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  init: function() {
    this.templates = [];
    this.config = {};

    this.config.availableFeatures = [
      {name: 'Directive', value: 'directive', suffix: '.directive'},
      {name: 'Service', value: 'service', suffix: '.service'},
      {name: 'Factory', value: 'factory', suffix: '.factory'},
      {name: 'Filter', value: 'filter', suffix: '.filter'},
      {name: 'Template', value: 'template', suffix: '.template'}
    ];

    this.hasFeature = function(feature) {
      return this.config.features.indexOf(feature) > -1;
    }

    this.validators = {};
    this.validators.isRequired = function (input, message) {
      if (/.+/.test(input)) {
        return true;
      }
      return message;
    };

  },
  promptUser: function() {
    var done = this.async();

    var prompts = [
      {
        type: 'input',
        name: 'NAMESPACE',
        message: 'Namespace',
        default: 'ng',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'You must specify a namespace');
        }.bind(this)
      },
      {
        type: 'input',
        name: 'name',
        message: 'Component / Module name (e.g. component-name)',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'You must specify a component / module name');
        }.bind(this)
      },
      {
        type: 'input',
        name: 'description',
        message: 'Description'
      },
      {
        type: 'input',
        name: 'keywords',
        message: 'Keywords (comma-separated)'
      },
      {
        type: 'input',
        name: 'authorName',
        message: 'Author\'s name',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'Please enter your name');
        }.bind(this),
        default: this.user.git.name
      },
      {
        type: 'input',
        name: 'authorEmail',
        message: 'Author\'s email',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'Please enter your email address');
        }.bind(this),
        default: this.user.git.email
      },
      {
        type: 'input',
        name: 'homepage',
        message: 'Homepage',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'Please enter a URL');
        }.bind(this)
      },
      {
        type: 'input',
        name: 'gitRepoUrl',
        message: 'GIT Repo. URL'
      },
      {
        type: 'checkbox',
        name: 'features',
        message: 'Please choose what which items you\'d like scaffold for',
        choices: this.config.availableFeatures
      }
    ];

    this.prompt(prompts, function(props) {
      this.config = this._.extend(this.config, props);
      done();
    }.bind(this));
  },

  configure: function() {

    var now                   = new Date();
    this.config.prefix        = 'angular';
    this.config.year          = now.getFullYear();

    this.config.NAMESPACE     = this._.dasherize(this.config.NAMESPACE);
    this.config.name          = this._.dasherize(this.config.name);

    this.config.moduleName    = this.config.NAMESPACE + '.' + this.config.name;

    this.config.projectName   = this._.slugify(this.config.prefix) + '-' +
                                this.config.moduleName;

    this.config.componentName = this._.camelize(this.config.NAMESPACE + '_' +
                                  this._.camelize(
                                    this._.underscored(this.config.name)));

    this.config.dependencies  = [];

    this.config.availableFeatures.forEach(function(feature) {
      if(this.hasFeature(feature.value)) {
        this.config.dependencies.push(this.config.moduleName +  feature.suffix);
      }
    }.bind(this));

  },
  scaffoldFolders: function() {
    this.mkdir('src');
    this.mkdir('tests');
  },
  prepareTemplates: function() {

    this.templates.push({
      src: '_package.json',
      dest: 'package.json'
    });

    this.templates.push({
      src: '_bower.json',
      dest: 'bower.json'
    });

    this.templates.push({
      src: '_.travis.yml',
      dest: '.travis.yml'
    });

    this.templates.push({
      src: '_README.md',
      dest: 'README.md'
    });

    this.templates.push({
      src: '_CONTRIBUTING.md',
      dest: 'CONTRIBUTING.md'
    });

    this.templates.push({
      src: '_LICENSE',
      dest: 'LICENSE'
    });

    this.templates.push({
      src: '_Gruntfile.js',
      dest: 'Gruntfile.js'
    });

    this.templates.push({
      src: '_karma.conf.js',
      dest: 'karma.conf.js'
    });

    this.config.availableFeatures.forEach(function (feature) {
      if (this.hasFeature(feature.value)) {
        if (feature.value === 'template') {
          this.templates.push({
            src: 'src/_directive.tpl.html',
            dest: 'src/' + this.config.name + feature.suffix + '.tpl.html'
          });
        } else {
          this.templates.push({
            src: 'src/_' + feature.value + '.js',
            dest: 'src/' + this.config.name + feature.suffix + '.js'
          });

          this.templates.push({
            src: 'tests/unit/_' + feature.value + '.spec.js',
            dest: 'tests/unit/' + this.config.name + feature.suffix + '.spec.js'
          });
        }
      }
    }.bind(this));

    this.templates.push({
      src: 'src/_index.js',
      dest: 'src/index.js'
    });

    this.templates.push({
      src: '_.jscsrc',
      dest: '.jscsrc'
    });

    this.templates.push({
      src: '_.jshintrc',
      dest: '.jshintrc'
    });

    this.templates.push({
      src: '_.gitignore',
      dest: '.gitignore'
    });

    this.templates.push({
      src: '_CHANGELOG.md',
      dest: 'CHANGELOG.md'
    });
  },
  copyTemplates: function() {
    this.templates.forEach(function(template) {
      try {
        this.fs.copyTpl(
          this.templatePath(template.src),
          this.destinationPath(template.dest),
          {
            config: this.config,
            hasFeature: this.hasFeature
          }
        );
      } catch(x) {
        console.log(x, this.templatePath(template.src));
      }
    }.bind(this));
  }
});
<commit_msg>feat(component/index.js): remove namespace default<commit_after>var generators = require('yeoman-generator');

module.exports = generators.Base.extend({
  init: function() {
    this.templates = [];
    this.config = {};

    this.config.availableFeatures = [
      {name: 'Directive', value: 'directive', suffix: '.directive'},
      {name: 'Service', value: 'service', suffix: '.service'},
      {name: 'Factory', value: 'factory', suffix: '.factory'},
      {name: 'Filter', value: 'filter', suffix: '.filter'},
      {name: 'Template', value: 'template', suffix: '.template'}
    ];

    this.hasFeature = function(feature) {
      return this.config.features.indexOf(feature) > -1;
    }

    this.validators = {};
    this.validators.isRequired = function (input, message) {
      if (/.+/.test(input)) {
        return true;
      }
      return message;
    };

  },
  promptUser: function() {
    var done = this.async();

    var prompts = [
      {
        type: 'input',
        name: 'NAMESPACE',
        message: 'Namespace',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'You must specify a namespace');
        }.bind(this)
      },
      {
        type: 'input',
        name: 'name',
        message: 'Component / Module name (e.g. component-name)',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'You must specify a component / module name');
        }.bind(this)
      },
      {
        type: 'input',
        name: 'description',
        message: 'Description'
      },
      {
        type: 'input',
        name: 'keywords',
        message: 'Keywords (comma-separated)'
      },
      {
        type: 'input',
        name: 'authorName',
        message: 'Author\'s name',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'Please enter your name');
        }.bind(this),
        default: this.user.git.name
      },
      {
        type: 'input',
        name: 'authorEmail',
        message: 'Author\'s email',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'Please enter your email address');
        }.bind(this),
        default: this.user.git.email
      },
      {
        type: 'input',
        name: 'homepage',
        message: 'Homepage',
        validate: function (input) {
          return this.validators
                  .isRequired(input, 'Please enter a URL');
        }.bind(this)
      },
      {
        type: 'input',
        name: 'gitRepoUrl',
        message: 'GIT Repo. URL'
      },
      {
        type: 'checkbox',
        name: 'features',
        message: 'Please choose what which items you\'d like scaffold for',
        choices: this.config.availableFeatures
      }
    ];

    this.prompt(prompts, function(props) {
      this.config = this._.extend(this.config, props);
      done();
    }.bind(this));
  },

  configure: function() {

    var now                   = new Date();
    this.config.prefix        = 'angular';
    this.config.year          = now.getFullYear();

    this.config.NAMESPACE     = this._.dasherize(this.config.NAMESPACE);
    this.config.name          = this._.dasherize(this.config.name);

    this.config.moduleName    = this.config.NAMESPACE + '.' + this.config.name;

    this.config.projectName   = this._.slugify(this.config.prefix) + '-' +
                                this.config.moduleName;

    this.config.componentName = this._.camelize(this.config.NAMESPACE + '_' +
                                  this._.camelize(
                                    this._.underscored(this.config.name)));

    this.config.dependencies  = [];

    this.config.availableFeatures.forEach(function(feature) {
      if(this.hasFeature(feature.value)) {
        this.config.dependencies.push(this.config.moduleName +  feature.suffix);
      }
    }.bind(this));

  },
  scaffoldFolders: function() {
    this.mkdir('src');
    this.mkdir('tests');
  },
  prepareTemplates: function() {

    this.templates.push({
      src: '_package.json',
      dest: 'package.json'
    });

    this.templates.push({
      src: '_bower.json',
      dest: 'bower.json'
    });

    this.templates.push({
      src: '_.travis.yml',
      dest: '.travis.yml'
    });

    this.templates.push({
      src: '_README.md',
      dest: 'README.md'
    });

    this.templates.push({
      src: '_CONTRIBUTING.md',
      dest: 'CONTRIBUTING.md'
    });

    this.templates.push({
      src: '_LICENSE',
      dest: 'LICENSE'
    });

    this.templates.push({
      src: '_Gruntfile.js',
      dest: 'Gruntfile.js'
    });

    this.templates.push({
      src: '_karma.conf.js',
      dest: 'karma.conf.js'
    });

    this.config.availableFeatures.forEach(function (feature) {
      if (this.hasFeature(feature.value)) {
        if (feature.value === 'template') {
          this.templates.push({
            src: 'src/_directive.tpl.html',
            dest: 'src/' + this.config.name + feature.suffix + '.tpl.html'
          });
        } else {
          this.templates.push({
            src: 'src/_' + feature.value + '.js',
            dest: 'src/' + this.config.name + feature.suffix + '.js'
          });

          this.templates.push({
            src: 'tests/unit/_' + feature.value + '.spec.js',
            dest: 'tests/unit/' + this.config.name + feature.suffix + '.spec.js'
          });
        }
      }
    }.bind(this));

    this.templates.push({
      src: 'src/_index.js',
      dest: 'src/index.js'
    });

    this.templates.push({
      src: '_.jscsrc',
      dest: '.jscsrc'
    });

    this.templates.push({
      src: '_.jshintrc',
      dest: '.jshintrc'
    });

    this.templates.push({
      src: '_.gitignore',
      dest: '.gitignore'
    });

    this.templates.push({
      src: '_CHANGELOG.md',
      dest: 'CHANGELOG.md'
    });
  },
  copyTemplates: function() {
    this.templates.forEach(function(template) {
      try {
        this.fs.copyTpl(
          this.templatePath(template.src),
          this.destinationPath(template.dest),
          {
            config: this.config,
            hasFeature: this.hasFeature
          }
        );
      } catch(x) {
        console.log(x, this.templatePath(template.src));
      }
    }.bind(this));
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import classnames from "classnames";
import enabledLocales from '../data/locales.js';

var MenuLink = React.createClass({
  onClick: function() {
    this.props.activate(this.props.item);
  },
  render: function() {
    var className = classnames(`nav-link`, {
      "active": this.props.active === this.props.item
    });

    return (
      {this.props.children}
    );
  }
});

var ScrollNav = React.createClass({
  contextTypes: {
    intl: React.PropTypes.object
  },
  getInitialState: function() {
    var active = ``;

    return {active};
  },
  componentDidMount: function() {
    document.addEventListener(`scroll`, this.onScroll);
  },
  componentWillUnmount: function() {
    document.removeEventListener(`scroll`, this.onScroll);
  },
  onScroll: function() {
    var links = [].slice.call(document.querySelectorAll(`.nav-anchor`));
    var hash = window.location.hash.replace(`#`, ``);
    var active = ``;
    var scrollY = window.scrollY;

    if (links[0]) {
      active = links[0].getAttribute(`id`);
    }

    // If we have no hash, we should set it to the top nav.
    // We can stop checking.
    if (hash) {

      // Check to see which is the current nav item.
      links.forEach((element) => {
        if (scrollY >= element.offsetTop - ( window.innerHeight / 2 )) {
          active = element.getAttribute(`id`);
        }
      });

      // If we're at the bottom of the page, ensure the last item is active.
      // This is in case the last item's height is less than the window height.
      if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        active = links[links.length-1].getAttribute(`id`);
      }
    }

    this.activate(active);
  },
  activate: function(active) {
    var hash = window.location.hash.replace(`#`, ``);

    if (this.state.active !== active) {
      if (!hash || document.querySelector(`.nav-anchor#` + hash)) {
        window.history.replaceState({}, null, `#` + active);
      }
      this.setState({
        active: active || ``
      });
    }
  },
  render: function() {
    var links = [
      {
        text: this.context.intl.formatMessage({id: `nav_copyright_campaign2`}),
        item: `about`,
        link: `#about`
      },
      {
        text: this.context.intl.formatMessage({id: `nav_get_involved2`}),
        item: `get-involved`,
        link: `#get-involved`
      }
    ];
    if (/^(en)(\b|$)/.test(this.context.intl.locale)) {
      links.splice(1, 0, {
        text: `More Resources`,
        item: `resources`,
        link: `/resources`
      });
    }
    return (
      <SimpleNav activate={this.activate} active={this.state.active}
        links={links}
      />
    );
  }
});

var SimpleNav = React.createClass({
  contextTypes: {
    intl: React.PropTypes.object
  },
  render: function() {
    var active = this.props.active || ``;
    var activate = this.props.activate || function() {};
    return (

          {
            this.props.links.map((linkObj, index) => {
              return (
                <MenuLink key={index}
                  activate={activate}
                  active={active}
                  item={linkObj.item}
                  href={linkObj.link}
                >
                  {linkObj.text}
                </MenuLink>
              );
            })
          }

            <select>
            {
              Object.keys(enabledLocales).map(function(locale, index) {
                var localeName = enabledLocales[locale];

                if (locale == "fr") {
                  return (
                    <option value={locale} selected="" lang={locale}>{localeName}</option>
                  );
                } else {
                  return (
                    <option value={locale} lang={locale}>{localeName}</option>
                  );
                }
              })
            }
            </select>

    );
  }
});

module.exports = {
  SimpleNav,
  ScrollNav
};
<commit_msg>Working poc<commit_after>import React from 'react';
import classnames from "classnames";
import enabledLocales from '../data/locales.js';

var MenuLink = React.createClass({
  onClick: function() {
    this.props.activate(this.props.item);
  },
  render: function() {
    var className = classnames(`nav-link`, {
      "active": this.props.active === this.props.item
    });

    return (
      {this.props.children}
    );
  }
});

var ScrollNav = React.createClass({
  contextTypes: {
    intl: React.PropTypes.object
  },
  getInitialState: function() {
    var active = ``;

    return {active};
  },
  componentDidMount: function() {
    document.addEventListener(`scroll`, this.onScroll);
  },
  componentWillUnmount: function() {
    document.removeEventListener(`scroll`, this.onScroll);
  },
  onScroll: function() {
    var links = [].slice.call(document.querySelectorAll(`.nav-anchor`));
    var hash = window.location.hash.replace(`#`, ``);
    var active = ``;
    var scrollY = window.scrollY;

    if (links[0]) {
      active = links[0].getAttribute(`id`);
    }

    // If we have no hash, we should set it to the top nav.
    // We can stop checking.
    if (hash) {

      // Check to see which is the current nav item.
      links.forEach((element) => {
        if (scrollY >= element.offsetTop - ( window.innerHeight / 2 )) {
          active = element.getAttribute(`id`);
        }
      });

      // If we're at the bottom of the page, ensure the last item is active.
      // This is in case the last item's height is less than the window height.
      if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        active = links[links.length-1].getAttribute(`id`);
      }
    }

    this.activate(active);
  },
  activate: function(active) {
    var hash = window.location.hash.replace(`#`, ``);

    if (this.state.active !== active) {
      if (!hash || document.querySelector(`.nav-anchor#` + hash)) {
        window.history.replaceState({}, null, `#` + active);
      }
      this.setState({
        active: active || ``
      });
    }
  },
  render: function() {
    var links = [
      {
        text: this.context.intl.formatMessage({id: `nav_copyright_campaign2`}),
        item: `about`,
        link: `#about`
      },
      {
        text: this.context.intl.formatMessage({id: `nav_get_involved2`}),
        item: `get-involved`,
        link: `#get-involved`
      }
    ];
    if (/^(en)(\b|$)/.test(this.context.intl.locale)) {
      links.splice(1, 0, {
        text: `More Resources`,
        item: `resources`,
        link: `/resources`
      });
    }
    return (
      <SimpleNav activate={this.activate} active={this.state.active}
        links={links}
      />
    );
  }
});

var options = [
  {
      description: 'This is option A',
      code: 'a'
  },
  {
      description: 'This is option B',
      code: 'b'
  },
  {
      description: 'This is option C',
      code: 'c'
  },
  {
      description: 'This is option D',
      code: 'd'
  }
];

var dropDownOnChange = function(change) {
  alert('onChangeForSelect:\noldValue: ' +
          change.oldValue +
          '\nnewValue: '
          + change.newValue);
};

var SimpleNav = React.createClass({
  contextTypes: {
    intl: React.PropTypes.object
  },
  render: function() {
    var active = this.props.active || ``;
    var activate = this.props.activate || function() {};
    return (

          {
            this.props.links.map((linkObj, index) => {
              return (
                <MenuLink key={index}
                  activate={activate}
                  active={active}
                  item={linkObj.item}
                  href={linkObj.link}
                >
                  {linkObj.text}
                </MenuLink>
              );
            })
}

            {
    <Dropdown id='myDropdown'
              options={options}
              value='b'
              labelField='description'
              valueField='code'
              onChange={dropDownOnChange}/>
            }

    );
  }
});

var Dropdown = React.createClass({

    propTypes: {
        id: React.PropTypes.string.isRequired,
        options: React.PropTypes.array.isRequired,
        value: React.PropTypes.oneOfType(
            [
                React.PropTypes.number,
                React.PropTypes.string
            ]
        ),
        valueField: React.PropTypes.string,
        labelField: React.PropTypes.string,
        onChange: React.PropTypes.func
    },

    getDefaultProps: function() {
        return {
            value: null,
            valueField: 'value',
            labelField: 'label',
            onChange: null
        };
    },

    getInitialState: function() {
        var selected = this.getSelectedFromProps(this.props);
        return {
            selected: selected
        }
    },

    componentWillReceiveProps: function(nextProps) {
        var selected = this.getSelectedFromProps(nextProps);
        this.setState({
           selected: selected
        });
    },

    getSelectedFromProps(props) {
        var selected;
        if (props.value === null && props.options.length !== 0) {
            selected = props.options[0][props.valueField];
        } else {
            selected = props.value;
        }
        return selected;
    },

    render: function() {
        var self = this;
        var options = self.props.options.map(function(option) {
            return (
                <option key={option[self.props.valueField]} value={option[self.props.valueField]}>
                    {option[self.props.labelField]}
                </option>
            )
        });
        return (
            <select id={this.props.id}
                    className='form-control'
                    value={this.state.selected}
                    onChange={this.handleChange}>
                {options}
            </select>
        )
    },

    handleChange: function(e) {
        if (this.props.onChange) {
            var change = {
              oldValue: this.state.selected,
              newValue: e.target.value
            }
            this.props.onChange(change);
        }
        this.setState({selected: e.target.value});
    }

});

module.exports = {
  SimpleNav,
  ScrollNav
};
<|endoftext|>


<commit_before>/**
 * Created by break_000 on 12/05/2016.
 */
/**
 * Created by break_000 on 09/05/2016.
 */

createJSON = function(corpo, res, tipologia){
    var campiComuni = "\"makeWith\" : \"QML\",\"language\" : " + "it" + ",";
    var jsonKey;
    if(corpo.hasOwnProperty('keywords')){
        jsonKey = "\"keywords\" : [ ";
        count = 0;
        for(key in corpo.keywords){
            count++;
        }
        i = 1;
        for(key in corpo.keywords){
            if(i == count){
                jsonKey = jsonKey + "\"" + key.getElementsByName('keywords') + "\"";
            }
            else{
                jsonKey = jsonKey + "\"" + key.getElementsByName('keywords') + "\" ,";
            }
            i++;
        }
        jsonKey = jsonKey + "],";
    }
    var jsonStatistic = "\"level\" : 500, \"totalAnswers\" : 0, \"correctAnswers\" : 0})"

    if(tipologia == "veroFalso") {
        var jsonString = createJsonVF(corpo, res);
    }
    else if(tipologia ==  "rispostaMultipla"){
        var jsonString = createJSONrispostaMultipla(corpo);
    }
    else if(tipologia == "ordinamentoStringhe"){
        var jsonString = createJSONordinamentoStringhe(corpo);
    }
    else if(tipologia == "collegamentoElementi"){
        var jsonString = createJSONcollegamentoElementi(corpo);
    }
    else if(tipologia == "ordinamentoImmagini"){
        var jsonString = createJSONordinamentoImmagini(corpo);
    }
    else if(tipologia == "areaCliccabile"){
        var jsonStirng = createJSONareaCliccabile(corpo);
    }
    else if(tipologia == "riempimentoSpaziVuoti"){
        var jsonString = createJSONriepimentoSpaziVuoti(corpo);
    }
    else if(tipologia == "custom"){
        var jsonString = createJSONcustom(corpo);
    }

    jsonString = campiComuni + jsonString +  jsonStatistic;
    console.log("jsonString: " + jsonString);
}

createJsonVF = function(corpo, res){
    var jsonString = "\"question\":[{\"type\" : \"veroFalso\"" + ",";
    if(corpo.hasOwnProperty('image')){
        jsonString =  jsonString + "\"image\" : " + corpo.image + ",";
    }
    jsonString = jsonString + "\"answers\" : [{\"text\" :" + corpo.answers.text + ",";
    jsonString = jsonString + "\"isItRight : \"" + corpo.answers.isItRight + "}]}],";
    return jsonString;
}

createJSONrispostaMultipla = function(corpo){
    var jsonString = "\"question\":[{\"type\" : \"rispostaMultipla\"" + ",";
    if(corpo.hasOwnProperty('image')){
        jsonString = jsonString + "\"image\" : " + corpo.url + ",";
    }
    if(corpo.hasOwnProperty('questionText')) {
        jsonString = jsonString + "\"questionText\" : " + corpo.questionText + ",";
    }
    jsonString = jsonString + "\"answers\" : [{";
    count = 0;
    for(key in corpo.keywords){
        count++;
    }
    var i = 1;
    for(key in corpo.answer){
        if(key.hasOwnProperty('text')){
            jsonString = jsonString + "\"text\" : " + key.getElementsByName('text') + ",";
        }
        if(key.hasOwnProperty('url')){
            jsonString = jsonString + "\"url\" :" + key.getElementsByName('url') + ",";
        }
        if(key.hasOwnProperty('isItRight')){
            jsonString = jsonString + "\"isItRight\" : " + key.getElementsByName('isItRight');
        }
        if(i == count) {
            jsonString = jsonString + "}";
        }
        else{
            jsonString = jsonString + "},";
        }
        i++;
    }
    jsonString = jsonString + "],}]";
    return jsonString;
}

createJSONordinamentoStringhe = function(corpo){

}

createJSONcollegamentoElementi = function(corpo){

}

createJSONordinamentoImmagini = function(corpo){

}

createJSONareaCliccabile = function(corpo){

}

createJSONriepimentoSpaziVuoti = function(corpo){

}

createJSONcustom = function(corpo){

}<commit_msg>update editor QML<commit_after>/**
 * Created by break_000 on 12/05/2016.
 */
/**
 * Created by break_000 on 09/05/2016.
 */

createJSON = function(corpo, res, tipologia){
    var campiComuni = "\"makeWith\" : \"QML\",\"language\" : " + "it" + ",";
    var jsonKey;
    if(corpo.hasOwnProperty('keywords')){
        jsonKey = "\"keywords\" : [ ";
        count = 0;
        for(key in corpo.keywords){
            count++;
        }
        i = 1;
        for(key in corpo.keywords){
            if(i == count){
                jsonKey = jsonKey + "\"" + key.getElementsByName('keywords') + "\"";
            }
            else{
                jsonKey = jsonKey + "\"" + key.getElementsByName('keywords') + "\" ,";
            }
            i++;
        }
        jsonKey = jsonKey + "],";
    }
    var jsonStatistic = "\"level\" : 500, \"totalAnswers\" : 0, \"correctAnswers\" : 0})"

    if(tipologia == "veroFalso") {
        var jsonString = createJsonVF(corpo, res);
    }
    else if(tipologia ==  "rispostaMultipla"){
        var jsonString = createJSONrispostaMultipla(corpo);
    }
    else if(tipologia == "ordinamentoStringhe"){
        var jsonString = createJSONordinamentoStringhe(corpo);
    }
    else if(tipologia == "collegamentoElementi"){
        var jsonString = createJSONcollegamentoElementi(corpo);
    }
    else if(tipologia == "ordinamentoImmagini"){
        var jsonString = createJSONordinamentoImmagini(corpo);
    }
    else if(tipologia == "areaCliccabile"){
        var jsonStirng = createJSONareaCliccabile(corpo);
    }
    else if(tipologia == "riempimentoSpaziVuoti"){
        var jsonString = createJSONriepimentoSpaziVuoti(corpo);
    }
    else if(tipologia == "custom"){
        var jsonString = createJSONcustom(corpo);
    }

    jsonString = campiComuni + jsonString +  jsonStatistic;
    console.log("jsonString: " + jsonString);
}

createJsonVF = function(corpo, res){
    var jsonString = "\"question\":[{\"type\" : \"veroFalso\"" + ",";
    if(corpo.hasOwnProperty('image')){
        jsonString =  jsonString + "\"image\" : " + corpo.image + ",";
    }
    jsonString = jsonString + "\"answers\" : [{\"text\" :" + corpo.answers.text + ",";
    jsonString = jsonString + "\"isItRight : \"" + corpo.answers.isItRight + "}]}],";
    return jsonString;
}

createJSONrispostaMultipla = function(corpo){
    var jsonString = "\"question\":[{\"type\" : \"rispostaMultipla\"" + ",";
    if(corpo.hasOwnProperty('image')){
        jsonString = jsonString + "\"image\" : " + corpo.url + ",";
    }
    if(corpo.hasOwnProperty('questionText')) {
        jsonString = jsonString + "\"questionText\" : " + corpo.questionText + ",";
    }
    jsonString = jsonString + "\"answers\" : [{";
    count = 0;
    for(key in corpo.keywords){
        count++;
    }
    var i = 1;
    for(key in corpo.answer){
        if(key.hasOwnProperty('text')){
            jsonString = jsonString + "\"text\" : " + key.getElementsByName('text') + ",";
        }
        if(key.hasOwnProperty('url')){
            jsonString = jsonString + "\"url\" :" + key.getElementsByName('url') + ",";
        }
        if(key.hasOwnProperty('isItRight')){
            jsonString = jsonString + "\"isItRight\" : " + key.getElementsByName('isItRight');
        }
        if(i == count) {
            jsonString = jsonString + "}";
        }
        else{
            jsonString = jsonString + "},";
        }
        i++;
    }
    jsonString = jsonString + "],}]";
    return jsonString;
}

createJSONordinamentoStringhe = function(corpo){
    var jsonString = "\"question\" : [{ \"type\" : \"ordinamentoStringhe\" ,";
    if(corpo.hasOwnProperty('questionText')){
        jsonString = jsonString + "\"questionText\" : " + corpo.questionText + ",";
    }
    if(corpo.hasOwnProperty('image')){
        jsonString = jsonString + "\"image\" : " + corpo.image + ",";
    }
    jsonString = jsonString + "\"answers\" : [{"
    var count = 0;
    for(key in corpo.answer){
        count++;
    }
    var i = 1;
    for(key in corpo.answer){
        jsonString = jsonString + "\"text\" : " + key.getElementsByName('text') + ",";
        jsonString = jsonString + "\"position\" : " + key.getElementsByName('position');
        if(i == count){
            jsonString = jsonString + "}]";
        }
        else{
            jsonString = jsonString + "},";
        }
        i++;
    }
}

createJSONcollegamentoElementi = function(corpo){

}

createJSONordinamentoImmagini = function(corpo){

}

createJSONareaCliccabile = function(corpo){

}

createJSONriepimentoSpaziVuoti = function(corpo){

}

createJSONcustom = function(corpo){

}<|endoftext|>


<commit_before>import React from 'react';

export default React.createClass({
    render() {
        return

;
    },

    componentDidMount() {
        /* global global */
        const maps = global.window.google.maps;

        new maps.Map(this.getDOMNode(), {
            zoom: 7,
            center: {lat: 46.8348, lng: 8.21745}
        });
    }
});
<commit_msg>Try maps.LatLng<commit_after>import React from 'react';

export default React.createClass({
    render() {
        return

;
    },

    componentDidMount() {
        /* global global */
        const maps = global.window.google.maps;

        new maps.Map(this.getDOMNode(), {
            zoom: 7,
            center: new maps.LatLng(46.8348, 8.21745)
        });
    }
});
<|endoftext|>


<commit_before>/*
 * Directives for the NIPAP AngularJS app
 */

var nipapAppDirectives = angular.module('nipapApp.directives', []);

nipapAppDirectives.directive('nipapPoolSelector', function ($http) {

	return {
		restrict: 'AE',
		templateUrl: '/templates/pool_selector.html',
		scope: {
			selected_pool: '=selectedPool'
		},
		link: function (scope, elem, attrs) {
			// Fetch Pools from backend
			$http.get('/xhr/list_pool')
				.success(function (data) {
					if (data.hasOwnProperty('error')) {
						showDialogNotice('Error', data.message);
					} else {
						scope.pools = data;
					}
				})
				.error(function (data, stat) {
					var msg = data || "Unknown failure";
					showDialogNotice('Error', stat + ': ' + msg);
				});

			/*
			 * A pool is selected
			 */
			scope.selectPool = function (pool) {
				scope.selected_pool = pool;
			}
		}
	};

});

nipapAppDirectives.directive('nipapPoolSelectorPopup', function ($http) {

	return {
		restrict: 'AE',
		templateUrl: '/templates/pool_selector_popup.html',
		scope: {
			selected_pool: '=selectedPool'
		},
		link: function (scope, elem, attr) {

			scope.query_string = '';
			scope.pools = [];
			scope.query_id = 0;
			scope.popup_open = false;

			/*
			 * Fetch pools
			 */
			$http.get('/xhr/list_pool')
				.success(function (data) {
					if (data.hasOwnProperty('error')) {
						showDialogNotice('Error', data.message);
					} else {
						scope.pools = data;
					}
				})
				.error(function (data, stat) {
					var msg = data || "Unknown failure";
					showDialogNotice('Error', stat + ': ' + msg);
				});

			/*
			 * A pool is selected
			 */
			scope.selectPool = function (pool) {

				// Set pool & close popup
				scope.selected_pool = pool;
				scope.popup_open = false;

			}

			/*
			 * Run when popup menu is toggled
			 */
			scope.toggled = function (open) {
				if (open) {
					// If menu was opened, place focus on text input field
					$('input[name="pool_search_string"]').focus();
				}
			}
		}
	};
});

nipapAppDirectives.directive('nipapVrfSelector', function ($http, $timeout) {

	return {
		restrict: 'AE',
		templateUrl: '/templates/vrf_selector.html',
		scope: {
			selected_vrf: '=selectedVrf'
		},
		link: function (scope, elem, attr) {

			scope.query_string = '';
			scope.timeout_promise = null;
			scope.search_result = [];
			scope.query_id = 0;
			scope.popup_open = false;

			/*
			 * Function to run when VRF search query string has changed.
			 * Waits 200 ms for further changes to the query string to let the
			 * user finish typing before sending the query.
			 */
			scope.vrfQueryStringChanged = function () {
				// cancel earlier timeout if it exists
				if (scope.timeout_promise !== null) {
					$timeout.cancel(scope.timeout_promise);
				}
				scope.timeout_promise = $timeout(scope.performVRFSearch, 200);
			}

			/*
			 * Perform VRF search
			 */
			scope.performVRFSearch = function () {

				var search_q = {
					'query_id': scope.query_id,
					'query_string': $.trim(scope.query_string),
					'max_result': 10,
					'offset': 0
				};

				// If search string empty, search for default VRF
				if (search_q['query_string'] == '') {
					search_q['vrf_id'] = 0;
				}

				$http.get('/xhr/smart_search_vrf', { 'params': search_q })
					.success(scope.receiveVRFSearchResult)
					.error(function (data, stat) {
						var msg = data || "Unknown failure";
						showDialogNotice('Error', stat + ': ' + msg);
					});

				scope.query_id += 1;

			}

			/*
			 * Search result returned
			 */
			scope.receiveVRFSearchResult = function (data) {
				if (data.hasOwnProperty('error')) {
					showDialogNotice('Error', data.message);
					return;
				}

				// Verify that received response is for latest query
				if (parseInt(data.search_options.query_id) != scope.query_id - 1) {
					return;
				}

				scope.search_result = data.result;

			}

			/*
			 * A VRF is selected
			 */
			scope.selectVRF = function (vrf) {

				// set VRF & close popup
				scope.selected_vrf = vrf;
				scope.popup_open = false;

			}

			/*
			 * Run when popup menu is toggled
			 */
			scope.toggled = function (open) {
				if (open) {
					// If menu was opened, place focus on text input field
					$('input[name="vrf_search_string"]').focus();
				}
			}

			// Perform search (with empty query string) to fetch default VRF
			scope.performVRFSearch();

		}
	};
});
<commit_msg>www-ui: Fix focus on query boxes after ng upgrade<commit_after>/*
 * Directives for the NIPAP AngularJS app
 */

var nipapAppDirectives = angular.module('nipapApp.directives', []);

nipapAppDirectives.directive('nipapPoolSelector', function ($http) {

	return {
		restrict: 'AE',
		templateUrl: '/templates/pool_selector.html',
		scope: {
			selected_pool: '=selectedPool'
		},
		link: function (scope, elem, attrs) {
			// Fetch Pools from backend
			$http.get('/xhr/list_pool')
				.success(function (data) {
					if (data.hasOwnProperty('error')) {
						showDialogNotice('Error', data.message);
					} else {
						scope.pools = data;
					}
				})
				.error(function (data, stat) {
					var msg = data || "Unknown failure";
					showDialogNotice('Error', stat + ': ' + msg);
				});

			/*
			 * A pool is selected
			 */
			scope.selectPool = function (pool) {
				scope.selected_pool = pool;
			}
		}
	};

});

nipapAppDirectives.directive('nipapPoolSelectorPopup', function ($http, $timeout) {

	return {
		restrict: 'AE',
		templateUrl: '/templates/pool_selector_popup.html',
		scope: {
			selected_pool: '=selectedPool'
		},
		link: function (scope, elem, attr) {

			scope.query_string = '';
			scope.pools = [];
			scope.query_id = 0;
			scope.popup_open = false;

			/*
			 * Fetch pools
			 */
			$http.get('/xhr/list_pool')
				.success(function (data) {
					if (data.hasOwnProperty('error')) {
						showDialogNotice('Error', data.message);
					} else {
						scope.pools = data;
					}
				})
				.error(function (data, stat) {
					var msg = data || "Unknown failure";
					showDialogNotice('Error', stat + ': ' + msg);
				});

			/*
			 * A pool is selected
			 */
			scope.selectPool = function (pool) {

				// Set pool & close popup
				scope.selected_pool = pool;
				scope.popup_open = false;

			}

			/*
			 * Run when popup menu is toggled
			 */
			scope.toggled = function (open) {
				if (open) {
					// If menu was opened, place focus on text input field
					$timeout(function () {
						$('input[name="pool_search_string"]').focus();
					});
				}
			}
		}
	};
});

nipapAppDirectives.directive('nipapVrfSelector', function ($http, $timeout) {

	return {
		restrict: 'AE',
		templateUrl: '/templates/vrf_selector.html',
		scope: {
			selected_vrf: '=selectedVrf'
		},
		link: function (scope, elem, attr) {

			scope.query_string = '';
			scope.timeout_promise = null;
			scope.search_result = [];
			scope.query_id = 0;
			scope.popup_open = false;

			/*
			 * Function to run when VRF search query string has changed.
			 * Waits 200 ms for further changes to the query string to let the
			 * user finish typing before sending the query.
			 */
			scope.vrfQueryStringChanged = function () {
				// cancel earlier timeout if it exists
				if (scope.timeout_promise !== null) {
					$timeout.cancel(scope.timeout_promise);
				}
				scope.timeout_promise = $timeout(scope.performVRFSearch, 200);
			}

			/*
			 * Perform VRF search
			 */
			scope.performVRFSearch = function () {

				var search_q = {
					'query_id': scope.query_id,
					'query_string': $.trim(scope.query_string),
					'max_result': 10,
					'offset': 0
				};

				// If search string empty, search for default VRF
				if (search_q['query_string'] == '') {
					search_q['vrf_id'] = 0;
				}

				$http.get('/xhr/smart_search_vrf', { 'params': search_q })
					.success(scope.receiveVRFSearchResult)
					.error(function (data, stat) {
						var msg = data || "Unknown failure";
						showDialogNotice('Error', stat + ': ' + msg);
					});

				scope.query_id += 1;

			}

			/*
			 * Search result returned
			 */
			scope.receiveVRFSearchResult = function (data) {
				if (data.hasOwnProperty('error')) {
					showDialogNotice('Error', data.message);
					return;
				}

				// Verify that received response is for latest query
				if (parseInt(data.search_options.query_id) != scope.query_id - 1) {
					return;
				}

				scope.search_result = data.result;

			}

			/*
			 * A VRF is selected
			 */
			scope.selectVRF = function (vrf) {

				// set VRF & close popup
				scope.selected_vrf = vrf;
				scope.popup_open = false;

			}

			/*
			 * Run when popup menu is toggled
			 */
			scope.toggled = function (open) {
				if (open) {
					// If menu was opened, place focus on text input field
					$timeout(function () {
						$('input[name="vrf_search_string"]').focus();
					});
				}
			}

			// Perform search (with empty query string) to fetch default VRF
			scope.performVRFSearch();

		}
	};
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'

function SEO({
  description,
  lang,
  meta,
  keywords,
  title,
  slug,
  featuredImageName,
}) {
  return (
    <StaticQuery
      query={detailsQuery}
      render={data => {
        const metaDescription =
          description || data.site.siteMetadata.description
        const publicUrl = `${data.site.siteMetadata.siteUrl}post${slug}`

        return (
          <Helmet
            htmlAttributes={{
              lang,
            }}
            title={title}
            titleTemplate={`%s | ${data.site.siteMetadata.title}`}
            meta={[
              {
                name: `description`,
                content: metaDescription,
              },
              {
                property: `og:url`,
                content: publicUrl,
              },
              {
                property: `og:title`,
                content: title,
              },
              {
                property: `og:description`,
                content: metaDescription,
              },
              featuredImageName
                ? {
                    property: `og:image`,
                    content: publicUrl + featuredImageName,
                  }
                : null,
              {
                property: `og:type`,
                content: `website`,
              },
              {
                name: `twitter:card`,
                content: `summary`,
              },
              {
                name: `twitter:site`,
                content: `@${data.site.siteMetadata.social.twitter}`,
              },
            ]
              .concat(
                keywords.length > 0
                  ? {
                      name: `keywords`,
                      content: keywords.join(`, `),
                    }
                  : []
              )
              .concat(meta)
              .filter(Boolean)}
          >
            <link
              rel="amphtml"
              href={publicUrl.replace('/post/', '/amp/post/')}
            />
          </Helmet>
        )
      }}
    />
  )
}

SEO.defaultProps = {
  lang: `ja`,
  meta: [],
  keywords: [],
}

SEO.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.array,
  keywords: PropTypes.arrayOf(PropTypes.string),
  title: PropTypes.string.isRequired,
  slug: PropTypes.string.isRequired,
  featuredImageName: PropTypes.string,
}

export default SEO

const detailsQuery = graphql`
  query DefaultSEOQuery {
    site {
      siteMetadata {
        title
        description
        author
        siteUrl
        social {
          twitter
        }
      }
    }
  }
`
<commit_msg>Append link rel=amphtml<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'

function SEO({
  description,
  lang,
  meta,
  keywords,
  title,
  slug,
  featuredImageName,
}) {
  return (
    <StaticQuery
      query={detailsQuery}
      render={data => {
        const metaDescription =
          description || data.site.siteMetadata.description
        const publicUrl = `${data.site.siteMetadata.siteUrl}post${slug}`

        return (
          <Helmet
            htmlAttributes={{
              lang,
            }}
            title={title}
            titleTemplate={`%s | ${data.site.siteMetadata.title}`}
            link={[
              {
                rel: 'amphtml',
                href: publicUrl.replace('/post/', '/amp/post/'),
              },
            ]}
            meta={[
              {
                name: `description`,
                content: metaDescription,
              },
              {
                property: `og:url`,
                content: publicUrl,
              },
              {
                property: `og:title`,
                content: title,
              },
              {
                property: `og:description`,
                content: metaDescription,
              },
              featuredImageName
                ? {
                    property: `og:image`,
                    content: publicUrl + featuredImageName,
                  }
                : null,
              {
                property: `og:type`,
                content: `website`,
              },
              {
                name: `twitter:card`,
                content: `summary`,
              },
              {
                name: `twitter:site`,
                content: `@${data.site.siteMetadata.social.twitter}`,
              },
            ]
              .concat(
                keywords.length > 0
                  ? {
                      name: `keywords`,
                      content: keywords.join(`, `),
                    }
                  : []
              )
              .concat(meta)
              .filter(Boolean)}
          />
        )
      }}
    />
  )
}

SEO.defaultProps = {
  lang: `ja`,
  meta: [],
  keywords: [],
}

SEO.propTypes = {
  description: PropTypes.string,
  lang: PropTypes.string,
  meta: PropTypes.array,
  keywords: PropTypes.arrayOf(PropTypes.string),
  title: PropTypes.string.isRequired,
  slug: PropTypes.string.isRequired,
  featuredImageName: PropTypes.string,
}

export default SEO

const detailsQuery = graphql`
  query DefaultSEOQuery {
    site {
      siteMetadata {
        title
        description
        author
        siteUrl
        social {
          twitter
        }
      }
    }
  }
`
<|endoftext|>


<commit_before>import fs from 'fs';
import isEmpty from 'lodash/lang/isEmpty';
import querystring from 'querystring';
import sass from 'sass.js';
import path from 'path';
import url from 'url';
import resolvePath from './resolve-path';

const cssInject = "(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})";

let urlBase;

const escape = source => {
  return source
    .replace(/(["\\])/g, '\\$1')
    .replace(/[\f]/g, '\\f')
    .replace(/[\b]/g, '\\b')
    .replace(/[\n]/g, '\\n')
    .replace(/[\t]/g, '\\t')
    .replace(/[\r]/g, '\\r')
    .replace(/[\ufeff]/g, '')
    .replace(/[\u2028]/g, '\\u2028')
    .replace(/[\u2029]/g, '\\u2029');
};

var isWin = process.platform.match(/^win/);

const loadFile = p => {
  return new Promise((resolve, reject) => {
    fs.readFile(p, { encoding: 'UTF-8' }, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

function fromFileURL(address) {
  address = address.replace(/^file:(\/+)?/i, '');

  if (!isWin)
    address = '/' + address;
  else
    address = address.replace(/\//g, '\\');

  return address;
}

// intercept file loading requests (@import directive) from libsass
sass.importer((request, done) => {
  // Currently only supporting scss imports due to
  // https://github.com/sass/libsass/issues/1695
  let content;
  let resolved;
  let readImportPath;
  let readPartialPath;
  resolvePath(request, urlBase)
    .then(importUrl => {
      resolved = importUrl;
      const partialUrl = importUrl.replace(/\/([^/]*)$/, '/_$1');
      readImportPath = fromFileURL(importUrl);
      readPartialPath = fromFileURL(partialUrl);
      return loadFile(readPartialPath);
    })
    .then(data => content = data)
    .catch(() => loadFile(readImportPath))
    .then(data => content = data)
    .then(() => done({ content, path: resolved }))
    .catch(() => done());
});

export default (loads, compileOpts) => {
  const stubDefines = loads.map(load => {
    return `${(compileOpts.systemGlobal || 'System')}\.register('${load.name}', [], false, function() {});`;
  }).join('\n');

  const compilePromise = load => {
    return new Promise((resolve, reject) => {
      urlBase = path.dirname(load.address) + '/';
      const options = {
        style: sass.style.compressed,
        indentedSyntax: load.address.endsWith('.sass'),
      };
      // Occurs on empty files
      if (isEmpty(load.source)) {
        return resolve('');
      }
      sass.compile(load.source, options, result => {
        if (result.status === 0) {
          resolve(result.text);
        } else {
          reject(result.formatted);
        }
      });
    });
  };
  return new Promise((resolve, reject) => {
    // Keep style order
    Promise.all(loads.map(compilePromise))
    .then(
      response => resolve([stubDefines, cssInject, `("${escape(response.reverse().join(''))}");`].join('\n')),
      reason => reject(reason));
  });
};
<commit_msg>Fix lint errors.<commit_after>import fs from 'fs';
import isEmpty from 'lodash/lang/isEmpty';
import sass from 'sass.js';
import path from 'path';
import resolvePath from './resolve-path';

const cssInject = "(function(c){var d=document,a='appendChild',i='styleSheet',s=d.createElement('style');s.type='text/css';d.getElementsByTagName('head')[0][a](s);s[i]?s[i].cssText=c:s[a](d.createTextNode(c));})";
const isWin = process.platform.match(/^win/);

let urlBase;

const escape = source => {
  return source
    .replace(/(["\\])/g, '\\$1')
    .replace(/[\f]/g, '\\f')
    .replace(/[\b]/g, '\\b')
    .replace(/[\n]/g, '\\n')
    .replace(/[\t]/g, '\\t')
    .replace(/[\r]/g, '\\r')
    .replace(/[\ufeff]/g, '')
    .replace(/[\u2028]/g, '\\u2028')
    .replace(/[\u2029]/g, '\\u2029');
};

const loadFile = p => {
  return new Promise((resolve, reject) => {
    fs.readFile(p, { encoding: 'UTF-8' }, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve(data);
      }
    });
  });
};

const fromFileURL = a => {
  let address = a.replace(/^file:(\/+)?/i, '');

  if (!isWin) {
    address = '/' + address;
  } else {
    address = address.replace(/\//g, '\\');
  }

  return address;
};

// intercept file loading requests (@import directive) from libsass
sass.importer((request, done) => {
  // Currently only supporting scss imports due to
  // https://github.com/sass/libsass/issues/1695
  let content;
  let resolved;
  let readImportPath;
  let readPartialPath;
  resolvePath(request, urlBase)
    .then(importUrl => {
      resolved = importUrl;
      const partialUrl = importUrl.replace(/\/([^/]*)$/, '/_$1');
      readImportPath = fromFileURL(importUrl);
      readPartialPath = fromFileURL(partialUrl);
      return loadFile(readPartialPath);
    })
    .then(data => content = data)
    .catch(() => loadFile(readImportPath))
    .then(data => content = data)
    .then(() => done({ content, path: resolved }))
    .catch(() => done());
});

export default (loads, compileOpts) => {
  const stubDefines = loads.map(load => {
    return `${(compileOpts.systemGlobal || 'System')}\.register('${load.name}', [], false, function() {});`;
  }).join('\n');

  const compilePromise = load => {
    return new Promise((resolve, reject) => {
      urlBase = path.dirname(load.address) + '/';
      const options = {
        style: sass.style.compressed,
        indentedSyntax: load.address.endsWith('.sass'),
      };
      // Occurs on empty files
      if (isEmpty(load.source)) {
        return resolve('');
      }
      sass.compile(load.source, options, result => {
        if (result.status === 0) {
          resolve(result.text);
        } else {
          reject(result.formatted);
        }
      });
    });
  };
  return new Promise((resolve, reject) => {
    // Keep style order
    Promise.all(loads.map(compilePromise))
    .then(
      response => resolve([stubDefines, cssInject, `("${escape(response.reverse().join(''))}");`].join('\n')),
      reason => reject(reason));
  });
};
<|endoftext|>


<commit_before>( function( $ ) {
	'use strict';

	// Nav bar text color.
	wp.customize( 'amp_navbar_color', function( value ) {
		value.bind( function( to ) {
			$( '.amp-wp-header a' ).css( 'color', to );
			$( '.amp-wp-header div' ).css( 'color', to );
			$( '.amp-wp-header .amp-wp-site-icon' ).css( 'border-color', to ).css( 'background-color', to );
		} );
	} );

	// Nav bar background color.
	wp.customize( 'amp_navbar_background_color', function( value ) {
		value.bind( function( to ) {
			$( '.amp-wp-header' ).css( 'background-color', to );
			$( '.amp-wp-article a, .amp-wp-article a:visited, .amp-wp-footer a, .amp-wp-footer a:visited' ).css( 'color', to );
			$( 'blockquote, .amp-wp-byline amp-img' ).css( 'border-color', to );
		} );
	} );

	// Add custom-background-image body class when background image is added.
	wp.customize( 'amp_navbar_background_image', function( value ) {
		value.bind( function( newVal, oldVal ) {
			if ( newVal ) {
				$( body ).addClass( 'amp-wp-has-header-image' );
				$( '.amp-wp-header' ).addClass( 'header-background-image' ).css( 'background-image', 'url(' + encodeURI( newVal ) + ')' );
			} else {
				$( body ).removeClass( 'amp-wp-has-header-image' );
				$( '.amp-wp-header' ).removeClass( 'header-background-image' ).css( 'background-image', 'none' );
			}
		} );
	} );

	// AMP background color scheme.
	wp.customize( 'amp_background_color', function( value ) {
		value.bind( function( to ) {

			// Light
			if ( to == 'light' ) {

				/*
					$theme_color      = '#fff';
					$text_color       = '#535353';
					$muted_text_color = '#9f9f9f';
					$border_color     = '#d4d4d4';
				*/

				$( 'body' ).css( 'background-color', '#ffffff' );
				$( 'body, a:hover, a:active, a:focus, blockquote, .amp-wp-article, .amp-wp-title' ).css( 'color', '#535353' );
				$( '.amp-wp-meta, .wp-caption .wp-caption-text, .amp-wp-tax-category, .amp-wp-tax-tag, .amp-wp-footer p' ).css( 'color', '#9f9f9f' );
				$( '.amp-wp-article-featured-image amp-img, .amp-wp-article-content amp-img, .wp-caption .wp-caption-text, .amp-wp-comments-link a, .amp-wp-footer' ).css( 'border-color', '#d4d4d4' );
				$( '.amp-wp-iframe-placeholder, amp-carousel, amp-iframe, amp-youtube, amp-instagram, amp-vine' ).css( 'background-color', '#d4d4d4' );

			// Dark
			} else if ( to == 'dark' ) {

				/*
					$theme_color      = '#111';
					$text_color       = '#acacac';
					$muted_text_color = '#606060';
					$border_color     = '#2b2b2b';
				*/

				$( 'body' ).css( 'background-color', '#111111' );
				$( 'body, a:hover, a:active, a:focus, blockquote, .amp-wp-article, .amp-wp-title' ).css( 'color', '#acacac' );
				$( '.amp-wp-meta, .wp-caption .wp-caption-text, .amp-wp-tax-category, .amp-wp-tax-tag, .amp-wp-footer p' ).css( 'color', '#606060' );
				$( '.amp-wp-article-featured-image amp-img, .amp-wp-article-content amp-img, .wp-caption .wp-caption-text, .amp-wp-comments-link a, .amp-wp-footer' ).css( 'border-color', '#2b2b2b' );
				$( '.amp-wp-iframe-placeholder, amp-carousel, amp-iframe, amp-youtube, amp-instagram, amp-vine' ).css( 'background-color', '#2b2b2b' );

			// Default
			} else {

				/*
					$theme_color      = '#fff';
					$text_color       = '#3d596d';
					$muted_text_color = '#87A6BC';
					$border_color     = '#c8d7e1';
				*/

				$( 'body' ).css( 'background-color', '#ffffff' );
				$( 'body, a:hover, a:active, a:focus, blockquote, .amp-wp-article, .amp-wp-title' ).css( 'color', '#3d596d' );
				$( '.amp-wp-meta, .wp-caption .wp-caption-text, .amp-wp-tax-category, .amp-wp-tax-tag, .amp-wp-footer p' ).css( 'color', '#87A6BC' );
				$( '.amp-wp-article-featured-image amp-img, .amp-wp-article-content amp-img, .wp-caption .wp-caption-text, .amp-wp-comments-link a, .amp-wp-footer' ).css( 'border-color', '#c8d7e1' );
				$( '.amp-wp-iframe-placeholder, amp-carousel, amp-iframe, amp-youtube, amp-instagram, amp-vine' ).css( 'background-color', '#c8d7e1' );

			}
		} );
	} );

} )( jQuery );
<commit_msg>Fix js error in customizer<commit_after>( function( $ ) {
	'use strict';

	// Nav bar text color.
	wp.customize( 'amp_navbar_color', function( value ) {
		value.bind( function( to ) {
			$( '.amp-wp-header a' ).css( 'color', to );
			$( '.amp-wp-header div' ).css( 'color', to );
			$( '.amp-wp-header .amp-wp-site-icon' ).css( 'border-color', to ).css( 'background-color', to );
		} );
	} );

	// Nav bar background color.
	wp.customize( 'amp_navbar_background_color', function( value ) {
		value.bind( function( to ) {
			$( '.amp-wp-header' ).css( 'background-color', to );
			$( '.amp-wp-article a, .amp-wp-article a:visited, .amp-wp-footer a, .amp-wp-footer a:visited' ).css( 'color', to );
			$( 'blockquote, .amp-wp-byline amp-img' ).css( 'border-color', to );
		} );
	} );

	// Add custom-background-image body class when background image is added.
	wp.customize( 'amp_navbar_background_image', function( value ) {
		value.bind( function( newVal, oldVal ) {
			if ( newVal ) {
				$( 'body' ).addClass( 'amp-wp-has-header-image' );
				$( '.amp-wp-header' ).css( 'background-image', 'url(' + encodeURI( newVal ) + ')' );
			} else {
				$( 'body' ).removeClass( 'amp-wp-has-header-image' );
				$( '.amp-wp-header' ).css( 'background-image', 'none' );
			}
		} );
	} );

	// AMP background color scheme.
	wp.customize( 'amp_background_color', function( value ) {
		value.bind( function( to ) {

			// Light
			if ( to == 'light' ) {

				/*
					$theme_color      = '#fff';
					$text_color       = '#535353';
					$muted_text_color = '#9f9f9f';
					$border_color     = '#d4d4d4';
				*/

				$( 'body' ).css( 'background-color', '#ffffff' );
				$( 'body, a:hover, a:active, a:focus, blockquote, .amp-wp-article, .amp-wp-title' ).css( 'color', '#535353' );
				$( '.amp-wp-meta, .wp-caption .wp-caption-text, .amp-wp-tax-category, .amp-wp-tax-tag, .amp-wp-footer p' ).css( 'color', '#9f9f9f' );
				$( '.amp-wp-article-featured-image amp-img, .amp-wp-article-content amp-img, .wp-caption .wp-caption-text, .amp-wp-comments-link a, .amp-wp-footer' ).css( 'border-color', '#d4d4d4' );
				$( '.amp-wp-iframe-placeholder, amp-carousel, amp-iframe, amp-youtube, amp-instagram, amp-vine' ).css( 'background-color', '#d4d4d4' );

			// Dark
			} else if ( to == 'dark' ) {

				/*
					$theme_color      = '#111';
					$text_color       = '#acacac';
					$muted_text_color = '#606060';
					$border_color     = '#2b2b2b';
				*/

				$( 'body' ).css( 'background-color', '#111111' );
				$( 'body, a:hover, a:active, a:focus, blockquote, .amp-wp-article, .amp-wp-title' ).css( 'color', '#acacac' );
				$( '.amp-wp-meta, .wp-caption .wp-caption-text, .amp-wp-tax-category, .amp-wp-tax-tag, .amp-wp-footer p' ).css( 'color', '#606060' );
				$( '.amp-wp-article-featured-image amp-img, .amp-wp-article-content amp-img, .wp-caption .wp-caption-text, .amp-wp-comments-link a, .amp-wp-footer' ).css( 'border-color', '#2b2b2b' );
				$( '.amp-wp-iframe-placeholder, amp-carousel, amp-iframe, amp-youtube, amp-instagram, amp-vine' ).css( 'background-color', '#2b2b2b' );

			// Default
			} else {

				/*
					$theme_color      = '#fff';
					$text_color       = '#3d596d';
					$muted_text_color = '#87A6BC';
					$border_color     = '#c8d7e1';
				*/

				$( 'body' ).css( 'background-color', '#ffffff' );
				$( 'body, a:hover, a:active, a:focus, blockquote, .amp-wp-article, .amp-wp-title' ).css( 'color', '#3d596d' );
				$( '.amp-wp-meta, .wp-caption .wp-caption-text, .amp-wp-tax-category, .amp-wp-tax-tag, .amp-wp-footer p' ).css( 'color', '#87A6BC' );
				$( '.amp-wp-article-featured-image amp-img, .amp-wp-article-content amp-img, .wp-caption .wp-caption-text, .amp-wp-comments-link a, .amp-wp-footer' ).css( 'border-color', '#c8d7e1' );
				$( '.amp-wp-iframe-placeholder, amp-carousel, amp-iframe, amp-youtube, amp-instagram, amp-vine' ).css( 'background-color', '#c8d7e1' );

			}
		} );
	} );

} )( jQuery );
<|endoftext|>


<commit_before>
function lessAlert(obj, type, msg)
{
    if (type == "") {
        $(obj).hide();
    } else {
        $(obj).removeClass().addClass("alert "+ type).html(msg).show();
    }
}

var lessModalData        = {};
var lessModalCurrent     = null;
var lessModalNextHistory = null;
var lessModalBodyWidth   = null;
var lessModalBodyHeight  = null;

function lessModalNextPost(url, title, opt, post)
{
    lessModalOpenRaw('POST', url, null, null, null, title, opt, post);
}

function lessModalNext(url, title, opt)
{
    lessModalOpen(url, null, null, null, title, opt);
}

function lessModalPrev()
{
    var prev = null;
    for (var i in lessModalData) {
        if (lessModalData[i].urid == lessModalCurrent && prev != null) {
            lessModalNextHistory = lessModalCurrent;
            lessModalSwitch(prev);
            break;
        }
        prev = i;
    }
}

function lessModalSwitch(urid)
{
    if (!lessModalData[urid].title) {
        return;
    }
    pp = $('#'+ urid).position();
    mov = pp.left;
    if (mov < 0) {
        mov = 0;
    }
    $('.less-modal-body-page').animate({top: 0, left: "-"+ mov +"px"}, 300, function() {

        $('.less-modal-header .title').text(lessModalData[urid].title);

        $('.less-modal-footer').empty();
        for (var i in lessModalData[urid].btns) {
            lessModalButtonAdd(lessModalData[urid].btns[i].id,
                lessModalData[urid].btns[i].title,
                lessModalData[urid].btns[i].func,
                lessModalData[urid].btns[i].style);
        }
        lessModalCurrent = urid;

        if (lessModalNextHistory != null) {
            delete lessModalData[lessModalNextHistory];
            $("#"+ lessModalNextHistory).remove();
            lessModalNextHistory = null;
        }
    });
}

function lessModalOpenPost(url, pos, w, h, title, opt, post)
{
    lessModalOpenRaw('POST', url, pos, w, h, title, opt, post)
}

function lessModalOpen(url, pos, w, h, title, opt)
{
    lessModalOpenRaw('GET', url, pos, w, h, title, opt, "")
}

function lessModalOpenRaw(method, url, pos, w, h, title, opt, post)
{
    var urid = Crypto.MD5("modal"+url);

    if (/\?/.test(url)) {
        urls = url + "&_=";
    } else {
        urls = url + "?_=";
    }
    urls += Math.random();

    var p  = lessPosGet();
    var bw = $('body').width() - 60;
    var bh = $('body').height() - 50;

    $.ajax({
        url     : urls,
        type    : method,
        timeout : 30000,
        data    : post,
        success : function(rsp) {

            var firstload = false;
            if (lessModalCurrent == null) {
                $(".less-modal").remove();
                firstload = true;
            }
            lessModalCurrent = urid;
            lessModalData[urid] = {
                "urid":     urid,
                "url":      url,
                "title":    title,
                "btns":     {},
            }
            $(".less-modal-footer").empty();

            var pl = '
'+rsp+'
';

            if (firstload) {

                var apd = '
';

                apd += '
\
                    '+title+'\
                    <button class="close" onclick="lessModalClose()">×</button>\

';

                apd += '
';
                apd += '
'+pl+'
';
                apd += '
';

                apd += '

';

                apd += '
'

                $("body").append(apd);

            } else {
                $(".less-modal-body-page").append(pl);
            }

            $("#"+urid).css({
                "z-index": "-100"
            }).show();

            if (!$('.less-modal').is(':visible')) {
                $(".less-modal").css({
                    "z-index": "-100"
                }).show();
            }

            if (firstload) {

                var hh = $('.less-modal-header').outerHeight(true);
                var fh = $('.less-modal-footer').outerHeight(true);

                if (w < 1) {
                    w = $("#"+urid).outerWidth(true);
                }
                if (w < 200) {
                    w = 200;
                }
                if (h < 1) {
                    h = $("#"+urid).outerHeight(true) + hh + fh + 10;
                }
                if (h < 100) {
                    h = 100;
                }

                var t = 0, l = 0;
                if (pos == 1) {
                    l = bw / 2 - w / 2;
                    t = bh / 2 - h / 2;
                } else {
                    l = p.left;
                    t = p.top;
                }
                if (l > (bw - w)) {
                    l = bw - w;
                }
                if ((t + h) > bh) {
                    t = bh - h;
                }
                if (t < 10) {
                    t = 10;
                }

                $(".less-modal").css({
                    "height": h +'px',
                    "width": w +'px',
                });

                lessModalBodyHeight = h - hh - fh - 10;
                lessModalBodyWidth  = $('.less-modal-body').width();
                $(".less-modal-body").height(lessModalBodyHeight);
            }

            $("#"+urid).css({
                "z-index"   : "1",
                "width"     : lessModalBodyWidth +"px",
                "height"    : lessModalBodyHeight +"px",
            });

            pp = $('#'+ urid).position();
            mov = pp.left;
            if (mov < 0) {
                mov = 0;
            }

            if (!$('.less-modal-bg').is(':visible')) {
                $(".less-modal-bg").remove();
                $("body").append('
');
                $(".less-modal-bg").fadeIn(300);
            }

            if (firstload) {
                $(".less-modal").css({
                    "z-index": 100,
                    "top": t +'px',
                    "left": l +'px',
                //}).hide().slideDown(200, function() {
                }).hide().show(200, function() {
                    lessModalResize();
                });
            }
            $('.less-modal-body-page').animate({top: 0, left: "-"+ mov +"px"}, 240, function() {
                $(".less-modal-header .title").text(title);
                $("#"+urid+" .inputfocus").focus();

                if (lessModalNextHistory != null) {
                    delete lessModalData[lessModalNextHistory];
                    $("#"+ lessModalNextHistory).remove();
                    lessModalNextHistory = null;
                }
            });
        },
        error: function(xhr, textStatus, error) {
            hdev_header_alert('error', xhr.responseText);
        }
    });
}

function lessModalResize()
{
    var h  = $('.less-modal').height();
    var hh = $('.less-modal-header').outerHeight(true);
    var fh = $('.less-modal-footer').outerHeight(true);
    lessModalBodyHeight = h - hh - fh - 10;
    $('.less-modal-body').height(lessModalBodyHeight);
    $('.less-modal-body-pagelet').height(lessModalBodyHeight);
}

function lessModalScrollTop()
{
    $(".less_gen_scroll").scrollTop(0);
}

function lessModalButtonAdd(id, title, func, style)
{
    $(".less-modal-footer")
        .append("<button class='btn btn-small "+style+"' onclick='"+func+"'>"+ title +"</button>")
        .show(0, function() {
            lessModalResize();
            lessModalData[lessModalCurrent].btns[id] = {
                "title":    title,
                "func":     func,
                "style":    style,
            }
        });
}

function lessModalClose()
{
    $(".less-modal").hide(200, function(){
        $(this).remove();
        lessModalData = {};
        lessModalCurrent = null;
        lessModalBodyWidth = null;
        lessModalBodyHeight = null;
    });
    $(".less-modal-bg").fadeOut(200);
}

function lessPosGet()
{
    var pos = null;

    if (window.event) {
        pos = {"left": window.event.pageX, "top": window.event.pageY};
    } else if (pos == null) {
        $(document).mousemove(function(e) {
            pos = {"left": e.pageX, "top": e.pageY};
        });
    }

    return pos;
}

function lessCookieSet(key, val, sec)
{
    var expires = "";

    if (sec) {
        var date = new Date();
        date.setTime(date.getTime() + (sec * 1000));
        expires = "; expires=" + date.toGMTString();
    }

    document.cookie = key + "=" + val + expires + "; path=/";
}

function lessCookieGet(key)
{
    var keyEQ = key + "=";
    var ca = document.cookie.split(';');

    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ')
            c = c.substring(1, c.length);
        if (c.indexOf(keyEQ) == 0)
            return c.substring(keyEQ.length, c.length);
    }

    return null;
}

function lessCookieDel(key)
{
    lessCookieSet(key, "", -1);
}

var lessSession = {};
lessSession.DelByPrefix = function(prefix)
{
    var prelen = prefix.length;
    var qs = {};

    for (var i = 0, len = sessionStorage.length; i < len; i++) {
        if (sessionStorage.key(i).slice(0, prelen) == prefix) {
            qs[i] = sessionStorage.key(i);
        }
    }

    for (var i in qs) {
        sessionStorage.removeItem(qs[i]);
    }
}

<commit_msg>[IMP] The more obvious message prompt<commit_after>
function lessAlert(obj, type, msg)
{
    if (type == "") {
        $(obj).hide();
    } else {
        $(obj).removeClass().addClass("alert "+ type).html(msg).hide(300).show(100);
    }
}

var lessModalData        = {};
var lessModalCurrent     = null;
var lessModalNextHistory = null;
var lessModalBodyWidth   = null;
var lessModalBodyHeight  = null;

function lessModalNextPost(url, title, opt, post)
{
    lessModalOpenRaw('POST', url, null, null, null, title, opt, post);
}

function lessModalNext(url, title, opt)
{
    lessModalOpen(url, null, null, null, title, opt);
}

function lessModalPrev()
{
    var prev = null;
    for (var i in lessModalData) {
        if (lessModalData[i].urid == lessModalCurrent && prev != null) {
            lessModalNextHistory = lessModalCurrent;
            lessModalSwitch(prev);
            break;
        }
        prev = i;
    }
}

function lessModalSwitch(urid)
{
    if (!lessModalData[urid].title) {
        return;
    }
    pp = $('#'+ urid).position();
    mov = pp.left;
    if (mov < 0) {
        mov = 0;
    }
    $('.less-modal-body-page').animate({top: 0, left: "-"+ mov +"px"}, 300, function() {

        $('.less-modal-header .title').text(lessModalData[urid].title);

        $('.less-modal-footer').empty();
        for (var i in lessModalData[urid].btns) {
            lessModalButtonAdd(lessModalData[urid].btns[i].id,
                lessModalData[urid].btns[i].title,
                lessModalData[urid].btns[i].func,
                lessModalData[urid].btns[i].style);
        }
        lessModalCurrent = urid;

        if (lessModalNextHistory != null) {
            delete lessModalData[lessModalNextHistory];
            $("#"+ lessModalNextHistory).remove();
            lessModalNextHistory = null;
        }
    });
}

function lessModalOpenPost(url, pos, w, h, title, opt, post)
{
    lessModalOpenRaw('POST', url, pos, w, h, title, opt, post)
}

function lessModalOpen(url, pos, w, h, title, opt)
{
    lessModalOpenRaw('GET', url, pos, w, h, title, opt, "")
}

function lessModalOpenRaw(method, url, pos, w, h, title, opt, post)
{
    var urid = Crypto.MD5("modal"+url);

    if (/\?/.test(url)) {
        urls = url + "&_=";
    } else {
        urls = url + "?_=";
    }
    urls += Math.random();

    var p  = lessPosGet();
    var bw = $('body').width() - 60;
    var bh = $('body').height() - 50;

    $.ajax({
        url     : urls,
        type    : method,
        timeout : 30000,
        data    : post,
        success : function(rsp) {

            var firstload = false;
            if (lessModalCurrent == null) {
                $(".less-modal").remove();
                firstload = true;
            }
            lessModalCurrent = urid;
            lessModalData[urid] = {
                "urid":     urid,
                "url":      url,
                "title":    title,
                "btns":     {},
            }
            $(".less-modal-footer").empty();

            var pl = '
'+rsp+'
';

            if (firstload) {

                var apd = '
';

                apd += '
\
                    '+title+'\
                    <button class="close" onclick="lessModalClose()">×</button>\

';

                apd += '
';
                apd += '
'+pl+'
';
                apd += '
';

                apd += '

';

                apd += '
'

                $("body").append(apd);

            } else {
                $(".less-modal-body-page").append(pl);
            }

            $("#"+urid).css({
                "z-index": "-100"
            }).show();

            if (!$('.less-modal').is(':visible')) {
                $(".less-modal").css({
                    "z-index": "-100"
                }).show();
            }

            if (firstload) {

                var hh = $('.less-modal-header').outerHeight(true);
                var fh = $('.less-modal-footer').outerHeight(true);

                if (w < 1) {
                    w = $("#"+urid).outerWidth(true);
                }
                if (w < 200) {
                    w = 200;
                }
                if (h < 1) {
                    h = $("#"+urid).outerHeight(true) + hh + fh + 10;
                }
                if (h < 100) {
                    h = 100;
                }

                var t = 0, l = 0;
                if (pos == 1) {
                    l = bw / 2 - w / 2;
                    t = bh / 2 - h / 2;
                } else {
                    l = p.left;
                    t = p.top;
                }
                if (l > (bw - w)) {
                    l = bw - w;
                }
                if ((t + h) > bh) {
                    t = bh - h;
                }
                if (t < 10) {
                    t = 10;
                }

                $(".less-modal").css({
                    "height": h +'px',
                    "width": w +'px',
                });

                lessModalBodyHeight = h - hh - fh - 10;
                lessModalBodyWidth  = $('.less-modal-body').width();
                $(".less-modal-body").height(lessModalBodyHeight);
            }

            $("#"+urid).css({
                "z-index"   : "1",
                "width"     : lessModalBodyWidth +"px",
                "height"    : lessModalBodyHeight +"px",
            });

            pp = $('#'+ urid).position();
            mov = pp.left;
            if (mov < 0) {
                mov = 0;
            }

            if (!$('.less-modal-bg').is(':visible')) {
                $(".less-modal-bg").remove();
                $("body").append('
');
                $(".less-modal-bg").fadeIn(300);
            }

            if (firstload) {
                $(".less-modal").css({
                    "z-index": 100,
                    "top": t +'px',
                    "left": l +'px',
                //}).hide().slideDown(200, function() {
                }).hide().show(200, function() {
                    lessModalResize();
                });
            }
            $('.less-modal-body-page').animate({top: 0, left: "-"+ mov +"px"}, 240, function() {
                $(".less-modal-header .title").text(title);
                $("#"+urid+" .inputfocus").focus();

                if (lessModalNextHistory != null) {
                    delete lessModalData[lessModalNextHistory];
                    $("#"+ lessModalNextHistory).remove();
                    lessModalNextHistory = null;
                }
            });
        },
        error: function(xhr, textStatus, error) {
            hdev_header_alert('error', xhr.responseText);
        }
    });
}

function lessModalResize()
{
    var h  = $('.less-modal').height();
    var hh = $('.less-modal-header').outerHeight(true);
    var fh = $('.less-modal-footer').outerHeight(true);
    lessModalBodyHeight = h - hh - fh - 10;
    $('.less-modal-body').height(lessModalBodyHeight);
    $('.less-modal-body-pagelet').height(lessModalBodyHeight);
}

function lessModalScrollTop()
{
    $(".less_gen_scroll").scrollTop(0);
}

function lessModalButtonAdd(id, title, func, style)
{
    $(".less-modal-footer")
        .append("<button class='btn btn-small "+style+"' onclick='"+func+"'>"+ title +"</button>")
        .show(0, function() {
            lessModalResize();
            lessModalData[lessModalCurrent].btns[id] = {
                "title":    title,
                "func":     func,
                "style":    style,
            }
        });
}

function lessModalClose()
{
    $(".less-modal").hide(200, function(){
        $(this).remove();
        lessModalData = {};
        lessModalCurrent = null;
        lessModalBodyWidth = null;
        lessModalBodyHeight = null;
    });
    $(".less-modal-bg").fadeOut(200);
}

function lessPosGet()
{
    var pos = null;

    if (window.event) {
        pos = {"left": window.event.pageX, "top": window.event.pageY};
    } else if (pos == null) {
        $(document).mousemove(function(e) {
            pos = {"left": e.pageX, "top": e.pageY};
        });
    }

    return pos;
}

function lessCookieSet(key, val, sec)
{
    var expires = "";

    if (sec) {
        var date = new Date();
        date.setTime(date.getTime() + (sec * 1000));
        expires = "; expires=" + date.toGMTString();
    }

    document.cookie = key + "=" + val + expires + "; path=/";
}

function lessCookieGet(key)
{
    var keyEQ = key + "=";
    var ca = document.cookie.split(';');

    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ')
            c = c.substring(1, c.length);
        if (c.indexOf(keyEQ) == 0)
            return c.substring(keyEQ.length, c.length);
    }

    return null;
}

function lessCookieDel(key)
{
    lessCookieSet(key, "", -1);
}

var lessSession = {};
lessSession.DelByPrefix = function(prefix)
{
    var prelen = prefix.length;
    var qs = {};

    for (var i = 0, len = sessionStorage.length; i < len; i++) {
        if (sessionStorage.key(i).slice(0, prelen) == prefix) {
            qs[i] = sessionStorage.key(i);
        }
    }

    for (var i in qs) {
        sessionStorage.removeItem(qs[i]);
    }
}

<|endoftext|>