<commit_before>
/**
 * juice
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

module.exports = exports = juice;

/**
 * Module dependencies.
 */

var utils = require('./utils')
  , Selector = require('./selector')
  , Property = require('./property')

/**
 * Export Selector.
 */

exports.Selector = Selector;

/**
 * Export Property.
 */

exports.Property = Property;

/**
 * Export utils.
 */

exports.utils = require('./utils');

/**
 * Inlines the CSS specified by `css` into the `html`
 *
 * @param {String} html
 * @param {String} css
 * @api public
 */

function juice (html, css, options) {
  var rules = utils.parseCSS(css)
    , document = utils.jsdom(html)
    , editedElements = []
    , topmost = new Selector('<style attribute>', [1, 0, 0, 0])
    , options = options || {}

  rules.forEach(function (rule) {
    var sel = rule[0]
      , style = rule[1]
      , matches = document.querySelectorAll(sel)
      , selector

    utils.toArray(matches).forEach(function (el) {
      // we initialize the Selector lazily to avoid needless parsing
      if (!selector) selector = new Selector(sel)

      if (!el.styleProps) {
        el.styleProps = {}

        // if the element has inline styles, fake selector with topmost specificity
        if (el.getAttribute('style')) {
          var cssText = '* { ' + el.getAttribute('style') + ' } '
          addProps(utils.parseCSS(cssText)[0][1], topmost);
        }

        // store reference to an element we need to compile style="" attr for
        editedElements.push(el);
      }

      // go through the properties
      function addProps (style, selector) {
        for (var i = 0, l = style.length; i < l; i++) {
          var name = style[i]
            , value = style[name]
            , sel = style._importants[name]
                ? new Selector('!important', [2,0,0,0])
                : selector
            , prop = new Property(name, value, sel)
            , existing = el.styleProps[name]

          if (existing) {
            var winner = existing.compare(prop)
              , loser = prop == winner ? existing : prop

            if (winner == prop) el.styleProps[name] = prop;
          } else {
            el.styleProps[name] = prop;
          }
        }
      }

      addProps(style, selector);
    });
  });

  // set `style` attributes
  editedElements.forEach(function (el) {
    var style = '';
    for (var i in el.styleProps)
      style += el.styleProps[i].toString();
    el.setAttribute('style', style);
  });

  return document.body.innerHTML;
}
<commit_msg>Cleanup<commit_after>
/**
 * juice
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */

module.exports = exports = juice;

/**
 * Module dependencies.
 */

var utils = require('./utils')
  , Selector = require('./selector')
  , Property = require('./property')

/**
 * Export Selector.
 */

exports.Selector = Selector;

/**
 * Export Property.
 */

exports.Property = Property;

/**
 * Export utils.
 */

exports.utils = require('./utils');

/**
 * Inlines the CSS specified by `css` into the `html`
 *
 * @param {String} html
 * @param {String} css
 * @api public
 */

var styleSelector = new Selector('<style attribute>', [1, 0, 0, 0])
  , importantSelector = new Selector('!important', [2, 0, 0, 0])

function juice (html, css, options) {
  var rules = utils.parseCSS(css)
    , document = utils.jsdom(html)
    , editedElements = []
    , options = options || {}

  rules.forEach(function (rule) {
    var sel = rule[0]
      , style = rule[1]
      , matches = document.querySelectorAll(sel)
      , selector

    utils.toArray(matches).forEach(function (el) {
      // we initialize the Selector lazily to avoid needless parsing
      if (!selector) selector = new Selector(sel)

      if (!el.styleProps) {
        el.styleProps = {}

        // if the element has inline styles, fake selector with topmost specificity
        if (el.getAttribute('style')) {
          var cssText = '* { ' + el.getAttribute('style') + ' } '
          addProps(utils.parseCSS(cssText)[0][1], styleSelector);
        }

        // store reference to an element we need to compile style="" attr for
        editedElements.push(el);
      }

      // go through the properties
      function addProps (style, selector) {
        for (var i = 0, l = style.length; i < l; i++) {
          var name = style[i]
            , value = style[name]
            , sel = style._importants[name] ? importantSelector : selector
            , prop = new Property(name, value, sel)
            , existing = el.styleProps[name]

          if (existing) {
            var winner = existing.compare(prop)
              , loser = prop == winner ? existing : prop

            if (winner == prop) el.styleProps[name] = prop;
          } else {
            el.styleProps[name] = prop;
          }
        }
      }

      addProps(style, selector);
    });
  });

  // set `style` attributes
  editedElements.forEach(function (el) {
    var style = '';
    for (var i in el.styleProps)
      style += el.styleProps[i].toString();
    el.setAttribute('style', style);
  });

  return document.body.innerHTML;
}
<|endoftext|>


<commit_before>const moduleLoader = require( '../support/moduleLoader' )

// --- Modules --- //

const fs = require( 'fs' )
const os = require( 'os' )

const utility = moduleLoader( 'utility' )
const file    = moduleLoader( 'file' )
const network = moduleLoader( 'network' )

const debug = message => {
  return utility.debug( 'yellow', 'manager', message )
}

// --- Store : Declare private member and method --- //

const store = new WeakMap()

// --- Functions --- //

const download = network.download
const unzip    = file.unzip

const remote = ( from, to ) => {
  const tmp = os.tmpdir()
  return download( from, tmp ).then( filePath => {
    to = utility.absPath( to, filePath.split( /\/|\\/ ).pop().split( '.' )[0] )
    return unzip( filePath, to )
  } )
}

const local = ( from, to ) => {
  to = utility.absPath( to, from.split( /\/|\\/ ).pop().split( '.' )[0] )
  return unzip( from, to )
}

// --- Manager Class --- //

class Manager {

  constructor( options ){
    const prefix = options.prefix || './'

    const electron = ( process.argv0 !== 'node' )
                       ? require( 'electron' )
                       : null

    const directory = utility.absPath(
      ( ( electron !== null )
        ? electron.app.getPath( 'documents' )
        : utility.absPath( options.directory, 'documents' ) )
      , options.prefix, 'applications' )

    if( utility.exists( directory ) === false )
      file.mkdir( directory )

    let applications = []

    fs.readdirSync( directory ).forEach( path => {
      let appPath = utility.absPath( directory, path )
      if( fs.statSync( appPath ).isDirectory() && utility.exists( utility.absPath( appPath, 'package.json' ) ) ){
        applications.push( path )
      }
    } )

    store.set( this, {
      electron    : electron,
      prefix      : prefix,
      directory   : directory,
      applications: applications
    } )
  }

  getAllApps(){
    let applications = []
    let directory = store.get( this ).directory

    fs.readdirSync( directory ).forEach( path => {
      let appPath = utility.absPath( directory, path )
      if( fs.statSync( appPath ).isDirectory() && utility.exists( utility.absPath( appPath, 'package.json' ) ) )
        applications.push( path )
    } )

    let s = store.get( this )
    s.applications = applications

    store.set( this, s )

    return applications
  }

  getAppPath( name ){
    if( name === undefined )
      return null

    const applications = this.getAllApps()
    if( applications.indexOf( name ) !== -1 )
      return utility.absPath( store.get( this ).directory, name )
    return null
  }

  add( url ){
    return new Promise( ( resolve, reject ) => {
      if( url === undefined ){
        debug( 'Error : Path must be a string. Received undefined' )
        reject( new Error( 'Path must be a string. Received undefined' ) )
      }

      const directory = store.get( this ).directory

      if( url.match( /https?\:\/\// ) !== null ){
        remote( url, directory ).then( appPath => {
          debug( 'Added app on ' + appPath )
          resolve( appPath )
        } ).catch( reject )
      } else {
        if( utility.isAbsPath( url ) === true ){
          local( url, directory ).then( appPath => {
            debug( 'Added app on ' + appPath )
            resolve( appPath )
          } ).catch( reject )
        } else {
          debug( 'Error : Path must be absolute' )
          reject( new Error( 'Path must be absolute' ) )
        }
      }
    } )
  }

  remove( name ){
    if( name === undefined )
      return false

    const path = this.getAppPath( name )
    if( path !== null ){
      file.rmdir( path )
      debug( 'Remove app ' + name + ' (' + path + ')' )
      return true
    } else {
      return false
    }
  }

}

module.exports.Manager = Manager
<commit_msg>Fix error when prefix is null<commit_after>const moduleLoader = require( '../support/moduleLoader' )

// --- Modules --- //

const fs = require( 'fs' )
const os = require( 'os' )

const utility = moduleLoader( 'utility' )
const file    = moduleLoader( 'file' )
const network = moduleLoader( 'network' )

const debug = message => {
  return utility.debug( 'yellow', 'manager', message )
}

// --- Store : Declare private member and method --- //

const store = new WeakMap()

// --- Functions --- //

const download = network.download
const unzip    = file.unzip

const remote = ( from, to ) => {
  const tmp = os.tmpdir()
  return download( from, tmp ).then( filePath => {
    to = utility.absPath( to, filePath.split( /\/|\\/ ).pop().split( '.' )[0] )
    return unzip( filePath, to )
  } )
}

const local = ( from, to ) => {
  to = utility.absPath( to, from.split( /\/|\\/ ).pop().split( '.' )[0] )
  return unzip( from, to )
}

// --- Manager Class --- //

class Manager {

