<commit_before>/* Модуль сжатия js-скриптов, css-стилей, html-файлов и
 * конвертации картинок в css-стилях
 * в base64 и помещения их в файл стилей
 */
(function() {
    'use strict';

    var DIR         = __dirname +'/',
        LIBDIR      = DIR + 'lib/',
        main        = require(LIBDIR + 'main'),
        img         = main.require(LIBDIR + 'img'),

        crypto      = main.crypto,
        fs          = main.fs,
        path        = main.path,
        Util        = main.util,

        MinFolder   = DIR + 'min/';

    /* Trying to create folder min
     * where woud be minifyed versions
     * of files 511(10)=777(8)
     * rwxrwxrwx
     */
    fs.exists(MinFolder, function makeFolder(exist) {
        if (!exist)
            fs.mkdir(MinFolder, 511, Util.log.bind(Util));
    });

    /**
     * function minificate js,css and html files
     * @param files  -   array of js, css and html file names or string, if name
     *                      single, or object if postProcessing neaded
     *                          {'client.js': function(pFinalCode) {} }
     *                      or convertion images to base64 neaded
     *                          {'style.css': true}
     *                       or {'style.css':{minimize: true, func: function() {}}
     *
     * @param options  -   object contain main options
     */
    function optimize(files, options) {
        var i,
            name        = '',
            lAllCSS     = '',
            /* varible contains all readed files count */
            lReadedFilesCount = 0,

            /**
             * Processing of files
             * @param fileData {name, data}
             */
            onDataRead  = function(fileData) {
                var name,
                    filename    = fileData.name,
                    data        = fileData.data,
                    lOptimizeParams;

                function isLastFile() {
                    return lReadedFilesCount === files.length;
                }

                if (Util.isObject(filename)) {
                    for (name in filename) {
                        break;
                    }

                    lOptimizeParams = fileName[name];
                    fileName        = name;
                }

            Util.log('minify: file ' + path.basename(filename) + ' read');

            var lExt            = Util.getExtension(filename),
                lMinFileName    = getName(filename, lExt);

            data = main.optimize({
                ext : lExt,
                data: data
            });

            Util.ifExec(lExt !== '.css', function(pOptData) {
                var ret = Util.isString(pOptData);

                if (ret) {
                    data    = pOptData;
                    lAllCSS += pOptData;
                }

                ++lReadedFilesCount;

                if (isLastFile())
                    saveAllCSS(lOptimizeParams, lAllCSS);

                writeFile(lMinFileName, data, function(pData) {
                    if (options)
                        if (options.returnName)
                             Util.exec(options.callback, {
                                 name: lMinFileName
                             });
                         else
                            Util.exec(options.callback, pData);
                    });
                }, function(callback) {
                    img.optimize(filename, data, callback);
            });
        };

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

        /* moving thru all elements of js files array */
        for (i = 0; files[i]; i++) {
            /* if postProcessing function exist
             * getting file name and pass next
             */
            var lPostProcessing_o = files[i];
            if (Util.isObject(lPostProcessing_o))
                for (name in lPostProcessing_o)
                    break;
            else
                name = files[i];

            Util.log('minify: reading file ' + path.basename(name) + '...');

            /* if it's last file send true */
             fs.readFile(name, Util.call(fileRead, {
                name    : files[i],
                callback: onDataRead
            }));
        }
    }

    /**
     * function get name of file in min folder
     * @param pName
     */
    function getName(name, ext) {
        var ret, minFileName;

        if (Util.isString(name)) {
            if (!ext)
                ext         = Util.getExtension(name);

            minFileName = crypto.createHash('sha1')
                .update(name)
                .digest('hex') + ext;

            ret = MinFolder + minFileName;
        }

        return ret;
    }

    function fileRead(pParams) {
        var p, d, lData,
            lRet =  Util.checkObj(pParams, ['error', 'data']) &&
                    Util.checkObjTrue(pParams.params, ['name', 'callback']);

        if (lRet) {
            p = pParams,
            d = p.params;

            Util.log(p.error);
            lData = p.data && p.data.toString();

            Util.exec(d.callback, {
                name: d.name,
                data: lData
            });
        }
    }

    /*
     * Функция записывает файла
     * и выводит ошибку или сообщает,
     * что файл успешно записан
     */
    function writeFile(name, data, callback) {
        fs.writeFile(name, data, function(error) {
            if (error)
                Util.log(error);
            else {
                name = path.basename(name);
                Util.log('minify: file ' + name + ' written...');
            }

            Util.exec(callback, data);
        });
    }

    function saveAllCSS(params, data) {
        var path;

        if (params && params.merge) {
           path = MinFolder + 'all.min.css';
           writeFile(path, data);
        }
    }

    exports.getName     = getName;
    exports.optimize    = optimize;
    exports.MinFolder   = MinFolder;

})();
<commit_msg>chore(minify) add " "<commit_after>/* Модуль сжатия js-скриптов, css-стилей, html-файлов и
 * конвертации картинок в css-стилях
 * в base64 и помещения их в файл стилей
 */
(function() {
    'use strict';

    var DIR         = __dirname +'/',
        LIBDIR      = DIR + 'lib/',
        main        = require(LIBDIR + 'main'),
        img         = main.require(LIBDIR + 'img'),

        crypto      = main.crypto,
        fs          = main.fs,
        path        = main.path,
        Util        = main.util,

        MinFolder   = DIR + 'min/';

    /* Trying to create folder min
     * where woud be minifyed versions
     * of files 511(10)=777(8)
     * rwxrwxrwx
     */
    fs.exists(MinFolder, function makeFolder(exist) {
        if (!exist)
            fs.mkdir(MinFolder, 511, Util.log.bind(Util));
    });

    /**
     * function minificate js,css and html files
     * @param files  -   array of js, css and html file names or string, if name
     *                      single, or object if postProcessing neaded
     *                          {'client.js': function(pFinalCode) {} }
     *                      or convertion images to base64 neaded
     *                          {'style.css': true}
     *                       or {'style.css':{minimize: true, func: function() {}}
     *
     * @param options  -   object contain main options
     */
    function optimize(files, options) {
        var i,
            name        = '',
            lAllCSS     = '',
            /* varible contains all readed files count */
            lReadedFilesCount = 0,

            /**
             * Processing of files
             * @param fileData {name, data}
             */
            onDataRead  = function(fileData) {
                var name,
                    filename    = fileData.name,
                    data        = fileData.data,
                    lOptimizeParams;

                function isLastFile() {
                    return lReadedFilesCount === files.length;
                }

                if (Util.isObject(filename)) {
                    for (name in filename) {
                        break;
                    }

                    lOptimizeParams = fileName[name];
                    fileName        = name;
                }

            Util.log('minify: file ' + path.basename(filename) + ' read');

            var lExt            = Util.getExtension(filename),
                lMinFileName    = getName(filename, lExt);

            data = main.optimize({
                ext : lExt,
                data: data
            });

            Util.ifExec(lExt !== '.css', function(pOptData) {
                var ret = Util.isString(pOptData);

                if (ret) {
                    data    = pOptData;
                    lAllCSS += pOptData;
                }

                ++lReadedFilesCount;

                if (isLastFile())
                    saveAllCSS(lOptimizeParams, lAllCSS);

                writeFile(lMinFileName, data, function(pData) {
                    if (options)
                        if (options.returnName)
                             Util.exec(options.callback, {
                                 name: lMinFileName
                             });
                         else
                            Util.exec(options.callback, pData);
                    });
                }, function(callback) {
                    img.optimize(filename, data, callback);
                });
        };

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

        /* moving thru all elements of js files array */
        for (i = 0; files[i]; i++) {
            /* if postProcessing function exist
             * getting file name and pass next
             */
            var lPostProcessing_o = files[i];
            if (Util.isObject(lPostProcessing_o))
                for (name in lPostProcessing_o)
                    break;
            else
                name = files[i];

            Util.log('minify: reading file ' + path.basename(name) + '...');

            /* if it's last file send true */
             fs.readFile(name, Util.call(fileRead, {
                name    : files[i],
                callback: onDataRead
            }));
        }
    }

    /**
     * function get name of file in min folder
     * @param pName
     */
    function getName(name, ext) {
        var ret, minFileName;

        if (Util.isString(name)) {
            if (!ext)
                ext         = Util.getExtension(name);

            minFileName = crypto.createHash('sha1')
                .update(name)
                .digest('hex') + ext;

            ret = MinFolder + minFileName;
        }

        return ret;
    }

    function fileRead(pParams) {
        var p, d, lData,
            lRet =  Util.checkObj(pParams, ['error', 'data']) &&
                    Util.checkObjTrue(pParams.params, ['name', 'callback']);

        if (lRet) {
            p = pParams,
            d = p.params;

            Util.log(p.error);
            lData = p.data && p.data.toString();

            Util.exec(d.callback, {
                name: d.name,
                data: lData
            });
        }
    }

    /*
     * Функция записывает файла
     * и выводит ошибку или сообщает,
     * что файл успешно записан
     */
    function writeFile(name, data, callback) {
        fs.writeFile(name, data, function(error) {
            if (error)
                Util.log(error);
            else {
                name = path.basename(name);
                Util.log('minify: file ' + name + ' written...');
            }

            Util.exec(callback, data);
        });
    }

    function saveAllCSS(params, data) {
        var path;

        if (params && params.merge) {
           path = MinFolder + 'all.min.css';
           writeFile(path, data);
        }
    }

    exports.getName     = getName;
    exports.optimize    = optimize;
    exports.MinFolder   = MinFolder;

})();
<|endoftext|>