  constructor( options ){
    const prefix = options.prefix || './'

    const electron = ( process.argv0 !== 'node' )
                       ? require( 'electron' )
                       : null

    const directory = utility.absPath(
      ( ( electron !== null )
        ? electron.app.getPath( 'documents' )
        : utility.absPath( options.directory, 'documents' ) )
      , prefix, 'applications' )

    if( utility.exists( directory ) === false )
      file.mkdir( directory )

    let applications = []

    fs.readdirSync( directory ).forEach( path => {
      let appPath = utility.absPath( directory, path )
      if( fs.statSync( appPath ).isDirectory() && utility.exists( utility.absPath( appPath, 'package.json' ) ) ){
        applications.push( path )
      }
    } )

    store.set( this, {
      electron    : electron,
      prefix      : prefix,
      directory   : directory,
      applications: applications
    } )
  }

  getAllApps(){
    let applications = []
    let directory = store.get( this ).directory

    fs.readdirSync( directory ).forEach( path => {
      let appPath = utility.absPath( directory, path )
      if( fs.statSync( appPath ).isDirectory() && utility.exists( utility.absPath( appPath, 'package.json' ) ) )
        applications.push( path )
    } )

    let s = store.get( this )
    s.applications = applications

    store.set( this, s )

    return applications
  }

  getAppPath( name ){
    if( name === undefined )
      return null

    const applications = this.getAllApps()
    if( applications.indexOf( name ) !== -1 )
      return utility.absPath( store.get( this ).directory, name )
    return null
  }

  add( url ){
    return new Promise( ( resolve, reject ) => {
      if( url === undefined ){
        debug( 'Error : Path must be a string. Received undefined' )
        reject( new Error( 'Path must be a string. Received undefined' ) )
      }

      const directory = store.get( this ).directory

      if( url.match( /https?\:\/\// ) !== null ){
        remote( url, directory ).then( appPath => {
          debug( 'Added app on ' + appPath )
          resolve( appPath )
        } ).catch( reject )
      } else {
        if( utility.isAbsPath( url ) === true ){
          local( url, directory ).then( appPath => {
            debug( 'Added app on ' + appPath )
            resolve( appPath )
          } ).catch( reject )
        } else {
          debug( 'Error : Path must be absolute' )
          reject( new Error( 'Path must be absolute' ) )
        }
      }
    } )
  }

  remove( name ){
    if( name === undefined )
      return false

    const path = this.getAppPath( name )
    if( path !== null ){
      file.rmdir( path )
      debug( 'Remove app ' + name + ' (' + path + ')' )
      return true
    } else {
      return false
    }
  }

}

module.exports.Manager = Manager
<|endoftext|>


<commit_before>var CloudCmd, Util, DOM;
(function(CloudCmd, Util, DOM){
    'use strict';

    CloudCmd.Config = new ConfigProto(CloudCmd, Util, DOM);

    function ConfigProto(CloudCmd, Util, DOM){
        var Key     = CloudCmd.Key,
            Images  = DOM.Images,
            Events  = DOM.Events,
            ESC     = CloudCmd.Key.ESC,
            INPUT   = 'INPUT',
            CONFIG,
            TEMPLATE,
            Config  = this;

        this.init               = function(pCallBack){
            Util.loadOnLoad([
                Config.show,
                CloudCmd.View,
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f10', Config.show);

            delete Config.init;
        };

        this.show               = function() {
            var funcs = [
                getTemplate,
                cssLoad
            ];

            Images.showLoad({top:true});
            Util.asyncCall(funcs, fillTemplate);
        };

        function cssLoad(callback) {
            DOM.cssLoad({
                src : '/css/config.css',
                func: Util.retExec(callback)
            });
        }

        function getTemplate(callback) {
            Util.ifExec(TEMPLATE, callback, function (execCall) {
                    DOM.ajax({
                    url     : '/html/config.html',
                    success :  function(data) {
                        TEMPLATE = data;
                        execCall();
                    },
                    error   : Images.showError
                });

            });
        }

        function fillTemplate() {
            Util.ifExec(CONFIG, function() {
                var i, n, div, data, li, param, obj = {};

                Util.copyObj(CONFIG, obj);
                changeConfig(obj);
                data    = Util.render(TEMPLATE, obj);
                div     = DOM.anyload({
                    name        : 'div',
                    className   : 'config',
                    inner       : data.toString()
                });

                li      = DOM.getByTag(INPUT, div);
                n       = li.length;

                for (i = 0; i < n; i++) {
                    param = li[i];
                    Events.add('change', change, param);
                    Events.addKey(key, param);
                }

                Images.hideLoad();
                CloudCmd.View.show(div, null, {
                    autoSize: true
                });
            }, function(callback) {
                CloudCmd.getConfig(function(config){
                    CONFIG = config;
                    callback();
                });
            });
        }

        this.hide               = function() {
            CloudCmd.View.hide();
        };

        function listener(pEvent){
            var f10         = Key.F10,
                isBind      = Key.isBind(),
                key         = pEvent.keyCode;

            /* если клавиши можно обрабатывать */
            if (isBind && key === f10)
                Config.show();
        }

        function changeConfig(config) {
            var name;

            for (name in config)
                if (Util.isBoolean(config[name]))
                    config[name] = setState(config[name]);
        }

        function setState(state) {
            var ret = "";

            if (state)
                ret = " checked";

            return ret;
        }

        function change(event) {
            var data,
                obj     = {},
                el      = event.target,
                name    = el.id,
                type    = el.type;

            if (el.type === 'checkbox')
                data = el.checked;
            else
                data = el.value;

            obj[name] = data;
            CONFIG[name] = data;
            CloudCmd.setConfig(CONFIG);

            DOM.RESTful.config(obj);
        }

        function key(event) {
            var keyCode = event.keyCode;

            if (keyCode === ESC)
                Config.hide();
        }
    }

})(CloudCmd, Util, DOM);
<commit_msg>refactor(config) key<commit_after>var CloudCmd, Util, DOM;
(function(CloudCmd, Util, DOM){
    'use strict';

    CloudCmd.Config = new ConfigProto(CloudCmd, Util, DOM);

    function ConfigProto(CloudCmd, Util, DOM){
        var Key     = CloudCmd.Key,
            Images  = DOM.Images,
            Events  = DOM.Events,
            INPUT   = 'INPUT',
            CONFIG,
            TEMPLATE,
            Config  = this;

        this.init               = function(pCallBack){
            Util.loadOnLoad([
                Config.show,
                CloudCmd.View,
            ]);

            DOM.Events.addKey(listener);
            DOM.setButtonKey('f10', Config.show);

            delete Config.init;
        };

        this.show               = function() {
            var funcs = [
                getTemplate,
                cssLoad
            ];

            Images.showLoad({top:true});
            Util.asyncCall(funcs, fillTemplate);
        };

        function cssLoad(callback) {
            DOM.cssLoad({
                src : '/css/config.css',
                func: Util.retExec(callback)
            });
        }

        function getTemplate(callback) {
            Util.ifExec(TEMPLATE, callback, function (execCall) {
                    DOM.ajax({
                    url     : '/html/config.html',
                    success :  function(data) {
                        TEMPLATE = data;
                        execCall();
                    },
                    error   : Images.showError
                });

            });
        }

        function fillTemplate() {
            Util.ifExec(CONFIG, function() {
                var i, n, div, data, li, param, obj = {};

                Util.copyObj(CONFIG, obj);
                changeConfig(obj);
                data    = Util.render(TEMPLATE, obj);
                div     = DOM.anyload({
                    name        : 'div',
                    className   : 'config',
                    inner       : data.toString()
                });

                li      = DOM.getByTag(INPUT, div);
                n       = li.length;

                for (i = 0; i < n; i++) {
                    param = li[i];
                    Events.add('change', change, param);
                    Events.addKey(key, param);
                }

                Images.hideLoad();
                CloudCmd.View.show(div, null, {
                    autoSize: true
                });
            }, function(callback) {
                CloudCmd.getConfig(function(config){
                    CONFIG = config;
                    callback();
                });
            });
        }

        this.hide               = function() {
            CloudCmd.View.hide();
        };

        function listener(pEvent){
            var f10         = Key.F10,
                isBind      = Key.isBind(),
                key         = pEvent.keyCode;

            /* если клавиши можно обрабатывать */
            if (isBind && key === f10)
                Config.show();
        }

        function changeConfig(config) {
            var name;

            for (name in config)
                if (Util.isBoolean(config[name]))
                    config[name] = setState(config[name]);
        }

        function setState(state) {
            var ret = "";

            if (state)
                ret = " checked";

            return ret;
        }

        function change(event) {
            var data,
                obj     = {},
                el      = event.target,
                name    = el.id,
                type    = el.type;

            if (el.type === 'checkbox')
                data = el.checked;
            else
                data = el.value;

            obj[name] = data;
            CONFIG[name] = data;
            CloudCmd.setConfig(CONFIG);

            DOM.RESTful.config(obj);
        }

        function key(event) {
            var keyCode = event.keyCode,
                ESC     = Key.ESC;

            if (keyCode === ESC)
                Config.hide();
        }
    }

})(CloudCmd, Util, DOM);
<|endoftext|>


<commit_before><commit_msg>Draw stroke around selected tiles<commit_after><|endoftext|>


<commit_before>var CloudCommander, CloudFunc, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
CloudCommander.Editor = {};
CloudCommander.Editor.CodeMirror = {
    load: (function(pParent){ /* function loads CodeMirror js and css files */

        /* function shows editor */
        var createEditorDiv = function(){
            if (!pParent.getById('CloudEditor')) {
                var lFM = document.getElementById('fm');
                if(lFM)
                    CloudCommander._anyload({
                        name    : 'div',
                        id      : 'CloudEditor',
                        element : lFM
                    });
                else
                    console.log('Error. Something went wrong FM not found');

                pParent.show();
            }
        };
        /* function loads css files
         * of CodeMirror
         */
        var loadAll = function(pParent) {
            return function(){
                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/codemirror.pack.css'
                });

                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/night.pack.css'
                });

                CloudCommander.cssSet({id:'editor',
                    inner : '.CodeMirror{'                          +
                                'font-family :\'Droid Sans Mono\';' +
                                'font-size   :15px;'                +
                                'padding     :20px;'                +
                            '}'                                     +
                            '.CodeMirror-scroll{'                   +
                                'height      : 660px;'              +
                            '}'
                });

                CloudCommander.jsload('lib/client/editor/'          +
                    'codemirror/pack/javascript.pack.js',
                    createEditorDiv);
            };
        };

        /* load CodeMirror main module */
        CloudCommander.jsload('lib/client/editor/'                  +
            'codemirror/pack/codemirror.pack.js',
            loadAll(this));
    }),

    show : (function(){ /* function shows CodeMirror editor */
            /* if CloudEditor is not loaded - loading him */
            if(!document.getElementById('CloudEditor'))
                return this.load(this);
              /* removing keyBinding if set */

            var lParent = this;
            var initCodeMirror_f = function(pValue){
                CodeMirror(lCloudEditor,{
                    mode        : 'javascript',
                    value       : pValue,
                    theme       : 'night',
                    lineNumbers : true,
                    //переносим длинные строки
                    lineWrapping: false,
                    autofocus   : true,
                    extraKeys: {
                      //Сохранение
                      "Esc": lParent.hide(lParent)
                    }
                });
            };

            var lLeft           = this.getById('left');
            var lCloudEditor    = this.getById('CloudEditor');
            var lCURRENTFILE    = CloudCommander.CURRENT_FILE;

            var lCurrent        = this.getByClass(lCURRENTFILE);
            var lA;
            if(lCurrent.length){
                lCurrent = lCurrent[0];

                /* getting link */
                lA = lCurrent.getElementsByTagName('a');
                if(!lA.length)
                    return console.log('Error:' +
                        'can not find links in current file');

                lA = lA[0].href;
                /* убираем адрес хоста*/
                lA = '/' + lA.replace(document.location.href,'');

                /* checking is this link is to directory */
                var lSize = lCurrent.getElementsByClassName('size');
                if(lSize){
                    lSize = lSize[0].textContent;

                    /* if directory - load json
                     * not html data
                     */
                    if (lSize === '<dir>'){
                        if (lA.indexOf(CloudFunc.NOJS) ===
                            CloudFunc.FS.length){
                            lA = lA.replace(CloudFunc.NOJS, '');
                        }
                    }
                }
            }

            /* показываем гиф загрузки возле пути папки сверху*/
            var lLoadingImage   = CloudCommander._images.loading();
            var lErrorImage     = CloudCommander._images.error();

            lLoadingImage.className='icon loading';/* показываем загрузку*/
            lErrorImage.className='icon error hidden';/* прячем ошибку */
            /* show loading icon */
            lCurrent.firstChild.nextSibling.appendChild(lLoadingImage);

            /* reading data from current file */
            $.ajax({
                url:lA,
                 error: function(jqXHR, textStatus, errorThrown){
                    lErrorImage.className   ='icon error';
                    lErrorImage.title       = jqXHR.responseText;

                    lCurrent.firstChild.nextSibling.appendChild(lErrorImage);

                    lLoadingImage.className ='hidden';

                    console.log(jqXHR.responseText);
                 },

                 success:function(data, textStatus, jqXHR){
                    /* if we got json - show it */
                    if(typeof data === 'object')
                        data = JSON.stringify(data, null, 4);

                    initCodeMirror_f(data);

                    CloudCommander.keyBinded = false;

                    lLeft   &&
                        (lLeft.className = 'panel hidden');

                    lLoadingImage.className ='hidden';
                }
            });
        }),
    hide :  (function(pParent) {
                return function(){
                    CloudCommander.keyBinded = true;

                    var lLeft           = pParent.getById('left');
                    var lCloudEditor    = pParent.getById('CloudEditor');

                    /*
                    lCloudEditor &&
                        (lCloudEditor.className  = 'hidden');
                    */
                    lLeft       &&
                        (lLeft.className         = 'panel');

                    var lCodeMirror = pParent.getByClass('CodeMirror');
                    if(lCodeMirror.length)
                        lCloudEditor
                            .removeChild(lCodeMirror[0]);
                };
            }),
    getById     : function(pId){return document.getElementById(pId);},

    getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    },

    getPanel    : function(){
        var lCurrent = document.getElementsByClassName('current-file');
        lCurrent.length &&
            (lCurrent = lCurrent[0].parentElement);

        return lCurrent && lCurrent.id;
    }
};
CloudCommander.Editor.Keys = (function(){
    "use strict";

    /* loading js and css of CodeMirror */
    CloudCommander.Editor.CodeMirror.show(CloudCommander.Editor.CodeMirror);

    var key_event=function(event){

        /* если клавиши можно обрабатывать */
        if(CloudCommander.keyBinded){
            /* if f4 pressed */
            if(event.keyCode===115){
                CloudCommander.Editor.CodeMirror.show();
            }
        }
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event,false);

    else
        document.onkeypress=key_event;
});<commit_msg>added object Util<commit_after>var CloudCommander, CloudFunc, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
CloudCommander.Editor = {};
CloudCommander.Editor.CodeMirror = new CloudCommander.Util()

/* function loads CodeMirror js and css files */;
CloudCommander.Editor.CodeMirror.load = (function(pParent){
    /* function shows editor */
    var createEditorDiv = function(){
        if (!pParent.getById('CloudEditor')) {
            var lFM = document.getElementById('fm');
            if(lFM)
                pParent.anyload({
                    name    : 'div',
                    id      : 'CloudEditor',
                    element : lFM
                });
            else
                console.log('Error. Something went wrong FM not found');

            pParent.show();
        }
    };
    /* function loads css files
     * of CodeMirror
     */
    var loadAll = function(pParent) {
        return function(){
            pParent.cssLoad({
                src     : 'lib/client/editor/codemirror/pack/codemirror.pack.css'
            });

            pParent.cssLoad({
                src     : 'lib/client/editor/codemirror/pack/night.pack.css'
            });

            pParent.cssSet({id:'editor',
                inner : '.CodeMirror{'                          +
                            'font-family :\'Droid Sans Mono\';' +
                            'font-size   :15px;'                +
                            'padding     :20px;'                +
                        '}'                                     +
                        '.CodeMirror-scroll{'                   +
                            'height      : 660px;'              +
                        '}'
            });

            pParent.jsload('lib/client/editor/'          +
                'codemirror/pack/javascript.pack.js',
                createEditorDiv);
        };
    };

    /* load CodeMirror main module */
    pParent.jsload('lib/client/editor/'                  +
        'codemirror/pack/codemirror.pack.js',
        loadAll(this));
});

 /* function shows CodeMirror editor */