<commit_before>/**
 * # Instant Win
 *
 * An instant-win is a game where the player finds out immediately if he or she is a winner of one of the prizes the administrators put at stake.
 *
 * A player can play once a day provided he or she loses at each attempt. A player that wins the prize will not be allowed to play the game anymore.
 *
 * To create am instant, use the `instant_win@hull` which will let you create an instant win and add prizes to it.
 *
 * ## Example
 *
 *

 *
 * ## Options
 *
 * - `id`: Required, the InstantWin achievement id.
 * - `provider`: Optional, the identity provider to log with before playing. By default it will list all your identity providers.
 * - `delay`: Optional, time in milliseconds to wait before displaying the game's results. By default the results are displayed imediatly after that the server tell us if the user has win or lost.
 *
 * ## Templates

 * - `intro`: Show the button to play to the game.
 * - `buttons`: The play buttons partial.
 * - `working`: Show a loading message.
 * - `won`: Say to the user that he has won
 * - `lost`: Say to the user that he has lost.
 * - `played`: Say to the user that he has already played.
 * - `unstarted`: Say to the user that the game hasn`t started yet.
 * - `ended`: Say to the user that the game has ended.
 *
 * ## Datasources
 *
 * - `achievement`: The InstantWin achievement.
 * - `badge`: The user's badge for the InstantWin.
 *
 * ## Action
 *
 * - `play`: Ensure that the user is logged and play.
 */
define({
  type: 'Hull',

  templates: [
    'intro',
    'buttons',
    'working',
    'won',
    'lost',
    'played',
    'unstarted',
    'ended'
  ],

  trackingData: function() {
    var data = { type: 'instant_win' };
    var achievement = this.data.achievement;
    if (achievement && achievement.get) { data.name = achievement.get('name'); }
    return data;
  },

  refreshEvents: ['model.hull.me.change'],

  datasources: {
    achievement: ':id',
    badge: function() {
      return this.loggedIn() ? this.api('hull/me/badges/' + this.options.id) : null;
    }
  },

  actions: {
    play: function(source, event, data) {
      var userLoggedIn = !!this.loggedIn();
      if (userLoggedIn) {
        this.play();
      } else {
        var provider = data.provider || this.options.provider;
        this.sandbox.login(provider);
        this.autoPlay = true;
      }

      this.track('start', { userLoggedIn: userLoggedIn });
    }
  },

  initialize: function() {
    this.authProviders = _.map(this.sandbox.config.services.types.auth, function(s) {
      return s.replace(/_app$/, '');
    });
  },

  beforeRender: function(data) {
    this.template = this.getInitialTemplate();

    data.authProviders = this.authProviders;

    if (!this.isInitialized) {
      this.track('init', { initialTemplate: this.template });
    }
  },

  afterRender: function(data) {
    if (this.autoPlay) {
      this.autoPlay = false;
      if (!this.userHasWon()) { this.play(); }
    }

    if (this.template === 'won' || this.template === 'lost') {
      this.track('finish', { result: this.template });
    }

    this.sandbox.emit('hull.instant_win.' + this.options.id + '.template.render', this.template);
  },

  /*!
   * Return the template name that the user should see when he lands on the
   * game.
   *
   * - `intro`: if the user hasn't played during the current day.
   * - `won`: if the user has won a prize.
   * - `played`: if the user has played during the current day.
   * - `unstarted`: if the game hasn't started.
   * - `ended`: if the game has ended.
   *
   * @return {String}
   */
  getInitialTemplate: function() {
    if (this.userHasWon()) {
      return 'won';
    } else if (this.hasEnded()) {
      return 'ended';
    } else if (this.hasStarted()) {
      return this.userCanPlay() ? 'intro' : 'played';
    } else {
      return 'unstarted';
    }
  },

  /*!
   * Determine if the game has started. return `true` if it has `false` if it
   * hasn't.
   *
   * @return {Boolean}
   */
  hasStarted: function() {
    // TODO Need achievement `start_date`
    return true;
  },

  /*!
   * Determine if the game has ended. Return `true` if it has `false` if it
   * hasn't.
   *
   * @return {Boolean}
   */
  hasEnded: function() {
    // TODO Need achievement `end_date`
    return false;
  },

  /*!
   * Determine if the user can play. Return `true` if he can `false` if he
   * cannot.
   *
   * @return {Boolean}
   */
  userCanPlay: function() {
    if (!this.data.badge || !this.data.badge.attempts) { return true; }
    var d = new Date().toISOString().slice(0, 10);
    return !this.data.badge.data.attempts[d];
  },

  /*!
   * Determine if user has won. Return `true` if the he has, `false` if he
   * hasn't.
   *
   * @return {Boolean}
   */
  userHasWon: function() {
    if (!this.data.badge || !this.data.badge.data) { return false; }
    return this.data.badge.data.winner;
  },

  /*!
   * Play to the game and render a template:
   *
   * - `won`: if the user has won.
   * - `lost`: if the user has lost.
   * - `played`: if the user has played during the current day.
   *
   * When the function is called we render `working` and display it
   * until we know if the user has won.
   */
  play: function() {
    this.render('working');
    this.api('hull/' + this.id + '/achieve', 'post', _.bind(function(res) {
      var template = 'played';
      if (this.userCanPlay()) { template = res.data.winner ? 'won' : 'lost'; }
      _.delay(_.bind(function() {
        this.render(template);
      }, this), parseInt(this.options.delay, 10) || 0);
    }, this));
  }
});
<commit_msg>Fix instant_win docs<commit_after>/**
 * # Instant Win
 *
 * An instant-win is a game where the player finds out immediately if he or she is a winner of one of the prizes the administrators put at stake.
 *
 * A player can play once a day provided he or she loses at each attempt. A player that wins the prize will not be allowed to play the game anymore.
 *
 * To create an instant win, use the `instant_win_admin@hull` widget which will let you create an instant win and add prizes to it.
 *
 * ## Example
 *
 *

 *
 * ## Options
 *
 * - `id`: Required, the InstantWin achievement id.
 * - `provider`: Optional, the identity provider to log with before playing. By default it will list all your identity providers.
 * - `delay`: Optional, time in milliseconds to wait before displaying the game's results. By default the results are displayed imediatly after that the server tell us if the user has win or lost.
 *
 * ## Templates

 * - `intro`: Show the button to play to the game.
 * - `buttons`: The play buttons partial.
 * - `working`: Show a loading message.
 * - `won`: Say to the user that he has won
 * - `lost`: Say to the user that he has lost.
 * - `played`: Say to the user that he has already played.
 * - `unstarted`: Say to the user that the game hasn`t started yet.
 * - `ended`: Say to the user that the game has ended.
 *
 * ## Datasources
 *
 * - `achievement`: The InstantWin achievement.
 * - `badge`: The user's badge for the InstantWin.
 *
 * ## Action
 *
 * - `play`: Ensure that the user is logged and play.
 */
define({
  type: 'Hull',

  templates: [
    'intro',
    'buttons',
    'working',
    'won',
    'lost',
    'played',
    'unstarted',
    'ended'
  ],

  trackingData: function() {
    var data = { type: 'instant_win' };
    var achievement = this.data.achievement;
    if (achievement && achievement.get) { data.name = achievement.get('name'); }
    return data;
  },

  refreshEvents: ['model.hull.me.change'],

  datasources: {
    achievement: ':id',
    badge: function() {
      return this.loggedIn() ? this.api('hull/me/badges/' + this.options.id) : null;
    }
  },

  actions: {
    play: function(source, event, data) {
      var userLoggedIn = !!this.loggedIn();
      if (userLoggedIn) {
        this.play();
      } else {
        var provider = data.provider || this.options.provider;
        this.sandbox.login(provider);
        this.autoPlay = true;
      }

      this.track('start', { userLoggedIn: userLoggedIn });
    }
  },

  initialize: function() {
    this.authProviders = _.map(this.sandbox.config.services.types.auth, function(s) {
      return s.replace(/_app$/, '');
    });
  },

  beforeRender: function(data) {
    this.template = this.getInitialTemplate();

    data.authProviders = this.authProviders;

    if (!this.isInitialized) {
      this.track('init', { initialTemplate: this.template });
    }
  },

  afterRender: function(data) {
    if (this.autoPlay) {
      this.autoPlay = false;
      if (!this.userHasWon()) { this.play(); }
    }

    if (this.template === 'won' || this.template === 'lost') {
      this.track('finish', { result: this.template });
    }

    this.sandbox.emit('hull.instant_win.' + this.options.id + '.template.render', this.template);
  },

  /*!
   * Return the template name that the user should see when he lands on the
   * game.
   *
   * - `intro`: if the user hasn't played during the current day.
   * - `won`: if the user has won a prize.
   * - `played`: if the user has played during the current day.
   * - `unstarted`: if the game hasn't started.
   * - `ended`: if the game has ended.
   *
   * @return {String}
   */
  getInitialTemplate: function() {
    if (this.userHasWon()) {
      return 'won';
    } else if (this.hasEnded()) {
      return 'ended';
    } else if (this.hasStarted()) {
      return this.userCanPlay() ? 'intro' : 'played';
    } else {
      return 'unstarted';
    }
  },

  /*!
   * Determine if the game has started. return `true` if it has `false` if it
   * hasn't.
   *
   * @return {Boolean}
   */
  hasStarted: function() {
    // TODO Need achievement `start_date`
    return true;
  },

  /*!
   * Determine if the game has ended. Return `true` if it has `false` if it
   * hasn't.
   *
   * @return {Boolean}
   */
  hasEnded: function() {
    // TODO Need achievement `end_date`
    return false;
  },

  /*!
   * Determine if the user can play. Return `true` if he can `false` if he
   * cannot.
   *
   * @return {Boolean}
   */
  userCanPlay: function() {
    if (!this.data.badge || !this.data.badge.attempts) { return true; }
    var d = new Date().toISOString().slice(0, 10);
    return !this.data.badge.data.attempts[d];
  },

  /*!
   * Determine if user has won. Return `true` if the he has, `false` if he
   * hasn't.
   *
   * @return {Boolean}
   */
  userHasWon: function() {
    if (!this.data.badge || !this.data.badge.data) { return false; }
    return this.data.badge.data.winner;
  },

  /*!
   * Play to the game and render a template:
   *
   * - `won`: if the user has won.
   * - `lost`: if the user has lost.
   * - `played`: if the user has played during the current day.
   *
   * When the function is called we render `working` and display it
   * until we know if the user has won.
   */
  play: function() {
    this.render('working');
    this.api('hull/' + this.id + '/achieve', 'post', _.bind(function(res) {
      var template = 'played';
      if (this.userCanPlay()) { template = res.data.winner ? 'won' : 'lost'; }
      _.delay(_.bind(function() {
        this.render(template);
      }, this), parseInt(this.options.delay, 10) || 0);
    }, this));
  }
});
<|endoftext|>