CloudCommander.Editor.CodeMirror.show = (function(){
    /* if CloudEditor is not loaded - loading him */
    if(!this.getById('CloudEditor'))
        return this.load(this);
      /* removing keyBinding if set */

    var lParent = this;
    var initCodeMirror_f = function(pValue){
        CodeMirror(lCloudEditor,{
            mode        : 'javascript',
            value       : pValue,
            theme       : 'night',
            lineNumbers : true,
            //переносим длинные строки
            lineWrapping: false,
            autofocus   : true,
            extraKeys: {
              //Сохранение
              "Esc": lParent.hide(lParent)
            }
        });
    };

    var lLeft           = this.getById('left');
    var lCloudEditor    = this.getById('CloudEditor');
    var lCURRENTFILE    = CloudCommander.CURRENT_FILE;

    var lCurrent        = this.getByClass(lCURRENTFILE);
    var lA;
    if(lCurrent.length){
        lCurrent = lCurrent[0];

        /* getting link */
        lA = lCurrent.getElementsByTagName('a');
        if(!lA.length)
            return console.log('Error:' +
                'can not find links in current file');

        lA = lA[0].href;
        /* убираем адрес хоста*/
        lA = '/' + lA.replace(document.location.href,'');

        /* checking is this link is to directory */
        var lSize = lCurrent.getElementsByClassName('size');
        if(lSize){
            lSize = lSize[0].textContent;

            /* if directory - load json
             * not html data
             */
            if (lSize === '<dir>'){
                if (lA.indexOf(CloudFunc.NOJS) ===
                    CloudFunc.FS.length){
                    lA = lA.replace(CloudFunc.NOJS, '');
                }
            }
        }
    }

    /* показываем гиф загрузки возле пути папки сверху*/
    var lLoadingImage   = CloudCommander._images.loading();
    var lErrorImage     = CloudCommander._images.error();

    lLoadingImage.className='icon loading';/* показываем загрузку*/
    lErrorImage.className='icon error hidden';/* прячем ошибку */
    /* show loading icon */
    lCurrent.firstChild.nextSibling.appendChild(lLoadingImage);

    /* reading data from current file */
    $.ajax({
        url:lA,
         error: function(jqXHR, textStatus, errorThrown){
            lErrorImage.className   ='icon error';
            lErrorImage.title       = jqXHR.responseText;

            lCurrent.firstChild.nextSibling.appendChild(lErrorImage);

            lLoadingImage.className ='hidden';

            console.log(jqXHR.responseText);
         },

         success:function(data, textStatus, jqXHR){
            /* if we got json - show it */
            if(typeof data === 'object')
                data = JSON.stringify(data, null, 4);

            initCodeMirror_f(data);

            CloudCommander.keyBinded = false;

            lLeft   &&
                (lLeft.className = 'panel hidden');

            lLoadingImage.className ='hidden';
        }
    });
});

/* function hides CodeMirror editor */
CloudCommander.Editor.CodeMirror.hide =  (function(pParent) {
    return function(){
        CloudCommander.keyBinded = true;

        var lLeft           = pParent.getById('left');
        var lCloudEditor    = pParent.getById('CloudEditor');

        /*
        lCloudEditor &&
            (lCloudEditor.className  = 'hidden');
        */
        lLeft       &&
            (lLeft.className         = 'panel');

        var lCodeMirror = pParent.getByClass('CodeMirror');
        if(lCodeMirror.length)
            lCloudEditor
                .removeChild(lCodeMirror[0]);
    };
});

CloudCommander.Editor.Keys = (function(){
    "use strict";

    /* loading js and css of CodeMirror */
    this.CodeMirror.show(this.CodeMirror);

    var key_event=function(event){

        /* если клавиши можно обрабатывать */
        if(CloudCommander.keyBinded){
            /* if f4 pressed */
            if(event.keyCode===115){
                CloudCommander.Editor.CodeMirror.show();
            }
        }
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event,false);

    else
        document.onkeypress=key_event;
});<|endoftext|>


<commit_before>/*
 * electron-builder
 * https://github.com/loopline-systems/electron-builder
 *
 * Licensed under the MIT license.
 */

'use strict';

var childProcess    = require( 'child_process' );
var os              = require( 'os' );
var writeConfigFile = require( './helper/writeConfigFile' );
var template        = require( 'lodash.template' );
var path            = require( 'path' );
var fs              = require( 'fs-extra' );

/**
 * Prototype for the linux installer builder
 * @type {Object}
 */
var LinuxBuilder = {
  /**
   * Build the installer for linux
   *
   * @param  {Object}   options  options
   * @param  {Function} callback callback
   */
  build : function( options, callback ) {
    options.log( '- Starting creation of installer for ´' + options.platform );

    var linux = options.config.linux;

    if ( linux.arch === 32 ) {
      linux.archName = 'i386';
    }
    else if ( linux.target === 'deb' ) {
      linux.archName = 'amd64';
    }
    else {
      linux.archName = 'x86_64';
    }

    var outFilename = linux.executable + '-' +
                      linux.version + '-' + linux.archName + '.' +
                      linux.target;
    var tmpFolder = path.join( os.tmpDir(), outFilename );
    _createFolders( tmpFolder );

    _createDesktopEntry( tmpFolder, linux );

    var scripts = _createScripts( linux );
    var destination = path.join( options.out, outFilename );
    _buildPackage( options, scripts, tmpFolder, destination, callback );
  }
};

/**
 * Create folders needed for the build
 *
 * @param {String} tmpFolder  folder where the packaged app is built
 */
function _createFolders( tmpFolder ) {
  fs.emptyDirSync( tmpFolder );
  fs.mkdirpSync( path.join( tmpFolder, 'usr', 'share', 'icons', 'hicolors' ) );
}

/**
 * Create desktop entry
 *
 * @param {String} tmpFolder  temp folder where the app is assembled
 * @param {Object} linux      linux conf
 */
function _createDesktopEntry( tmpFolder, linux ) {
  var desktopEntryTemplate = linux.desktopTemplate || path.join(
    __dirname,
    '..',
    'templates/linux/desktop.tpl'
  );
  var dest = path.join(
    tmpFolder,
    'usr', 'share', 'applications',
    linux.executable + '.desktop'
  );
  var tplFile = fs.readFileSync( desktopEntryTemplate, 'utf8' );
  var tpl = template( tplFile );
  var merge = tpl( linux );
  fs.outputFileSync( dest, merge );
}

/**
 * Create scripts
 *
 * @param {Object} linux  linux conf
 * @return an array containing the scripts paths
 */
function _createScripts ( linux ) {
  var afterInstallTemplate =  linux.afterInstall || path.join(
    __dirname,
    '..',
    'templates/linux/after-install.tpl'
  );
  var afterInstallFilePath = writeConfigFile( afterInstallTemplate, linux );

  var afterRemoveTemplate =  linux.afterRemove || path.join(
    __dirname,
    '..',
    'templates/linux/after-remove.tpl'
  );
  var afterRemoveFilePath = writeConfigFile( afterRemoveTemplate, linux );

  return [ afterInstallFilePath, afterRemoveFilePath ];
}

/**
 * Build the package
 *
 * @param {Object} options options
 * @param {Array}  scripts paths to scripts
 * @param {String} tmpFolder  temp folder where the app is assembled
 * @param {String} destination The package file path to output.
 * @param callback
 */
function _buildPackage( options, scripts, tmpFolder, destination, callback ) {
  var linux = options.config.linux;
  var installPath = 'opt/' + linux.executable;
  var args = [
    '-s', 'dir',
    '-t', linux.target,
    '--architecture', linux.archName,
    '--rpm-os', 'linux',
    '--name', linux.title,
    '--force',
    '--after-install', scripts[0],
    '--after-remove', scripts[1],
    '--description',  linux.comment,
    '--maintainer', linux.maintainer,
    '--version', linux.version,
    '--package', destination,
    tmpFolder + '/=/',
    path.resolve( options.appPath ) + '/=/' + installPath
  ];

  fs.outputFileSync(
    path.join( tmpFolder, installPath, 'pkgtarget' ),
    linux.target
  );
  childProcess.execFile( 'fpm', args, function ( error, stdout, stderr ) {
    if ( error != null ) {
      console.error( stdout.toString() );
      console.error( stderr.toString() );
    }
    callback( error, destination );
  } );
}

/**
 * Expose factory function
 *
 * @type {Object}
 */
module.exports = {
  init : function() {
    return Object.create( LinuxBuilder );
  }
};
<commit_msg>Provide an option to set deb compression and use xz by default (test app if default gz: 38.5MB, xz: 27.6MB)<commit_after>/*
 * electron-builder
 * https://github.com/loopline-systems/electron-builder
 *
 * Licensed under the MIT license.
 */