<commit_before>$(document).ready(function(){
    Lobibox.alert.DEFAULT_OPTIONS = {
        width: 700
    };
    Lobibox.info.DEFAULT_OPTIONS = {
        iconClass: 'glyphicon glyphicon-info-sign'
    };
    Lobibox.error.DEFAULT_OPTIONS = {
        iconClass: 'glyphicon glyphicon-remove-sign'
    };
    Lobibox.progress.DEFAULT_OPTIONS = {
        width: 500
    };
    Lobibox.confirm.DEFAULT_OPTIONS = {
        width: 500
    };
     Lobibox.prompt.DEFAULT_OPTIONS = {
        width: 500,
        lines: 5
    };
    $('#error').click(function(){
        Lobibox.alert('error',{
            title   : "შეცდომა",
            msg     : "რაღაც არ გამოვიდა!!!",
            buttons: ['ok', 'yes', 'no', 'cancel'],
//            buttons: {
//                ok : {
//                    'class' : 'btn btn-default btn-sm',
//                    closeMessagebox: true
//                }
//            },
//            width: 400,
            modal: false,
//            iconClass   : 'glyphicon glyphicon-remove-sign',
            footer: {
                buttonsAlign: 'center'
            },
            callback: function(exert, type, event){
                if (type === 'ok'){
                    Lobibox.notify('success', {
                        title: "OKOK",
                        msg: "You clicked OK button",
                        delay: 5000,
                        closeOnClick: false,
                        position: 'top left'
                    });
                }else if (type === 'cancel'){
                    Lobibox.notify('error', {
                        title: 'My Title',
                        msg: "Lorem Iecently with desktop versions of Lorem versions of Lorem versions of Lorem Ipsum.",
                        delay: 0,
                        closeOnClick: true,
                        imgUrl: 'DSC00118.JPG'
                    });
                }else if (type === 'yes'){
                    Lobibox.notify('warning', {
                        msg: "You clicked Yes button",
                        delay: 0,
                        closeOnClick: true
                    });
                }else if (type === 'no'){
                    Lobibox.notify('info', {
                        title: 'This is Info',
                        msg: "You clicked No button",
                        delay: 0,
                        closeOnClick: true
                    });
                }
            }
        });
    });
    $('#success').click(function(){
        Lobibox.alert('success',{
            title       : 'Success Popup',
            msg         : "Lorem ipsum dolor sit amet paradise variety yonder neque sweep porches general, bagdat buried flows granted.",
            iconClass   : 'glyphicon glyphicon-ok-sign',
//            buttons     : ['yes', 'no']
        });
    });
    $('#progress').click(function(){
        Lobibox.progress({
            title       : 'Please wait',
            label       : 'Uploading files...',
//            progressBarHTML : '
\n\
//

\n\
//
',
            progressCompleted: function(){
                window.console.log("completed");
            },
            onShow      : function(exert){
                var i = 0;
                var inter = setInterval(function(){
                    window.console.log(i);
                    if (i > 50){
                        inter = clearInterval(inter);
                    }
                    i = i+0.1;
                    exert.setProgress(i);
                },10);
            }
        });
    });
    $('#info').click(function(){
        Lobibox.alert('info',{
            title       : 'Info Popup',
            msg         : "Lorem ipsum dolor sit amet paradise variety yonder neque sweep porches general, bagdat buried flows granted. Linden grudge plunge, float metus libraries mind feet ribald reports for callow fare every. ",
//            iconClass   : 'glyphicon glyphicon-info-sign'
        });
    });
    $('#warning').click(function(){
        Lobibox.alert('warning',{
            title       : 'Warning Popup',
            msg         : "Lorem ipsum dolor sit amet paradise variety yonder neque sweep porches general, bagdat buried flows granted. Linden grudge plunge, float metus libraries mind feet ribald reports for callow fare every. Blessed suffices linden fled, receipt brink region, lured wrath dew neutral",
            closeButton : true,
            modal       : false,
            iconClass   : 'glyphicon glyphicon-exclamation-sign'
        });
    });
    $('#yesNo').click(function(){
        Lobibox.confirm({
//            title       : 'Question',
            msg         : "Are you sure you want to delete this user?",
            closeButton : true,
            draggable   : true,
//            modal       : false,
            iconClass   : 'glyphicon glyphicon-question-sign',
            callback    : function(exert, type, ev){
                window.console.log(exert);
                exert.destroy();
                window.console.log(type);
            }
        });
    });

    $('#prompt').click(function(){
        Lobibox.prompt({
            title       : 'Please enter you email',
            closeButton : true,
            draggable   : true,
            placeholder : "Please enter your email",
            closeOnEsc  : true,
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });
    $('#promptColor').click(function(){
        Lobibox.prompt({
            title       : 'Please Choose color',
            type        : 'color',
            label       : 'Please Choose color',
            closeOnEsc  : true,
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });
    $('#promptNumber').click(function(){
        Lobibox.prompt({
            title       : 'How old are you?',
            placeholder : 'Age',
            type        : 'number',
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });

    $('#multilinePrompt').click(function(){
        Lobibox.prompt({
            title       : 'Comment',
            closeButton : true,
            draggable   : true,
            placeholder : "Please tell us your oppinion",
            multiline   : true,
            width       : 400,
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });
    Lobibox.window.DEFAULT_OPTIONS = {
        loadMethod: 'POST',
        width: 600
    };
    $('#window').click(function(){
        var v = Lobibox.window({
            title       : 'Window title',
            content     : function(){
                return $('#windowContent').clone().removeAttr('style');
            },
//            width       : 480,
            height      : 640,
            url         : 'content.html',
            autoload    : false,
            modal       : false,
//            beforeCreate: function(){
//                window.console.log("before create");
//            },
//            beforeShow  : function(){
//                window.console.log("before show");
//            },
            onShow      : function(exert){
               setTimeout(function(){
                   exert.setTitle("gamarjoba");
               },2000);
            },
//            beforePosition: function(){
//                window.console.log("before position");
//            },
//            afterPosition: function(){
//                window.console.log("after position");
//            },
//            params      : {
//                name    : 'zura'
//            },
            buttons: {
                print: {
                    text: 'print'
                },
                save: {
                    text: 'Save'
                },
                cancel: {}
            },
            callback    : function(exert, type, ev){
                if (type === 'print'){
                    exert.setParams({
                        name: 'mari'
                    });
                    exert.load();
                }
                window.console.log(exert);
                window.console.log(type);
            }
        });
    });

});<commit_msg>working on menu toggle<commit_after>$(document).ready(function(){
    Lobibox.alert.DEFAULT_OPTIONS = {
        width: 700
    };
    Lobibox.info.DEFAULT_OPTIONS = {
        iconClass: 'glyphicon glyphicon-info-sign'
    };
    Lobibox.error.DEFAULT_OPTIONS = {
        iconClass: 'glyphicon glyphicon-remove-sign'
    };
    Lobibox.progress.DEFAULT_OPTIONS = {
        width: 500
    };
    Lobibox.confirm.DEFAULT_OPTIONS = {
        width: 500
    };
     Lobibox.prompt.DEFAULT_OPTIONS = {
        width: 500,
        lines: 5
    };
    $('#error').click(function(){
        Lobibox.alert('error',{
            title   : "შეცდომა",
            msg     : "რაღაც არ გამოვიდა!!!",
            buttons: ['ok', 'yes', 'no', 'cancel'],
//            buttons: {
//                ok : {
//                    'class' : 'btn btn-default btn-sm',
//                    closeMessagebox: true
//                }
//            },
//            width: 400,
            modal: false,
//            iconClass   : 'glyphicon glyphicon-remove-sign',
            footer: {
                buttonsAlign: 'center'
            },
            callback: function(exert, type, event){
                if (type === 'ok'){
                    Lobibox.notify('success', {
                        title: "OKOK",
                        msg: "You clicked OK button",
                        delay: 5000,
                        closeOnClick: false,
                        position: 'top left'
                    });
                }else if (type === 'cancel'){
                    Lobibox.notify('error', {
                        title: 'My Title',
                        msg: "Lorem Iecently with desktop versions of Lorem versions of Lorem versions of Lorem Ipsum.",
                        delay: 0,
                        closeOnClick: true,
                        imgUrl: 'DSC00118.JPG'
                    });
                }else if (type === 'yes'){
                    Lobibox.notify('warning', {
                        msg: "You clicked Yes button",
                        delay: 0,
                        closeOnClick: true
                    });
                }else if (type === 'no'){
                    Lobibox.notify('info', {
                        title: 'This is Info',
                        msg: "You clicked No button",
                        delay: 0,
                        closeOnClick: true
                    });
                }
            }
        });
    });
    $('#success').click(function(){
        Lobibox.alert('success',{
            title       : 'Success Popup',
            msg         : "Lorem ipsum dolor sit amet paradise variety yonder neque sweep porches general, bagdat buried flows granted.",
            iconClass   : 'glyphicon glyphicon-ok-sign',
//            buttons     : ['yes', 'no']
        });
    });
    $('#progress').click(function(){
        Lobibox.progress({
            title       : 'Please wait',
            label       : 'Uploading files...',
//            progressBarHTML : '
\n\
//

\n\
//
',
            progressCompleted: function(){
                window.console.log("completed");
            },
            onShow      : function(exert){
                var i = 0;
                var inter = setInterval(function(){
                    window.console.log(i);
                    if (i > 50){
                        inter = clearInterval(inter);
                    }
                    i = i+0.1;
                    exert.setProgress(i);
                },10);
            }
        });
    });
    $('#info').click(function(){
        Lobibox.alert('info',{
            title       : 'Info Popup',
            msg         : "Lorem ipsum dolor sit amet paradise variety yonder neque sweep porches general, bagdat buried flows granted. Linden grudge plunge, float metus libraries mind feet ribald reports for callow fare every. ",
//            iconClass   : 'glyphicon glyphicon-info-sign'
        });
    });
    $('#warning').click(function(){
        Lobibox.alert('warning',{
            title       : 'Warning Popup',
            msg         : "Lorem ipsum dolor sit amet paradise variety yonder neque sweep porches general, bagdat buried flows granted. Linden grudge plunge, float metus libraries mind feet ribald reports for callow fare every. Blessed suffices linden fled, receipt brink region, lured wrath dew neutral",
            closeButton : true,
            modal       : false,
            iconClass   : 'glyphicon glyphicon-exclamation-sign'
        });
    });
    $('#yesNo').click(function(){
        Lobibox.confirm({
//            title       : 'Question',
            msg         : "Are you sure you want to delete this user?",
            closeButton : true,
            draggable   : true,
//            modal       : false,
            iconClass   : 'glyphicon glyphicon-question-sign',
            callback    : function(exert, type, ev){
                window.console.log(exert);
                exert.destroy();
                window.console.log(type);
            }
        });
    });

    $('#prompt').click(function(){
        Lobibox.prompt({
            title       : 'Please enter you email',
            closeButton : true,
            draggable   : true,
            placeholder : "Please enter your email",
            closeOnEsc  : true,
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });
    $('#promptColor').click(function(){
        Lobibox.prompt({
            title       : 'Please Choose color',
            type        : 'color',
            label       : 'Please Choose color',
            closeOnEsc  : true,
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });
    $('#promptNumber').click(function(){
        Lobibox.prompt({
            title       : 'How old are you?',
            placeholder : 'Age',
            type        : 'number',
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });

    $('#multilinePrompt').click(function(){
        Lobibox.prompt({
            title       : 'Comment',
            closeButton : true,
            draggable   : true,
            placeholder : "Please tell us your oppinion",
            multiline   : true,
            width       : 400,
            callback    : function(exert, type, ev){
                exert.destroy();
                if (type === 'ok'){
                    window.console.log(exert.getValue());
                }
            }
        });
    });
    Lobibox.window.DEFAULT_OPTIONS = {
        loadMethod: 'POST',
        width: 600
    };
    $('#window').click(function(){
        var v = Lobibox.window({
            title       : 'Window title',
            content     : function(){
                return $('#windowContent').clone().removeAttr('style');
            },
//            width       : 480,
            height      : 640,
            url         : 'content.html',
            autoload    : false,
//            modal       : false,
//            beforeCreate: function(){
//                window.console.log("before create");
//            },
//            beforeShow  : function(){
//                window.console.log("before show");
//            },
            onShow      : function(exert){
               setTimeout(function(){
                   exert.setTitle("gamarjoba");
               },2000);
            },
//            beforePosition: function(){
//                window.console.log("before position");
//            },
//            afterPosition: function(){
//                window.console.log("after position");
//            },
//            params      : {
//                name    : 'zura'
//            },
            buttons: {
                print: {
                    text: 'print'
                },
                save: {
                    text: 'Save'
                },
                cancel: {}
            },
            callback    : function(exert, type, ev){
                if (type === 'print'){
                    exert.setParams({
                        name: 'mari'
                    });
                    exert.load();
                }
                window.console.log(exert);
                window.console.log(type);
            }
        });
    });

});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Measure from './measure/Measure';

const style = {
  padding: 5,
  paddingTop: 60,
  display: 'flex',
  flexWrap: 'wrap',
  flex: 1
};

class TabStaff extends Component {
  calcWidth = (measures) => {
    return measures.reduce((width, measure) => {
      return measure.width + width;
    }, 20);
  };

  calcHeight = (measures, tuning) => {
    return 1.7 * (measures[measures.length - 1].rowIndex + 1) * (27 * tuning.length) + 40;
  };

  renderMeasureForRow = (_, measureIndex) => {
    return <Measure key={measureIndex} measureIndex={measureIndex} />;
  };

  render() {
    const { layout, tuning, measures } = this.props;

    let height = layout === 'linear' ? '100% - 10' : this.calcHeight(measures, tuning);
    let width = layout === 'linear' ? this.calcWidth(measures) : window.innerWidth - 10;
    return (

        { this.props.measures.map(this.renderMeasureForRow) }

    );
  }
}

function mapStateToProps(state) {
  const track = state.tracks[state.currentTrackIndex];

  return {
    measures: track.measures,
    tuning: track.tuning,
    layout: state.layout
  };
}

export default connect(mapStateToProps)(TabStaff);
<commit_msg>remove unnecessary method and declaration<commit_after>import React, { Component } from 'react';
import { connect } from 'react-redux';
import Measure from './measure/Measure';

const style = {
  padding: 5,
  paddingTop: 60,
  display: 'flex',
  flexWrap: 'wrap',
  flex: 1
};

class TabStaff extends Component {
  calcWidth = (measures) => {
    return measures.reduce((width, measure) => {
      return measure.width + width;
    }, 20);
  };

  calcHeight = (measures, tuning) => {
    return 1.7 * (measures[measures.length - 1].rowIndex + 1) * (27 * tuning.length) + 40;
  };

  render() {
    const { layout, tuning, measures } = this.props;

    const height = layout === 'linear' ? '100% - 10' : this.calcHeight(measures, tuning);
    const width = layout === 'linear' ? this.calcWidth(measures) : window.innerWidth - 10;
    return (

      { this.props.measures.map((_, i) => <Measure key={i} measureIndex={i} />) }

    );
  }
}

function mapStateToProps(state) {
  return {
    measures: state.tracks[state.currentTrackIndex].measures,
    tuning: state.tracks[state.currentTrackIndex].tuning,
    layout: state.layout
  };
}

export default connect(mapStateToProps)(TabStaff);
<|endoftext|>


<commit_before>/**
* @author Alejandro Galue <agalue@opennms.org>
* @copyright 2016 The OpenNMS Group, Inc.
*/

'use strict';

angular.module('onms-resources', [
  'ui.bootstrap',
  'angular-growl'
])

.config(['growlProvider', function(growlProvider) {
  growlProvider.globalTimeToLive(3000);
  growlProvider.globalPosition('bottom-center');
}])

.controller('NodeResourcesCtrl', ['$scope', '$filter', '$http', '$window', 'growl', function($scope, $filter, $http, $window, growl) {

  $scope.searchQuery = undefined;
  $scope.resources = {};
  $scope.hasResources = false;
  $scope.filteredResources = {};
  $scope.isCollapsed = {};
  $scope.nodeLink = undefined;
  $scope.nodeLabel = undefined;
  $scope.url = 'graph/results.htm?reports=all';

  $scope.init = function(criteria) {
    $http.get('rest/resources/fornode/'+criteria).success(function(data) {
      $scope.nodeLink = data.link;
      $scope.nodeLabel = data.label;
      $scope.hasResources = data.children.resource.length > 0;
      var reduced = _.map(data.children.resource, function(obj) {
        return { id: obj.id, label: obj.label, typeLabel: obj.typeLabel, checked: false };
      });
      $scope.resources = _.groupBy(_.sortBy(reduced, 'typeLabel'), 'typeLabel');
      angular.copy($scope.resources, $scope.filteredResources);
    });
  };

  $scope.checkAll = function(check) {
    for (var key in $scope.resources) {
      _.each($scope.filteredResources[key], function(r) {
        r.selected = check;
      });
    }
  };

  $scope.graphSelected = function() {
    var selected = [];
    for (var key in $scope.resources) {
      _.each($scope.filteredResources[key], function(r) {
        if (r.selected) {
          selected.push('resourceId=' + r.id);
        }
      });
    }
    $scope.doGraph(selected);
  };

  $scope.graphAll = function() {
    var selected = [];
    for (var key in $scope.filteredResources) {
      selected.concat(_.map($scope.filteredResources[key], function(r) {
        return 'resourceId=' + r.id;
      }));
    }
    $scope.doGraph(selected);
  };

  $scope.doGraph = function(selected) {
    if (selected.length > 0) {
      $window.location.href = $scope.url + '&' + selected.join('&');
    } else {
      growl.error('Please select at least one resource.');
    }
  };

  $scope.$watch('searchQuery', function() {
    $scope.filteredResurces = {};
    for (var key in $scope.resources) {
      $scope.filteredResources[key] = $filter('filter')($scope.resources[key], $scope.searchQuery);
    }
  });

}]);
<commit_msg>NMS-8646: ensure that 'SNMP Node Data' and 'SNMP Interfaces Data' appear first.<commit_after>/**
* @author Alejandro Galue <agalue@opennms.org>
* @copyright 2016 The OpenNMS Group, Inc.
*/

'use strict';

angular.module('onms-resources', [
  'ui.bootstrap',
  'angular-growl'
])

.config(['growlProvider', function(growlProvider) {
  growlProvider.globalTimeToLive(3000);
  growlProvider.globalPosition('bottom-center');
}])

.controller('NodeResourcesCtrl', ['$scope', '$filter', '$http', '$window', 'growl', function($scope, $filter, $http, $window, growl) {

  $scope.searchQuery = undefined;
  $scope.resources = {};
  $scope.hasResources = false;
  $scope.filteredResources = {};
  $scope.isCollapsed = {};
  $scope.nodeLink = undefined;
  $scope.nodeLabel = undefined;
  $scope.url = 'graph/results.htm?reports=all';

  $scope.init = function(criteria) {
    $http.get('rest/resources/fornode/'+criteria).success(function(data) {
      $scope.nodeLink = data.link;
      $scope.nodeLabel = data.label;
      $scope.hasResources = data.children.resource.length > 0;
      var reduced = _.map(data.children.resource, function(obj) {
        return { id: obj.id, label: obj.label, typeLabel: obj.typeLabel, checked: false };
      });
      $scope.resources = _.groupBy(_.sortBy(reduced, function(r) {
        var type = r['typeLabel'];
        return (type === 'SNMP Node Data' || type === 'SNMP Interface Data') ? Infinity : type;
      }), 'typeLabel');
      angular.copy($scope.resources, $scope.filteredResources);
    });
  };

  $scope.checkAll = function(check) {
    for (var key in $scope.resources) {
      _.each($scope.filteredResources[key], function(r) {
        r.selected = check;
      });
    }
  };

  $scope.graphSelected = function() {
    var selected = [];
    for (var key in $scope.resources) {
      _.each($scope.filteredResources[key], function(r) {
        if (r.selected) {
          selected.push('resourceId=' + r.id);
        }
      });
    }
    $scope.doGraph(selected);
  };

  $scope.graphAll = function() {
    var selected = [];
    for (var key in $scope.filteredResources) {
      selected.concat(_.map($scope.filteredResources[key], function(r) {
        return 'resourceId=' + r.id;
      }));
    }
    $scope.doGraph(selected);
  };

  $scope.doGraph = function(selected) {
    if (selected.length > 0) {
      $window.location.href = $scope.url + '&' + selected.join('&');
    } else {
      growl.error('Please select at least one resource.');
    }
  };

  $scope.$watch('searchQuery', function() {
    $scope.filteredResurces = {};
    for (var key in $scope.resources) {
      $scope.filteredResources[key] = $filter('filter')($scope.resources[key], $scope.searchQuery);
    }
  });

}]);
<|endoftext|>


<commit_before>leaf.ai={PatternList:new leaf.List,TopicList:void 0,chat:function(a,b,c){function d(a){return a.replace(/[^a-z0-9*]/gi,"").toLowerCase()}function e(a){return a[Math.floor(Math.random()*a.length)]}function f(a){var b="";return leaf.isDefined(a.get("header"))&&(b+=e(a.get("header"))+" "),leaf.isDefined(a.get("content"))&&(b+=e(a.get("content"))+" "),leaf.isDefined(a.get("footer"))&&(b+=e(a.get("footer"))),b}function g(a,b){return a=d(a),b=d(b),new RegExp("^"+a.split("*").join(".*")+"$").test(b)}function h(b){var c;return b.each(function(b){b.get("pattern").forEach(function(d){g(d,a)&&(c=b)})}),c}var i;return i=h(leaf.isUndefined(this.TopicList)?this.PatternList:this.TopicList),leaf.isDefined(i)?leaf.isFunction(b)&&(this.TopicList=new leaf.List(i.get("topic"))||void 0,b(f(i),i)):leaf.isFunction(c)&&c(),a}};<commit_msg>Updated<commit_after>leaf.ai={PatternList:new leaf.List,TopicList:void 0,chat:function(a,b,c){function d(a){return a.replace(/[^a-z0-9*]/gi,"").toLowerCase()}function e(a){return a[Math.floor(Math.random()*a.length)]}function f(a){var b="";return leaf.isDefined(a.get("header"))&&(b+=e(a.get("header"))+" "),leaf.isDefined(a.get("content"))&&(b+=e(a.get("content"))+" "),leaf.isDefined(a.get("footer"))&&(b+=e(a.get("footer"))),b}function g(a,b){return a=d(a),b=d(b),new RegExp("^"+a.split("*").join(".*")+"$").test(b)}function h(b){var c;return b.each(function(b){b.get("pattern").forEach(function(d){g(d,a)&&leaf.isUndefined(c)&&(c=b)})}),c}var i;return i=h(leaf.isUndefined(this.TopicList)?this.PatternList:this.TopicList),leaf.isDefined(i)?leaf.isFunction(b)&&(this.TopicList=new leaf.List(i.get("topic"))||void 0,b(f(i),i)):leaf.isFunction(c)&&c(),a}};<|endoftext|>


<commit_before>/* jshint ignore:start */
$(document).ready(function () {
    var sense;
    var imageSize;
    var handModule;
    var handConfiguration;

    // check platform compatibility
    /*RealSenseInfo(['hand'], function (info) {
        if (info.IsReady == true) {
            $('#info').append('Platform supports Intel(R) RealSense(TM) SDK feature');
            status('OK');
            document.getElementById("Start").disabled = false;
        } else {
            status('Platform not supported: ' + info.responseText);
            if (info.IsPlatformSupported != true) {
                $('#info').append('Intel� RealSense� 3D camera not found');
            } else if (info.IsBrowserSupported != true) {
                $('#info').append('Please update your browser to latest version');
            } else {
                $('#info').append('Please download and install the following update(s) before running sample: ');
                for (i = 0; i < info.Updates.length; i++) {
                    $('#info').append('' + info.Updates[i].href + '
');
                }
            }
        }
    })*/

    PXCMSenseManager_CreateInstance().then(function (result) {
        sense = result;
        return sense.EnableHand(onHandData);
    }).then(function (result) {
        handModule = result;
        status('Init started');
        return sense.Init(onConnect, onStatus);
    }).then(function (result) {
        return handModule.CreateActiveConfiguration();
    }).then(function (result) {
        handConfiguration = result;
        return handConfiguration.DisableAllAlerts();
    }).then(function (result) {
        if (document.getElementById("gestures").checked)
            return handConfiguration.EnableAllGestures(false);
        else
            return handConfiguration.DisableAllGestures();
    }).then(function (result) {
        return handConfiguration.ApplyChanges();
    }).then(function (result) {
        return sense.QueryCaptureManager();
    }).then(function (capture) {
        return capture.QueryImageSize(pxcmConst.PXCMCapture.STREAM_TYPE_DEPTH);
    }).then(function (result) {
        imageSize = result.size;
        return sense.StreamFrames();
    }).then(function (result) {
        status('Streaming ' + imageSize.width + 'x' + imageSize.height);
    }).catch(function (error) {
        status('Init failed: ' + JSON.stringify(error));
    });

    function clear() {
        $('#alerts_status').text('');
        $('#gestures_status').text('');
        document.getElementById("Start").disabled = false;
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
    }

    $('#Stop').click(function () {
        document.getElementById("Stop").disabled = true;
        sense.Close().then(function (result) {
            status('Stopped');
            clear();
        });
    });

    function onHandData(mid, module, data) {
        /*var canvas = document.getElementById('myCanvas'),*/
            /*context = canvas.getContext('2d'),*/
            /*radius = 5,*/
            /*scale = 1;*/

        /*canvas.width = imageSize.width;*/
        /*canvas.height = imageSize.height;*/

        if(!_.has(data, 'hands')) {
            status('NO HANDS!!');
        } else {
            status('Found ' + _.size(data.hands) + ' hand');
            _.each(data.hands, function(hand) {
                /*drawHandOnCanvas(hand, context);*/
            });
        }

        if(_.has(data, 'gestures')) {
            for (g = 0; g < data.gestures.length; g++) {
                currentGesture(data.gestures[g]);
            }
        }
    }

    /*function drawHandOnCanvas(hand, context) {
        var joints = hand.trackedJoint,
            baseX = joints[0].positionImage.x,
            baseY = joints[0].positionImage.y,
            wristX = joints[0].positionImage.x,
            wristY = joints[0].positionImage.y;

        for (j = 0; j < joints.length; j++) {
            if (joints[j] == null || joints[j].confidence <= 0) continue;

            var x = joints[j].positionImage.x;
            var y = joints[j].positionImage.y;

            context.beginPath();
            context.arc(x * scale, y * scale, radius, 0, 2 * Math.PI);
            context.lineWidth = 2;
            context.strokeStyle = 'green';
            context.stroke();

            if (j == 2 || j == 6 || j == 10 || j == 14 || j == 18) {
                baseX = wristX;
                baseY = wristY;
            }

            context.beginPath();
            context.moveTo(baseX * scale, baseY * scale);
            context.lineTo(x * scale, y * scale);
            context.stroke();

            baseX = x;
            baseY = y;
        }
    }*/

    function onConnect(data) {
        if (data.connected == false) {
            $('#alerts_status').append('Alert: ' + JSON.stringify(data) + '
');
        }
    }

    function onStatus(data) {
        if (data.sts < 0) {
            status('Error ' + data.sts);
            clear();
        }
    }

    function currentGesture(gesture) {
        $('#currentGesture').text(gesture.name);

        if(gesture.name === 'thumb_up') {
            status('VOTING YES');
            sense.Close().then(function (result) {
                status('Stopped');
                clear();
                $.post('/vote/yes')
                    .success(_goToNextStep);
            });

        } else if(gesture.name === 'thumb_down') {
            status('VOTING NO');
            sense.Close().then(function (result) {
                status('Stopped');
                clear();
                $.post('/vote/no')
                    .success(_goToNextStep);
            });
        }
    }

    function status(msg) {
        $('#status').text(msg);
    }

    function _goToNextStep() {
        $('#nextStep').click();
    }
});
/* jshint ignore:end */
<commit_msg>More.<commit_after>/* jshint ignore:start */
$(document).ready(function () {
    var sense;
    var imageSize;
    var handModule;
    var handConfiguration;

    // check platform compatibility
    /*RealSenseInfo(['hand'], function (info) {
        if (info.IsReady == true) {
            $('#info').append('Platform supports Intel(R) RealSense(TM) SDK feature');
            status('OK');
            document.getElementById("Start").disabled = false;
        } else {
            status('Platform not supported: ' + info.responseText);
            if (info.IsPlatformSupported != true) {
                $('#info').append('Intel� RealSense� 3D camera not found');
            } else if (info.IsBrowserSupported != true) {
                $('#info').append('Please update your browser to latest version');
            } else {
                $('#info').append('Please download and install the following update(s) before running sample: ');
                for (i = 0; i < info.Updates.length; i++) {
                    $('#info').append('' + info.Updates[i].href + '
');
                }
            }
        }
    })*/

    PXCMSenseManager_CreateInstance().then(function (result) {
        sense = result;
        return sense.EnableHand(onHandData);
    }).then(function (result) {
        handModule = result;
        status('Init started');
        return sense.Init(onConnect, onStatus);
    }).then(function (result) {
        return handModule.CreateActiveConfiguration();
    }).then(function (result) {
        handConfiguration = result;
        return handConfiguration.DisableAllAlerts();
    }).then(function (result) {
        if (document.getElementById("gestures").checked)
            return handConfiguration.EnableAllGestures(false);
        else
            return handConfiguration.DisableAllGestures();
    }).then(function (result) {
        return handConfiguration.ApplyChanges();
    }).then(function (result) {
        return sense.QueryCaptureManager();
    }).then(function (capture) {
        return capture.QueryImageSize(pxcmConst.PXCMCapture.STREAM_TYPE_DEPTH);
    }).then(function (result) {
        imageSize = result.size;
        return sense.StreamFrames();
    }).then(function (result) {
        status('Streaming ' + imageSize.width + 'x' + imageSize.height);
    }).catch(function (error) {
        status('Init failed: ' + JSON.stringify(error));
    });

    function clear() {
        $('#alerts_status').text('');
        $('#gestures_status').text('');
        document.getElementById("Start").disabled = false;
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
    }

    $('#Stop').click(function () {
        document.getElementById("Stop").disabled = true;
        sense.Close().then(function (result) {
            status('Stopped');
            clear();
        });
    });

    function onHandData(mid, module, data) {
        /*var canvas = document.getElementById('myCanvas'),*/
            /*context = canvas.getContext('2d'),*/
            /*radius = 5,*/
            /*scale = 1;*/

        /*canvas.width = imageSize.width;*/
        /*canvas.height = imageSize.height;*/

        if(!_.has(data, 'hands')) {
            status('NO HANDS!!');
        } else {
            status('Found ' + _.size(data.hands) + ' hand');
            _.each(data.hands, function(hand) {
                /*drawHandOnCanvas(hand, context);*/
            });
        }

        if(_.has(data, 'gestures')) {
            for (g = 0; g < data.gestures.length; g++) {
                currentGesture(data.gestures[g]);
            }
        }
    }

    /*function drawHandOnCanvas(hand, context) {
        var joints = hand.trackedJoint,
            baseX = joints[0].positionImage.x,
            baseY = joints[0].positionImage.y,
            wristX = joints[0].positionImage.x,
            wristY = joints[0].positionImage.y;

        for (j = 0; j < joints.length; j++) {
            if (joints[j] == null || joints[j].confidence <= 0) continue;

            var x = joints[j].positionImage.x;
            var y = joints[j].positionImage.y;

            context.beginPath();
            context.arc(x * scale, y * scale, radius, 0, 2 * Math.PI);
            context.lineWidth = 2;
            context.strokeStyle = 'green';
            context.stroke();

            if (j == 2 || j == 6 || j == 10 || j == 14 || j == 18) {
                baseX = wristX;
                baseY = wristY;
            }

            context.beginPath();
            context.moveTo(baseX * scale, baseY * scale);
            context.lineTo(x * scale, y * scale);
            context.stroke();

            baseX = x;
            baseY = y;
        }
    }*/

    function onConnect(data) {
        if (data.connected == false) {
            $('#alerts_status').append('Alert: ' + JSON.stringify(data) + '
');
        }
    }

    function onStatus(data) {
        if (data.sts < 0) {
            status('Error ' + data.sts);
            clear();
        }
    }

    function currentGesture(gesture) {
        $('#currentGesture').text(gesture.name);

        if(gesture.name === 'thumb_up') {
            status('VOTING YES');
            sense.Close().then(function (result) {
                status('Stopped');
                clear();
                $.post('/vote/yes', _goToNextStep);
            });

        } else if(gesture.name === 'thumb_down') {
            status('VOTING NO');
            sense.Close().then(function (result) {
                status('Stopped');
                clear();
                $.post('/vote/no', _goToNextStep);
            });
        }
    }

    function status(msg) {
        $('#status').text(msg);
    }

    function _goToNextStep() {
        $('#nextStep').click();
    }
});
/* jshint ignore:end */
<|endoftext|>


<commit_before>/**
 * jQuery Input Sheeper plugin.
 *
 */
(function($) {
    $.sheeper = $.inputSheeper = function(element, options) {
        var plugin = this,
            defaults = {
                selector: ".sheep", // Each sheep must have this selector in template.
                addSelector: ".sheep-link", // Add button (new sheep in the list).
                removeSelector: ".unsheep-link", // Remove button in the prototype.
                moveUpSelector: ".sheepup-link", // Move up button in the prototype.
                moveDownSelector: ".sheepdown-link", // Move up button in the prototype.
                min: 1, // Minimum number of sheeps in the list.
                max: 100,
                prepend: false, // By default, append new element. Set prepend to true to prepend new sheeps.
                afterInit: function(element) {
                    return true;
                },
                afterSheep: function(element) {
                    return true;
                },
                beforeUnsheep: function(element) {
                    return true;
                },
                afterUnsheep: function(element) {
                    return true;
                }
            },
            $element = $(element),
            $wrapper,
            ids = [];

        plugin.settings = {};

        /**
         *
         * @return {[type]} [description]
         */
        plugin.init = function()
        {
            plugin.settings = $.extend({}, defaults, $element.data(), options);
            // Container for sheeps.
            $wrapper = (plugin.settings.container) ? $element.find(plugin.settings.container) : $element;

            if(! plugin.settings.prototype) {
                console.error("No template found. Please provide a template using the 'prototype' javascript option or data-prototype HTML attribute.");
                return;
            }

            if(plugin.settings.prototype.match('^(#|\\.)[a-zA-Z].*')) {
                // Prototype is an id (#) or a class (.)
                var $template = $(plugin.settings.prototype);

                if ($template.length === 0) {
                    console.error("No template found. Prototype '" + plugin.settings.prototype + "' does not exists.");
                    return;
                }

                // Hide the template and retrieve its content for latter use.
                $template.hide();
                plugin.settings.prototype = $template.html();
            }

            // Do some init / apply stuffs.
            plugin.execute();
            plugin.settings.afterInit($element);
        };

        /**
         * Inits / apply DOM to this sheeper.
         *   - Called when init. @see init.
         *   - Called after an AJAX call. (that's why it's public ;) )
         * @return void
         */
        plugin.execute = function()
        {
            // Init the sheeper with existing sheeps.
            if (plugin.numberOfSheeps() > 0) {
                $wrapper.children().each(function() {
                    sheep(this);
                });
            }

            // If there's not enough sheeps in the herd, just sheep !
            var countSheepsAtInit = plugin.numberOfSheeps();
            if (countSheepsAtInit < plugin.settings.min) {
                for (var i = 0; i < (plugin.settings.min - countSheepsAtInit); i++) {
                    sheep();
                }
            }
            if (plugin.numberOfSheeps() === plugin.settings.min) {
                disableUnsheep();
            }
            // Actives the add link.
            $element.find(plugin.settings.addSelector).on("click", function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                sheep();
            });
            $wrapper.on("click", plugin.settings.removeSelector, function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                unsheep(this);
            });
            $wrapper.on("click", plugin.settings.moveUpSelector, function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                moveUp(this);
            });
            $wrapper.on("click", plugin.settings.moveDownSelector, function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                moveDown(this);
            });
        }

        /**
         * Creates (or registers) a new sheep in the herd.
         * @param  Element e  Opt: the sheep to add to the herd.
         * @return void.
         */
        var sheep = function(e)
        {
            if (plugin.numberOfSheeps() >= plugin.settings.max) {
                return;
            }
            if (e) {
                // Only registers the sheep in the herd.
                var $e = $(e),
                    id = $(e).data("sheep-id");

                if(id === undefined) {
                    // data-sheep-id is not defined on the element, making one.
                    id = getId();
                    $e.data("sheep-id", id);
                }

                ids.push(id);

                plugin.settings.afterSheep($e);
                $e.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            } else {
                var id = getId();

                // Creates a new sheep.
                var $sheep = $(plugin.settings.prototype.replace(/(__|\{\{)\s?name\s?(__|\}\})/gi, id));

                // Sets the sheep ID.
                $sheep.data("sheep-id", id);
                ids.push(id);

                if (plugin.settings.prepend) {
                    $wrapper.prepend($sheep);
                } else {
                    $wrapper.append($sheep);
                }
                // Registers the sheep in the herd.
                plugin.settings.afterSheep($sheep);
                $sheep.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            }

            refresh();
        }

        /**
         * Deletes a sheep element.
         * @param  Element e The '.unsheep-link' clicked.
         * @return void
         */
        var unsheep = function(e)
        {
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                var $sheep = $(e).closest(plugin.settings.selector);
                plugin.settings.beforeUnsheep($sheep);
                $sheep.trigger(
                    $.Event('unsheep.jq.sheeper', {})
                );

                // Removes the sheep.
                $sheep.remove();

                plugin.settings.afterUnsheep($sheep);
                $wrapper.trigger(
                    $.Event('unsheeped.jq.sheeper', {
                        relatedTarget: $sheep
                    })
                );
            }

            refresh();
        }

        /**
         * Move up sheep element.
         * @param  Element e The '.move-up-sheep-link' clicked.
         * @return void
         */
        var moveUp = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $previous = $sheep.prev(plugin.settings.selector);

            if($previous.length) {
                updateIndex($sheep, $previous);
                $sheep.detach().insertBefore($previous);
            }

            refresh();
        }

        /**
         * Move down sheep element.
         * @param  Element e The '.move-down-sheep-link' clicked.
         * @return void
         */
        var moveDown = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $next = $sheep.next(plugin.settings.selector);

            if($next.length) {
                updateIndex($sheep, $next);
                $sheep.detach().insertAfter($next);
            }

            refresh();
        }

        plugin.getSheeps = function()
        {
            return $wrapper.children(plugin.settings.selector);
        }

        plugin.numberOfSheeps = function()
        {
            return plugin.getSheeps().length;
        }

        var refresh = function()
        {
            // Get sheeps list.
            var $sheeps = plugin.getSheeps();

            // Enable/Disable sheeping.
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                enableUnsheep();
            } else {
                disableUnsheep();
            }

            // Enable/Disable unsheeping.
            if (plugin.numberOfSheeps() < plugin.settings.max) {
                enableSheep();
            } else {
                disableSheep();
            }

            // Remove .disabled class on every move up & move down trigger.
            $sheeps.each(function(i, e) {
                var $e = $(e);
                $e.find(plugin.settings.moveUpSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
                $e.find(plugin.settings.moveDownSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
            });

            // Disable move up for the first sheep.
            $sheeps.first().find(plugin.settings.moveUpSelector).addClass("disabled");

            // Disable move down for the last sheep.
            $sheeps.last().find(plugin.settings.moveDownSelector).addClass("disabled");
        }

        /**
         * Enable the "sheep" feature.
         * @return void
         */
        var enableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).removeClass("disabled");
        }

        /**
         * Disable the "unsheep" feature.
         * @return void
         */
        var disableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).addClass("disabled");
        }

        /**
         * Enable the ability to unhseep.
         * @return void
         */
        var enableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).removeClass("disabled");
        }

        /**
         * Disable the ability to unsheep.
         * @return void
         */
        var disableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).addClass("disabled");
        }

        /**
         * Get the longest commong string in an array of strings.
         *   Ex. ['interspecies', 'interstelar', 'interstate'])  => 'inters'
         * @param  Array<String> array
         * @return String
         */
        var sharedStart = function(array) {
          var A= array.concat().sort(),
          a1= A[0], a2= A[A.length-1], L= a1.length, i= 0;
          while(i<L && a1.charAt(i)=== a2.charAt(i)) i++;
          return a1.substring(0, i);
        }

        /**
         * Find the root name attribute to swap on move-up / move-down.
         * @param  Array array
         * @return String
         */
        var findRootNameAttr = function($fields) {
          return sharedStart($fields.map(function(i, e) {
            return $(e).attr('name');
          }).get());
        }

        /**
         * Swap sheep id and form name.
         * @param  jQuery $element1
         * @param  jQuery $element2
         */
        var updateIndex = function ($element1, $element2)
        {
          // Get all fields within element1.
          var $fields1 = $element1.find("input, select, textarea");

          // Get all fields within element2.
          var $fields2 = $element2.find("input, select, textarea");

          if ($fields1.length === 0 || $fields.length === 0) {
            // Skip; no input / select / textarea in sheep template.
            return;
          }

          // Defines root name attributes to be swaped.
          var rootName1 = findRootNameAttr($fields1),
              rootName2 = findRootNameAttr($fields2);

          // Replace names from $element1 by those in $elements2
          $fields1.each(function (i, e) {
            $(e).attr('name', $(e).attr('name').replace(rootName1, rootName2));
          });

          // Replace names from $element2 by those in $elements1
          $fields2.each(function (i, e) {
            $(e).attr('name', $(e).attr('name').replace(rootName2, rootName1));
          });
        }

        /**
         * Generate a new (unused) sheep id.
         * @return Int
         */
        var getId = function()
        {
            var id = 0;
            while($.inArray(id, ids) !== -1) {
                id++;
            }

            return id;
        }

        plugin.init();
    }

    $.fn.sheeper = $.fn.inputSheeper = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('inputSheeper')) {
                var plugin = new $.sheeper(this, options);
                $(this).data('inputSheeper', plugin);
            }
        });
    }

    /**
     * DATA-* ATTRIBUTES API
     *
     * Use data-* attributes to enable/configure your sheeper components.
     */
    $(document).ready(function() {
        $('[data-toggle="sheeper"]').sheeper({});
    });
})(jQuery);
<commit_msg>Add callbacks: beforeMove, beforeMoveUp, beforeMoveDown, afterMove, afterMoveUp, afterMoveDown<commit_after>/**
 * jQuery Input Sheeper plugin.
 *
 */