'use strict';

var childProcess    = require( 'child_process' );
var os              = require( 'os' );
var writeConfigFile = require( './helper/writeConfigFile' );
var template        = require( 'lodash.template' );
var path            = require( 'path' );
var fs              = require( 'fs-extra' );

/**
 * Prototype for the linux installer builder
 * @type {Object}
 */
var LinuxBuilder = {
  /**
   * Build the installer for linux
   *
   * @param  {Object}   options  options
   * @param  {Function} callback callback
   */
  build : function( options, callback ) {
    options.log( '- Starting creation of installer for ´' + options.platform );

    var linux = options.config.linux;

    if ( linux.arch === 32 ) {
      linux.archName = 'i386';
    }
    else if ( linux.target === 'deb' ) {
      linux.archName = 'amd64';
    }
    else {
      linux.archName = 'x86_64';
    }

    var outFilename = linux.executable + '-' +
                      linux.version + '-' + linux.archName + '.' +
                      linux.target;
    var tmpFolder = path.join( os.tmpDir(), outFilename );
    _createFolders( tmpFolder );

    _createDesktopEntry( tmpFolder, linux );

    var scripts = _createScripts( linux );
    var destination = path.join( options.out, outFilename );
    _buildPackage( options, scripts, tmpFolder, destination, callback );
  }
};

/**
 * Create folders needed for the build
 *
 * @param {String} tmpFolder  folder where the packaged app is built
 */
function _createFolders( tmpFolder ) {
  fs.emptyDirSync( tmpFolder );
  fs.mkdirpSync( path.join( tmpFolder, 'usr', 'share', 'icons', 'hicolors' ) );
}

/**
 * Create desktop entry
 *
 * @param {String} tmpFolder  temp folder where the app is assembled
 * @param {Object} linux      linux conf
 */
function _createDesktopEntry( tmpFolder, linux ) {
  var desktopEntryTemplate = linux.desktopTemplate || path.join(
    __dirname,
    '..',
    'templates/linux/desktop.tpl'
  );
  var dest = path.join(
    tmpFolder,
    'usr', 'share', 'applications',
    linux.executable + '.desktop'
  );
  var tplFile = fs.readFileSync( desktopEntryTemplate, 'utf8' );
  var tpl = template( tplFile );
  var merge = tpl( linux );
  fs.outputFileSync( dest, merge );
}

/**
 * Create scripts
 *
 * @param {Object} linux  linux conf
 * @return an array containing the scripts paths
 */
function _createScripts ( linux ) {
  var afterInstallTemplate =  linux.afterInstall || path.join(
    __dirname,
    '..',
    'templates/linux/after-install.tpl'
  );
  var afterInstallFilePath = writeConfigFile( afterInstallTemplate, linux );

  var afterRemoveTemplate =  linux.afterRemove || path.join(
    __dirname,
    '..',
    'templates/linux/after-remove.tpl'
  );
  var afterRemoveFilePath = writeConfigFile( afterRemoveTemplate, linux );

  return [ afterInstallFilePath, afterRemoveFilePath ];
}

/**
 * Build the package
 *
 * @param {Object} options options
 * @param {Array}  scripts paths to scripts
 * @param {String} tmpFolder  temp folder where the app is assembled
 * @param {String} destination The package file path to output.
 * @param callback
 */
function _buildPackage( options, scripts, tmpFolder, destination, callback ) {
  var linux = options.config.linux;
  var installPath = 'opt/' + linux.executable;
  var args = [
    '-s', 'dir',
    '-t', linux.target,
    '--architecture', linux.archName,
    '--rpm-os', 'linux',
    '--name', linux.title,
    '--force',
    '--after-install', scripts[0],
    '--after-remove', scripts[1],
    '--description',  linux.comment,
    '--maintainer', linux.maintainer,
    '--version', linux.version,
    '--package', destination,
    '--deb-compression', linux.compression || 'xz',
    tmpFolder + '/=/',
    path.resolve( options.appPath ) + '/=/' + installPath
  ];

  fs.outputFileSync(
    path.join( tmpFolder, installPath, 'pkgtarget' ),
    linux.target
  );
  childProcess.execFile( 'fpm', args, function ( error, stdout, stderr ) {
    if ( error != null ) {
      console.error( stdout.toString() );
      console.error( stderr.toString() );
    }
    callback( error, destination );
  } );
}

/**
 * Expose factory function
 *
 * @type {Object}
 */
module.exports = {
  init : function() {
    return Object.create( LinuxBuilder );
  }
};
<|endoftext|>


<commit_before>var CloudCommander, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
CloudCommander.Editor = {};
CloudCommander.Editor.CodeMirror = {
    load: (function(){ /* function loads CodeMirror js and css files */

        /* function shows editor */
        var createEditorDiv = function (pParent){
            return function(){
                if (!document.getElementById('CloudEditor')) {
                    var lEditor=document.createElement('div');
                    lEditor.id ='CloudEditor';
                    var lFM = document.getElementById('fm');

                    if(lFM){
                      lFM.appendChild(lEditor);
                    }else console.log('Error. Something went wrong FM not found');
                }
            };
        };
        /* function loads css files
         * of CodeMirror
         */
        var loadAll = function(pParent) {
            return function(){
                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/codemirror.pack.css'
                });

                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/night.pack.css'
                });

                CloudCommander.cssSet({id:'editor',
                    inner : '.CodeMirror{'                          +
                                'font-family:\'Droid Sans Mono\';'  +
                                'font-size:15px;'                   +
                                'resize:vertical;'                  +
                                'padding:20px;'                     +
                            '}'                                     +
                            '.CodeMirror-scroll{'                   +
                                'height: 660px;'                    +
                            '}'                                     +
                            '.CodeMirror-scrollbar{'                +
                                 'overflow-y:auto'                  +
                            '}'
                });

                CloudCommander.jsload('lib/client/editor/codemirror/pack/xml.pack.js',
                    createEditorDiv);
            };
        };

        /* load CodeMirror main module */
        CloudCommander.jsload('lib/client/editor/codemirror/pack/codemirror.pack.js', loadAll(this));
    }),

    show : (function(pParent){ /* function shows CodeMirror editor */
            /* if CloudEditor is not loaded - loading him */
            document.getElementById('CloudEditor') ||
                this.load();
              /* removing keyBinding if set */
            CloudCommander.keyBinded = false;

            var lLeft           = this.getById('left');
            var lCloudEditor    = this.getById('CloudEditor');

            lLeft   &&
                (lLeft.className = 'panel hidden');

            CodeMirror(lCloudEditor,{
                            mode        : "xml",
                            htmlMode    : true,
                            theme       : 'night',
                            lineNumbers : true,
                            //переносим длинные строки
                            lineWrapping: true,
                            extraKeys: {
                              //Сохранение
                              "Esc": pParent.hide(pParent)
                            }
                        });

            lCloudEditor    &&
                (lCloudEditor.className  = '');
        }),
    hide :  (function(pParent) {
                return function(){
                    CloudCommander.keyBinded = true;

                    var lLeft           = pParent.getById('left');
                    var lCloudEditor    = pParent.getById('CloudEditor');

                    lCloudEditor &&
                        (lCloudEditor.className  = 'hidden');

                    lLeft       &&
                        (lLeft.className         = 'panel');
                };
            }),
    getById: function(pId){return document.getElementById(pId);},

    getPanel: function(){
        var lCurrent = document.getElementsByClassName('current-file');
        lCurrent.length &&
            (lCurrent = lCurrent[0].parentElement);

        return lCurrent && lCurrent.id;
    }
};
CloudCommander.Editor.Keys = (function(){
    "use strict";

    /* loading js and css of CodeMirror */
    CloudCommander.Editor.CodeMirror.show(CloudCommander.Editor.CodeMirror);

    var key_event=function(event){

        /* если клавиши можно обрабатывать */
        if(CloudCommander.keyBinded){
            /* if f4 pressed */
            if(event.keyCode===115){
                CloudCommander.Editor.CodeMirror.show();
            }
        }
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event,false);

    else
        document.onkeypress=key_event;
});<commit_msg>minor changes<commit_after>var CloudCommander, CodeMirror;
/* object contains editors CodeMirror
 * and later will be Ace
 */
CloudCommander.Editor = {};
CloudCommander.Editor.CodeMirror = {
    load: (function(){ /* function loads CodeMirror js and css files */

        /* function shows editor */
        var createEditorDiv = function (pParent){
            return function(){
                if (!document.getElementById('CloudEditor')) {
                    var lEditor=document.createElement('div');
                    lEditor.id ='CloudEditor';
                    var lFM = document.getElementById('fm');

                    if(lFM){
                      lFM.appendChild(lEditor);
                      this.show();
                    }else console.log('Error. Something went wrong FM not found');
                }
            };
        };
        /* function loads css files
         * of CodeMirror
         */
        var loadAll = function(pParent) {
            return function(){
                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/codemirror.pack.css'
                });

                CloudCommander.cssLoad({
                    src     : 'lib/client/editor/codemirror/pack/night.pack.css'
                });

                CloudCommander.cssSet({id:'editor',
                    inner : '.CodeMirror{'                          +
                                'font-family:\'Droid Sans Mono\';'  +
                                'font-size:15px;'                   +
                                'resize:vertical;'                  +
                                'padding:20px;'                     +
                            '}'                                     +
                            '.CodeMirror-scroll{'                   +
                                'height: 660px;'                    +
                            '}'                                     +
                            '.CodeMirror-scrollbar{'                +
                                 'overflow-y:auto'                  +
                            '}'
                });

                CloudCommander.jsload('lib/client/editor/codemirror/pack/xml.pack.js',
                    createEditorDiv);
            };
        };

        /* load CodeMirror main module */
        CloudCommander.jsload('lib/client/editor/codemirror/pack/codemirror.pack.js', loadAll(this));
    }),

    show : (function(){ /* function shows CodeMirror editor */
            /* if CloudEditor is not loaded - loading him */
            if(!document.getElementById('CloudEditor'))
                return this.load();
              /* removing keyBinding if set */
            CloudCommander.keyBinded = false;

            var lLeft           = this.getById('left');
            var lCloudEditor    = this.getById('CloudEditor');

            lLeft   &&
                (lLeft.className = 'panel hidden');

            CodeMirror(lCloudEditor,{
                            mode        : "xml",
                            htmlMode    : true,
                            theme       : 'night',
                            lineNumbers : true,
                            //переносим длинные строки
                            lineWrapping: true,
                            extraKeys: {
                              //Сохранение
                              "Esc": this.hide(this)
                            }
                        });

            lCloudEditor    &&
                (lCloudEditor.className  = '');
        }),
    hide :  (function(pParent) {
                return function(){
                    CloudCommander.keyBinded = true;

                    var lLeft           = pParent.getById('left');
                    var lCloudEditor    = pParent.getById('CloudEditor');

                    lCloudEditor &&
                        (lCloudEditor.className  = 'hidden');

                    lLeft       &&
                        (lLeft.className         = 'panel');
                };
            }),
    getById: function(pId){return document.getElementById(pId);},

    getPanel: function(){
        var lCurrent = document.getElementsByClassName('current-file');
        lCurrent.length &&
            (lCurrent = lCurrent[0].parentElement);

        return lCurrent && lCurrent.id;
    }
};
CloudCommander.Editor.Keys = (function(){
    "use strict";

    /* loading js and css of CodeMirror */
    CloudCommander.Editor.CodeMirror.show(CloudCommander.Editor.CodeMirror);

    var key_event=function(event){

        /* если клавиши можно обрабатывать */
        if(CloudCommander.keyBinded){
            /* if f4 pressed */
            if(event.keyCode===115){
                CloudCommander.Editor.CodeMirror.show();
            }
        }
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event,false);

    else
        document.onkeypress=key_event;
});<|endoftext|>


<commit_before>var Helpers = require('./helpers');
var definitions = require('../lib/definitions');

exports.words = function(num){
	if( typeof num == 'undefined'){ var num = 3;}
  return Helpers.shuffle(definitions.lorem()).slice(0, num);
  //Words.shuffle[0, num]
};

exports.sentence = function(wordCount){
	if( typeof wordCount == 'undefined'){ var wordCount = 3;}

	// strange issue with the node_min_test failing for captialize, please fix and add this back
  //return  this.words(wordCount + Helpers.randomNumber(7)).join(' ').capitalize();

  return  this.words(wordCount + Helpers.randomNumber(7)).join(' ');
};

exports.sentences = function(sentenceCount){
  if( typeof sentenceCount == 'undefined'){ var sentenceCount = 3;}
	var sentences = [];
	for(sentenceCount; sentenceCount >= 0; sentenceCount--){
		sentences.push(this.sentence());
	}
  return sentences.join("\n");
};

exports.paragraph = function(sentenceCount){
  if( typeof sentenceCount == 'undefined'){ var sentenceCount = 3;}
	return this.sentences(sentenceCount + Helpers.randomNumber(3));
};

exports.sentences = function(paragraphCount){
  if( typeof paragraphCount == 'undefined'){ var paragraphCount = 3;}
	var paragraphs = [];
	for(paragraphCount; paragraphCount >= 0; paragraphCount--){
		paragraphs.push(this.paragraph());
	}
  return paragraphs.join("\n \r\t");
};
<commit_msg>fixed another typo<commit_after>var Helpers = require('./helpers');
var definitions = require('../lib/definitions');

exports.words = function(num){
	if( typeof num == 'undefined'){ var num = 3;}
  return Helpers.shuffle(definitions.lorem()).slice(0, num);
  //Words.shuffle[0, num]
};

exports.sentence = function(wordCount){
	if( typeof wordCount == 'undefined'){ var wordCount = 3;}

	// strange issue with the node_min_test failing for captialize, please fix and add this back
  //return  this.words(wordCount + Helpers.randomNumber(7)).join(' ').capitalize();

  return  this.words(wordCount + Helpers.randomNumber(7)).join(' ');
};

exports.sentences = function(sentenceCount){
  if( typeof sentenceCount == 'undefined'){ var sentenceCount = 3;}
	var sentences = [];
	for(sentenceCount; sentenceCount >= 0; sentenceCount--){
		sentences.push(this.sentence());
	}
  return sentences.join("\n");
};

exports.paragraph = function(sentenceCount){
  if( typeof sentenceCount == 'undefined'){ var sentenceCount = 3;}
	return this.sentences(sentenceCount + Helpers.randomNumber(3));
};

exports.paragraphs = function(paragraphCount){
  if( typeof paragraphCount == 'undefined'){ var paragraphCount = 3;}
	var paragraphs = [];
	for(paragraphCount; paragraphCount >= 0; paragraphCount--){
		paragraphs.push(this.paragraph());
	}
  return paragraphs.join("\n \r\t");
};
<|endoftext|>


<commit_before>var Util, DOM;