(function($) {
    $.sheeper = $.inputSheeper = function(element, options) {
        var plugin = this,
            defaults = {
                selector: ".sheep", // Each sheep must have this selector in template.
                addSelector: ".sheep-link", // Add button (new sheep in the list).
                removeSelector: ".unsheep-link", // Remove button in the prototype.
                moveUpSelector: ".sheepup-link", // Move up button in the prototype.
                moveDownSelector: ".sheepdown-link", // Move up button in the prototype.
                min: 1, // Minimum number of sheeps in the list.
                max: 100,
                prepend: false, // By default, append new element. Set prepend to true to prepend new sheeps.
                afterInit: function(element) {
                    return true;
                },
                afterSheep: function(element) {
                    return true;
                },
                beforeUnsheep: function(element) {
                    return true;
                },
                afterUnsheep: function(element) {
                    return true;
                },
                beforeMove: function(element) {
                    return true;
                },
                afterMove: function(element) {
                    return true;
                },
                beforeMoveUp: function(element) {
                    return true;
                },
                afterMoveUp: function(element) {
                    return true;
                },
                beforeMoveDown: function(element) {
                    return true;
                },
                afterMoveDown: function(element) {
                    return true;
                }
            },
            $element = $(element),
            $wrapper,
            ids = [];

        plugin.settings = {};

        /**
         *
         * @return {[type]} [description]
         */
        plugin.init = function()
        {
            plugin.settings = $.extend({}, defaults, $element.data(), options);
            // Container for sheeps.
            $wrapper = (plugin.settings.container) ? $element.find(plugin.settings.container) : $element;

            if(! plugin.settings.prototype) {
                console.error("No template found. Please provide a template using the 'prototype' javascript option or data-prototype HTML attribute.");
                return;
            }

            if(plugin.settings.prototype.match('^(#|\\.)[a-zA-Z].*')) {
                // Prototype is an id (#) or a class (.)
                var $template = $(plugin.settings.prototype);

                if ($template.length === 0) {
                    console.error("No template found. Prototype '" + plugin.settings.prototype + "' does not exists.");
                    return;
                }

                // Hide the template and retrieve its content for latter use.
                $template.hide();
                plugin.settings.prototype = $template.html();
            }

            // Do some init / apply stuffs.
            plugin.execute();
            plugin.settings.afterInit($element);
        };

        /**
         * Inits / apply DOM to this sheeper.
         *   - Called when init. @see init.
         *   - Called after an AJAX call. (that's why it's public ;) )
         * @return void
         */
        plugin.execute = function()
        {
            // Init the sheeper with existing sheeps.
            if (plugin.numberOfSheeps() > 0) {
                $wrapper.children().each(function() {
                    sheep(this);
                });
            }

            // If there's not enough sheeps in the herd, just sheep !
            var countSheepsAtInit = plugin.numberOfSheeps();
            if (countSheepsAtInit < plugin.settings.min) {
                for (var i = 0; i < (plugin.settings.min - countSheepsAtInit); i++) {
                    sheep();
                }
            }
            if (plugin.numberOfSheeps() === plugin.settings.min) {
                disableUnsheep();
            }
            // Actives the add link.
            $element.find(plugin.settings.addSelector).on("click", function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                sheep();
            });
            $wrapper.on("click", plugin.settings.removeSelector, function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                unsheep(this);
            });
            $wrapper.on("click", plugin.settings.moveUpSelector, function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                moveUp(this);
            });
            $wrapper.on("click", plugin.settings.moveDownSelector, function(e) {
                e.preventDefault();

                if($(this).is(".disabled,:disabled")) {
                    return;
                }

                moveDown(this);
            });
        }

        /**
         * Creates (or registers) a new sheep in the herd.
         * @param  Element e  Opt: the sheep to add to the herd.
         * @return void.
         */
        var sheep = function(e)
        {
            if (plugin.numberOfSheeps() >= plugin.settings.max) {
                return;
            }
            if (e) {
                // Only registers the sheep in the herd.
                var $e = $(e),
                    id = $(e).data("sheep-id");

                if(id === undefined) {
                    // data-sheep-id is not defined on the element, making one.
                    id = getId();
                    $e.data("sheep-id", id);
                }

                ids.push(id);

                plugin.settings.afterSheep($e);
                $e.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            } else {
                var id = getId();

                // Creates a new sheep.
                var $sheep = $(plugin.settings.prototype.replace(/(__|\{\{)\s?name\s?(__|\}\})/gi, id));

                // Sets the sheep ID.
                $sheep.data("sheep-id", id);
                ids.push(id);

                if (plugin.settings.prepend) {
                    $wrapper.prepend($sheep);
                } else {
                    $wrapper.append($sheep);
                }
                // Registers the sheep in the herd.
                plugin.settings.afterSheep($sheep);
                $sheep.trigger(
                    $.Event('sheeped.jq.sheeper', {})
                );
            }

            refresh();
        }

        /**
         * Deletes a sheep element.
         * @param  Element e The '.unsheep-link' clicked.
         * @return void
         */
        var unsheep = function(e)
        {
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                var $sheep = $(e).closest(plugin.settings.selector);
                plugin.settings.beforeUnsheep($sheep);
                $sheep.trigger(
                    $.Event('unsheep.jq.sheeper', {})
                );

                // Removes the sheep.
                $sheep.remove();

                plugin.settings.afterUnsheep($sheep);
                $wrapper.trigger(
                    $.Event('unsheeped.jq.sheeper', {
                        relatedTarget: $sheep
                    })
                );
            }

            refresh();
        }

        /**
         * Move up sheep element.
         * @param  Element e The '.move-up-sheep-link' clicked.
         * @return void
         */
        var moveUp = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $previous = $sheep.prev(plugin.settings.selector);

            if($previous.length) {
                // Setup some callbacks.
                plugin.settings.beforeMove($sheep);
                plugin.settings.beforeMoveUp($sheep);

                updateIndex($sheep, $previous);
                $sheep.detach().insertBefore($previous);

                // Setup some callbacks.
                plugin.settings.afterMoveUp($sheep);
                plugin.settings.afterMove($sheep);
            }

            refresh();
        }

        /**
         * Move down sheep element.
         * @param  Element e The '.move-down-sheep-link' clicked.
         * @return void
         */
        var moveDown = function(e)
        {
            var $sheep = $(e).parents(plugin.settings.selector),
                $next = $sheep.next(plugin.settings.selector);

            if($next.length) {
                // Setup some callbacks.
                plugin.settings.beforeMove($sheep);
                plugin.settings.beforeMoveDown($sheep);

                updateIndex($sheep, $next);
                $sheep.detach().insertAfter($next);

                // Setup some callbacks.
                plugin.settings.afterMoveDown($sheep);
                plugin.settings.afterMove($sheep);
            }

            refresh();
        }

        plugin.getSheeps = function()
        {
            return $wrapper.children(plugin.settings.selector);
        }

        plugin.numberOfSheeps = function()
        {
            return plugin.getSheeps().length;
        }

        var refresh = function()
        {
            // Get sheeps list.
            var $sheeps = plugin.getSheeps();

            // Enable/Disable sheeping.
            if (plugin.numberOfSheeps() > plugin.settings.min) {
                enableUnsheep();
            } else {
                disableUnsheep();
            }

            // Enable/Disable unsheeping.
            if (plugin.numberOfSheeps() < plugin.settings.max) {
                enableSheep();
            } else {
                disableSheep();
            }

            // Remove .disabled class on every move up & move down trigger.
            $sheeps.each(function(i, e) {
                var $e = $(e);
                $e.find(plugin.settings.moveUpSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
                $e.find(plugin.settings.moveDownSelector).each(function(i, e) {
                    $(e).removeClass("disabled");
                });
            });

            // Disable move up for the first sheep.
            $sheeps.first().find(plugin.settings.moveUpSelector).addClass("disabled");

            // Disable move down for the last sheep.
            $sheeps.last().find(plugin.settings.moveDownSelector).addClass("disabled");
        }

        /**
         * Enable the "sheep" feature.
         * @return void
         */
        var enableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).removeClass("disabled");
        }

        /**
         * Disable the "unsheep" feature.
         * @return void
         */
        var disableSheep = function()
        {
            $wrapper.find(plugin.settings.addSelector).addClass("disabled");
        }

        /**
         * Enable the ability to unhseep.
         * @return void
         */
        var enableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).removeClass("disabled");
        }

        /**
         * Disable the ability to unsheep.
         * @return void
         */
        var disableUnsheep = function()
        {
            $wrapper.find(plugin.settings.removeSelector).addClass("disabled");
        }

        /**
         * Get the longest commong string in an array of strings.
         *   Ex. ['interspecies', 'interstelar', 'interstate'])  => 'inters'
         * @param  Array<String> array
         * @return String
         */
        var sharedStart = function(array) {
          var A= array.concat().sort(),
          a1= A[0], a2= A[A.length-1], L= a1.length, i= 0;
          while(i<L && a1.charAt(i)=== a2.charAt(i)) i++;
          return a1.substring(0, i);
        }

        /**
         * Find the root name attribute to swap on move-up / move-down.
         * @param  Array array
         * @return String
         */
        var findRootNameAttr = function($fields) {
          return sharedStart($fields.map(function(i, e) {
            return $(e).attr('name');
          }).get());
        }

        /**
         * Swap sheep id and form name.
         * @param  jQuery $element1
         * @param  jQuery $element2
         */
        var updateIndex = function ($element1, $element2)
        {
          // Get all fields within element1.
          var $fields1 = $element1.find("input, select, textarea");

          // Get all fields within element2.
          var $fields2 = $element2.find("input, select, textarea");

          if ($fields1.length === 0 || $fields.length === 0) {
            // Skip; no input / select / textarea in sheep template.
            return;
          }

          // Defines root name attributes to be swaped.
          var rootName1 = findRootNameAttr($fields1),
              rootName2 = findRootNameAttr($fields2);

          // Replace names from $element1 by those in $elements2
          $fields1.each(function (i, e) {
            $(e).attr('name', $(e).attr('name').replace(rootName1, rootName2));
          });

          // Replace names from $element2 by those in $elements1
          $fields2.each(function (i, e) {
            $(e).attr('name', $(e).attr('name').replace(rootName2, rootName1));
          });
        }

        /**
         * Generate a new (unused) sheep id.
         * @return Int
         */
        var getId = function()
        {
            var id = 0;
            while($.inArray(id, ids) !== -1) {
                id++;
            }

            return id;
        }

        plugin.init();
    }

    $.fn.sheeper = $.fn.inputSheeper = function(options) {
        return this.each(function() {
            if (undefined == $(this).data('inputSheeper')) {
                var plugin = new $.sheeper(this, options);
                $(this).data('inputSheeper', plugin);
            }
        });
    }

    /**
     * DATA-* ATTRIBUTES API
     *
     * Use data-* attributes to enable/configure your sheeper components.
     */
    $(document).ready(function() {
        $('[data-toggle="sheeper"]').sheeper({});
    });
})(jQuery);
<|endoftext|>


<commit_before>// requires that cordova files are placed in the src/3rdparty folder, and are all named cordova-[PLATFORM]-[VERSION].js
module.exports = function(grunt) {

  'use strict';

  var targetFolder = "compile_ios";
  var sourceFolder = "src";

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

      copy: {
          main: {
              files: [
                  { expand: true, cwd : sourceFolder, src: ['**'], dest: targetFolder + '/' },
                  { src: [ sourceFolder + '/app/settings-ios.js'], dest : targetFolder + '/app/settings.js', filter: 'isFile' }
              ]
          }
      },

      uglify: {
        my_target: {
          files: [
            { cwd: targetFolder + '/3rdparty', src: '**/*.js', dest:  targetFolder + '/3rdparty', expand: true },
            { cwd: targetFolder + '/app', src: '**/*.js', dest: targetFolder + '/app', expand: true },
            { cwd: targetFolder + '/views', src: '**/*.js', dest: targetFolder + '/views', expand: true }
          ]
        }
      },

      cssmin: {
        minify: {
          expand: true,
          cwd: sourceFolder + '/css',
          src: ['*.css', '!*.min.css'],
          dest: targetFolder + '/css/',
          ext: '.css'
        }
      },

      clean: [
        targetFolder + "/shims/disposable",
        targetFolder + "/css-sass",
        targetFolder + "/tests",
        targetFolder + "/config.rb",
        targetFolder + "/start compass.bat",
        targetFolder + "/app/settings-*.js"
      ],

      replace: {
          example: {
              // clear all shim files of content, but leave empty files
              src: [ targetFolder + '/shims/*.js'],
              dest: targetFolder + '/shims/',
              replacements: [{
                  from: /.*/g,
                  to: ''
              }]
          }
      }

  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-text-replace');

  // Default task(s).
  grunt.registerTask('default', ['copy', 'uglify', 'cssmin', 'clean' ,'replace']);

};<commit_msg>Added ios Require.js path to build script.<commit_after>// requires that cordova files are placed in the src/3rdparty folder, and are all named cordova-[PLATFORM]-[VERSION].js
module.exports = function(grunt) {

  'use strict';

  var targetFolder = "compile_ios";
  var sourceFolder = "src";

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

      copy: {
          main: {
              files: [
                  { expand: true, cwd : sourceFolder, src: ['**'], dest: targetFolder + '/' },
                  { src: [ sourceFolder + '/app/settings-ios.js'], dest : targetFolder + '/app/settings.js', filter: 'isFile' }
              ]
          }
      },

      uglify: {
        my_target: {
          files: [
            { cwd: targetFolder + '/3rdparty', src: '**/*.js', dest:  targetFolder + '/3rdparty', expand: true },
            { cwd: targetFolder + '/app', src: '**/*.js', dest: targetFolder + '/app', expand: true },
            { cwd: targetFolder + '/views', src: '**/*.js', dest: targetFolder + '/views', expand: true }
          ]
        }
      },

      cssmin: {
        minify: {
          expand: true,
          cwd: sourceFolder + '/css',
          src: ['*.css', '!*.min.css'],
          dest: targetFolder + '/css/',
          ext: '.css'
        }
      },

      clean: [
        targetFolder + "/shims/disposable",
        targetFolder + "/css-sass",
        targetFolder + "/tests",
        targetFolder + "/config.rb",
        targetFolder + "/start compass.bat",
        targetFolder + "/app/settings-*.js"
      ],

      replace: {

          requireRoot: {
              src: [ targetFolder + '/app/haku.js'],
              dest: targetFolder + '/app/',
              replacements: [{
                  from: /haku.settings.systemPathRoot="\/"/g,
                  to: 'haku.settings.systemPathRoot=window.location.pathname.replace("index.html", "");'
              }]
          },

          removeShims: {
              // clear all shim files of content, but leave empty files
              src: [ targetFolder + '/shims/*.js'],
              dest: targetFolder + '/shims/',
              replacements: [{
                  from: /.*/g,
                  to: ''
              }]
          }
      }

  });

  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-cssmin');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-text-replace');

  // Default task(s).
  grunt.registerTask('default', ['copy', 'uglify', 'cssmin', 'clean' ,'replace']);

};<|endoftext|>