(function (Util, DOMTree) {
    'use strict';

    var Loader      = Util.extendProto(LoaderProto),
        DOMProto    = Object.getPrototypeOf(DOMTree);

    Util.extend(DOMProto, Loader);

    function LoaderProto() {
        var Images  = DOM.Images,
            Events  = DOM.Events,
            Loader  = this;

        /**
         * Function gets id by src
         * @param pSrc
         *
         * Example: http://domain.com/1.js -> 1_js
         */
        this.getIdBySrc             = function(src) {
            var num, sub, id,
                isStr       = Util.isString(src);

            if (isStr) {
                num    = src.lastIndexOf('/') + 1,
                sub    = src.substr(src, num),
                id     = Util.rmStrOnce(src, sub);

                /* убираем точки */
                while (id.indexOf('.') > 0)
                    id = id.replace('.', '_');
            }

            return id;
        };

        /**
         * load file countent via ajax
         *
         * @param pParams
         */
        this.ajax                    = function(params) {
            var p           = params, countProgress,
                type        = p.type || p.method || 'GET',
                xhr         = new XMLHttpRequest();

            xhr.open(type, p.url, true);

            if (p.responseType)
                xhr.responseType = p.responseType;

            Events.add('progress', function(event) {
                var percent, count;

                if (event.lengthComputable) {
                    percent = (event.loaded / event.total) * 100;
                    count   = Math.round(percent);

                    if (countProgress)
                        Images.setProgress(count);

                    countProgress = true;
                }

            }, xhr.upload);

            Events.add('readystatechange', function(event) {
                var TYPE_JSON, type, data, isContain,
                    xhr         = event.target;

                if (xhr.readyState === 4 /* Complete */) {
                    Images.clearProgress();
                    TYPE_JSON   = 'application/json';
                    type        = xhr.getResponseHeader('content-type');

                    if (xhr.status === 200 /* OK */) {
                        data        = xhr.response;
                        isContain   = Util.isContainStr(type, TYPE_JSON);

                        if (p.dataType !== 'text')
                            /* If it's json - parse it as json */
                            if (type && isContain)
                                data = Util.parseJSON(xhr.response) || xhr.response;

                            Util.exec(p.success, data, xhr.statusText, xhr);
                    }
                    /* file not found or connection lost */
                    else {
                        /* if html given or something like thet
                         * getBack just status of result
                         */
                        if (type && type.indexOf('text/plain') !== 0)
                            xhr.responseText = xhr.statusText;

                        Util.exec(p.error, xhr);
                    }
                }
            }, xhr);

            xhr.send(p.data);
        };

        /**
         * create elements and load them to DOM-tree
         * one-by-one
         *
         * @param params
         * @param callback
         */
        this.anyLoadOnLoad          = function(params, callback) {
            var param, func,
                isArray     = Util.isArray(params);

            if (isArray) {
                param   = params.shift();
                isArray = Util.isArray(param);
                func    = function() {
                    Loader.anyLoadOnLoad(params, callback);
                };

                if (!param) {
                    Util.exec(callback);
                } else if (isArray) {
                    Loader.anyLoadInParallel(param, callback);
                } else {
                    if (Util.isString(param))
                        param = {
                            src : param
                        };

                    if (!param.func)
                        param.func = func;

                    Loader.anyload(param);
                }
            }

            return Loader;
        };

        /**
         * improve callback of funcs so
         * we pop number of function and
         * if it's last we call pCallBack
         *
         * @param params
         * @param callback - onload function
         */
        this.anyLoadInParallel        = function(params, callback) {
            var func,
                i     = 0,
                done  = [],

                doneFunc    = function (func) {
                    Util.exec(func);

                    if (!done.pop())
                        Util.exec(callback);
                };

            if (!Util.isArray(params))
                params = [params];

            params.forEach(function(param) {
                var isStr = Util.isString(param);

                done.push(i++);

                if (isStr)
                    param   = { src : param };
                else
                    func    = param.func;

                param.func  = Util.retExec(doneFunc, func);

                Loader.anyload(param);
            });

            return Loader;
        };

        /**
         * Функция создаёт элемент и загружает файл с src.
         *
         * @param pParams_o = {
         * name, - название тэга
         * src', - путь к файлу
         * func, - обьект, содержаий одну из функций
         *          или сразу две onload и onerror
         *          {onload: function() {}, onerror: function();}
         * style,
         * id,
         * element,
         * async, - true by default
         * inner: 'id{color:red, },
         * class,
         * not_append - false by default
         * }
         */
        this.anyload                 = function(pParams_o) {
            var i, n, lElements_a;

            if (!pParams_o ) return;

            /* if a couple of params was
             * processing every of params
             * and quit
             */
            if (Util.isArray(pParams_o)) {
                lElements_a = [];
                for(i = 0, n = pParams_o.length; i < n ; i++)
                    lElements_a[i] = this.anyload(pParams_o[i]);

                return lElements_a;
            }

            var lName       = pParams_o.name,
                lAttr       = pParams_o.attribute,
                lID         = pParams_o.id,
                lClass      = pParams_o.className,
                lSrc        = pParams_o.src,
                lFunc       = pParams_o.func,
                lOnError,
                lAsync      = pParams_o.async,
                lParent     = pParams_o.parent || document.body,
                lInner      = pParams_o.inner,
                lStyle      = pParams_o.style,
                lNotAppend  = pParams_o.not_append;

            if (Util.isObject(lFunc)) {
                lOnError = lFunc.onerror;
                lFunc  = lFunc.onload;
            }
            /* убираем путь к файлу, оставляя только название файла */
            if (!lID && lSrc)
                lID = DOM.getIdBySrc(lSrc);

            var lElement = DOMTree.getById(lID);

            /* если скрипт еще не загружен */
            if (!lElement) {
                if (!lName && lSrc) {

                    var lDot = lSrc.lastIndexOf('.'),
                        lExt =  lSrc.substr(lDot);
                    switch(lExt) {
                        case '.js':
                            lName = 'script';
                            break;
                        case '.css':
                            lName = 'link';
                            lParent = document.head;
                            break;
                        default:
                            return {code: -1, text: 'name can not be empty'};
                    }
                }
                lElement                = document.createElement(lName);

                if (lID)
                    lElement.id         = lID;

                if (lClass)
                    lElement.className  = lClass;

                if (lSrc) {
                    /* if work with css use href */
                    if (lName === 'link') {
                        lElement.href = lSrc;
                        lElement.rel = 'stylesheet';
                    } else
                        lElement.src  = lSrc;

                    /*
                     * if passed arguments function
                     * then it's onload by default
                     *
                     * if object - then onload and onerror
                     */
                    var lLoad     = function(pEvent) {
                            Events.remove('load', lLoad, lElement);
                            Events.remove('error', lError, lElement);

                            Util.exec(lFunc, pEvent);
                        },

                        lError    = function() {
                            lParent.removeChild(lElement);

                            Images.showError({
                                responseText: 'file ' +
                                lSrc                  +
                                ' could not be loaded',
                                status : 404
                            });

                            Util.exec(lOnError);
                        };

                    Events.add('load', lLoad, lElement);
                    Events.addError(lError, lElement);
                }

                if (lAttr)
                    for(i in lAttr)
                        lElement.setAttribute(i, lAttr[i]);

                if (lStyle)
                    lElement.style.cssText = lStyle;

                if (lAsync || lAsync === undefined)
                    lElement.async = true;

                if (!lNotAppend)
                    lParent.appendChild(lElement);

                if (lInner)
                    lElement.innerHTML = lInner;
            }
            /* если js-файл уже загружен
             * запускаем функцию onload
             */
            else
                Util.exec(lFunc);

            return lElement;
        },

        /**
         * Функция загружает js-файл
         *
         * @param pSrc
         * @param pFunc
         */
        this.jsload                  = function(pSrc, pFunc) {
            var lRet = Loader.anyload({
                name : 'script',
                src  : pSrc,
                func : pFunc
            });

            return lRet;
        },

        /**
         * returns jsload functions
         */
        this.retJSLoad               = function(pSrc, pFunc) {
            var lRet = function() {
                return Loader.jsload(pSrc, pFunc);
            };

            return lRet;
        },

        /**
         * Функция создаёт елемент style и записывает туда стили
         * @param pParams_o - структура параметров, заполняеться таким
         * образом: {src: ' ',func: '', id: '', element: '', inner: ''}
         * все параметры опциональны
         */
        this.cssSet                  = function(pParams_o) {
            pParams_o.name      = 'style';
            pParams_o.parent    = pParams_o.parent || document.head;

            return Loader.anyload(pParams_o);
        },

        /**
         * Function loads external css files
         * @pParams_o - структура параметров, заполняеться таким
         * образом: {src: ' ',func: '', id: '', element: '', inner: ''}
         * все параметры опциональны
         */
        this.cssLoad                 = function(pParams_o) {
             if (Util.isArray(pParams_o)) {
                for(var i = 0, n = pParams_o.length; i < n; i++) {
                    pParams_o[i].name = 'link';
                    pParams_o[i].parent   = pParams_o.parent || document.head;
                }

                return Loader.anyload(pParams_o);
            }

            else if (Util.isString(pParams_o))
                pParams_o = { src: pParams_o };

            pParams_o.name      = 'link';
            pParams_o.parent    = pParams_o.parent || document.head;

            return Loader.anyload(pParams_o);
        };

        /**
         * load jquery from google cdn or local copy
         * @param pParams
         */
        this.jquery                     = function(paramObj) {
            var params  = paramObj || {},
                onload  = params.onload,
                onerror = params.onerror;

            /* загружаем jquery: */
            Loader.jsload('//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', {
                onload  : onload,
                onerror : onerror
            });
        };
    }
})(Util, DOM);
<commit_msg>refactore(loader) anyLoadOnLoad<commit_after>var Util, DOM;

(function (Util, DOMTree) {
    'use strict';

    var Loader      = Util.extendProto(LoaderProto),
        DOMProto    = Object.getPrototypeOf(DOMTree);

    Util.extend(DOMProto, Loader);

    function LoaderProto() {
        var Images  = DOM.Images,
            Events  = DOM.Events,
            Loader  = this;

        /**
         * Function gets id by src
         * @param pSrc
         *
         * Example: http://domain.com/1.js -> 1_js
         */
        this.getIdBySrc             = function(src) {
            var num, sub, id,
                isStr       = Util.isString(src);

            if (isStr) {
                num    = src.lastIndexOf('/') + 1,
                sub    = src.substr(src, num),
                id     = Util.rmStrOnce(src, sub);

                /* убираем точки */
                while (id.indexOf('.') > 0)
                    id = id.replace('.', '_');
            }

            return id;
        };

        /**
         * load file countent via ajax
         *
         * @param pParams
         */
        this.ajax                    = function(params) {
            var p           = params, countProgress,
                type        = p.type || p.method || 'GET',
                xhr         = new XMLHttpRequest();

            xhr.open(type, p.url, true);

            if (p.responseType)
                xhr.responseType = p.responseType;

            Events.add('progress', function(event) {
                var percent, count;

                if (event.lengthComputable) {
                    percent = (event.loaded / event.total) * 100;
                    count   = Math.round(percent);

                    if (countProgress)
                        Images.setProgress(count);

                    countProgress = true;
                }

            }, xhr.upload);

            Events.add('readystatechange', function(event) {
                var TYPE_JSON, type, data, isContain,
                    xhr         = event.target;

                if (xhr.readyState === 4 /* Complete */) {
                    Images.clearProgress();
                    TYPE_JSON   = 'application/json';
                    type        = xhr.getResponseHeader('content-type');

                    if (xhr.status === 200 /* OK */) {
                        data        = xhr.response;
                        isContain   = Util.isContainStr(type, TYPE_JSON);

                        if (p.dataType !== 'text')
                            /* If it's json - parse it as json */
                            if (type && isContain)
                                data = Util.parseJSON(xhr.response) || xhr.response;

                            Util.exec(p.success, data, xhr.statusText, xhr);
                    }
                    /* file not found or connection lost */
                    else {
                        /* if html given or something like thet
                         * getBack just status of result
                         */
                        if (type && type.indexOf('text/plain') !== 0)
                            xhr.responseText = xhr.statusText;

                        Util.exec(p.error, xhr);
                    }
                }
            }, xhr);

            xhr.send(p.data);
        };

        /**
         * create elements and load them to DOM-tree
         * one-by-one
         *
         * @param params
         * @param callback
         */
        this.anyLoadOnLoad          = function(params, callback) {
            var param, func, isStr,
                isArray     = Util.isArray(params);

            if (isArray) {
                param   = params.shift();
                isArray = Util.isArray(param);
                isStr   = Util.isString(param),
                func    = function() {
                    Loader.anyLoadOnLoad(params, callback);
                };

                if (!param) {
                    Util.exec(callback);
                } else if (isArray) {
                    Loader.anyLoadInParallel(param, callback);
                } else {
                    if (isStr)
                        param = {
                            src : param
                        };

                    if (!param.func)
                        param.func = func;

                    Loader.anyload(param);
                }
            }

            return Loader;
        };

        /**
         * improve callback of funcs so
         * we pop number of function and
         * if it's last we call pCallBack
         *
         * @param params
         * @param callback - onload function
         */
        this.anyLoadInParallel        = function(params, callback) {
            var func,
                i     = 0,
                done  = [],

                doneFunc    = function (func) {
                    Util.exec(func);

                    if (!done.pop())
                        Util.exec(callback);
                };

            if (!Util.isArray(params))
                params = [params];

            params.forEach(function(param) {
                var isStr = Util.isString(param);

                done.push(i++);

                if (isStr)
                    param   = { src : param };
                else
                    func    = param.func;

                param.func  = Util.retExec(doneFunc, func);

                Loader.anyload(param);
            });

            return Loader;
        };

        /**
         * Функция создаёт элемент и загружает файл с src.
         *
         * @param pParams_o = {
         * name, - название тэга
         * src', - путь к файлу
         * func, - обьект, содержаий одну из функций
         *          или сразу две onload и onerror
         *          {onload: function() {}, onerror: function();}
         * style,
         * id,
         * element,
         * async, - true by default
         * inner: 'id{color:red, },
         * class,
         * not_append - false by default
         * }
         */
        this.anyload                 = function(pParams_o) {
            var i, n, lElements_a;

            if (!pParams_o ) return;

            /* if a couple of params was
             * processing every of params
             * and quit
             */
            if (Util.isArray(pParams_o)) {
                lElements_a = [];
                for(i = 0, n = pParams_o.length; i < n ; i++)
                    lElements_a[i] = this.anyload(pParams_o[i]);

                return lElements_a;
            }

            var lName       = pParams_o.name,
                lAttr       = pParams_o.attribute,
                lID         = pParams_o.id,
                lClass      = pParams_o.className,
                lSrc        = pParams_o.src,
                lFunc       = pParams_o.func,
                lOnError,
                lAsync      = pParams_o.async,
                lParent     = pParams_o.parent || document.body,
                lInner      = pParams_o.inner,
                lStyle      = pParams_o.style,
                lNotAppend  = pParams_o.not_append;

            if (Util.isObject(lFunc)) {
                lOnError = lFunc.onerror;
                lFunc  = lFunc.onload;
            }
            /* убираем путь к файлу, оставляя только название файла */
            if (!lID && lSrc)
                lID = DOM.getIdBySrc(lSrc);

            var lElement = DOMTree.getById(lID);

            /* если скрипт еще не загружен */
            if (!lElement) {
                if (!lName && lSrc) {

                    var lDot = lSrc.lastIndexOf('.'),
                        lExt =  lSrc.substr(lDot);
                    switch(lExt) {
                        case '.js':
                            lName = 'script';
                            break;
                        case '.css':
                            lName = 'link';
                            lParent = document.head;
                            break;
                        default:
                            return {code: -1, text: 'name can not be empty'};
                    }
                }
                lElement                = document.createElement(lName);

                if (lID)
                    lElement.id         = lID;

                if (lClass)
                    lElement.className  = lClass;

                if (lSrc) {
                    /* if work with css use href */
                    if (lName === 'link') {
                        lElement.href = lSrc;
                        lElement.rel = 'stylesheet';
                    } else
                        lElement.src  = lSrc;

                    /*
                     * if passed arguments function
                     * then it's onload by default
                     *
                     * if object - then onload and onerror
                     */
                    var lLoad     = function(pEvent) {
                            Events.remove('load', lLoad, lElement);
                            Events.remove('error', lError, lElement);

                            Util.exec(lFunc, pEvent);
                        },

                        lError    = function() {
                            lParent.removeChild(lElement);

                            Images.showError({
                                responseText: 'file ' +
                                lSrc                  +
                                ' could not be loaded',
                                status : 404
                            });

                            Util.exec(lOnError);
                        };

                    Events.add('load', lLoad, lElement);
                    Events.addError(lError, lElement);
                }

                if (lAttr)
                    for(i in lAttr)
                        lElement.setAttribute(i, lAttr[i]);

                if (lStyle)
                    lElement.style.cssText = lStyle;

                if (lAsync || lAsync === undefined)
                    lElement.async = true;

                if (!lNotAppend)
                    lParent.appendChild(lElement);

                if (lInner)
                    lElement.innerHTML = lInner;
            }
            /* если js-файл уже загружен
             * запускаем функцию onload
             */
            else
                Util.exec(lFunc);

            return lElement;
        },

        /**
         * Функция загружает js-файл
         *
         * @param pSrc
         * @param pFunc
         */
        this.jsload                  = function(pSrc, pFunc) {
            var lRet = Loader.anyload({
                name : 'script',
                src  : pSrc,
                func : pFunc
            });

            return lRet;
        },

        /**
         * returns jsload functions
         */
        this.retJSLoad               = function(pSrc, pFunc) {
            var lRet = function() {
                return Loader.jsload(pSrc, pFunc);
            };

            return lRet;
        },

        /**
         * Функция создаёт елемент style и записывает туда стили
         * @param pParams_o - структура параметров, заполняеться таким
         * образом: {src: ' ',func: '', id: '', element: '', inner: ''}
         * все параметры опциональны
         */
        this.cssSet                  = function(pParams_o) {
            pParams_o.name      = 'style';
            pParams_o.parent    = pParams_o.parent || document.head;

            return Loader.anyload(pParams_o);
        },

        /**
         * Function loads external css files
         * @pParams_o - структура параметров, заполняеться таким
         * образом: {src: ' ',func: '', id: '', element: '', inner: ''}
         * все параметры опциональны
         */
        this.cssLoad                 = function(pParams_o) {
             if (Util.isArray(pParams_o)) {
                for(var i = 0, n = pParams_o.length; i < n; i++) {
                    pParams_o[i].name = 'link';
                    pParams_o[i].parent   = pParams_o.parent || document.head;
                }

                return Loader.anyload(pParams_o);
            }

            else if (Util.isString(pParams_o))
                pParams_o = { src: pParams_o };

            pParams_o.name      = 'link';
            pParams_o.parent    = pParams_o.parent || document.head;

            return Loader.anyload(pParams_o);
        };

        /**
         * load jquery from google cdn or local copy
         * @param pParams
         */
        this.jquery                     = function(paramObj) {
            var params  = paramObj || {},
                onload  = params.onload,
                onerror = params.onerror;

            /* загружаем jquery: */
            Loader.jsload('//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', {
                onload  : onload,
                onerror : onerror
            });
        };
    }
})(Util, DOM);
<|endoftext|>