<commit_before>/** @type {?lf.Database} */
var db = null;

/**
 * The data model observed by UI.
 * @type {{count: number}}
 */
var model = {
    count: 0
};

var query;

var title = ".+";

var author = ".+";

// When the page loads.
$(function() {
    main().then(function() {
        // Simulate Controller/Model bindings.
        setUpBinding();
        setUpSearch();
        selectAllBooks();
    });
});

function setUpSearch() {

    $('#title').keyup(function() {

        var value = $(this).val();
        if (value.length <= 3) {
            value = ".+";
        }

        title = value;
        selectAllBooks();
    });

    $('#author').keyup(function() {

        var value = $(this).val();
        if (value.length <= 3) {
            value = ".+";
        }

        author = value;
        selectAllBooks();
    });
}

function setUpBinding() {
    var book = db.getSchema().table('Book');
    query = db.select(lf.fn.count(book.title).as('num')).
        from(book)
    ;

    db.observe(query, function(changes) {
        model.count = changes[0].object[0]['num'];
    });
}

/**
 * Selects all books.
 */
function selectAllBooks() {

    var $bookLists = $('#books-list');
    $bookLists.empty();

    var $titleFormGroup = $("#titleFormGroup");
    var $titleHelpBox = $("#titleHelpBox");

    var $authorFormGroup = $("#authorFormGroup");
    var $authorHelpBox =$("#authorHelpBox");

    try {
        var regexpTitle = new RegExp(title, 'i');
    } catch (e) {

        $titleFormGroup.addClass('has-error');
        $titleHelpBox.show();

        return;
    }

    try {
        var regexpAuthor = new RegExp(title, 'i');
    } catch (e) {

        $authorFormGroup.addClass('has-error');
        $authorHelpBox.show();

        return;
    }

    $titleFormGroup.removeClass('has-error');
    $titleHelpBox.hide();
    $authorFormGroup.removeClass('has-error');
    $authorHelpBox.hide();

    var book = db.getSchema().table('Book');
    db.select(book.title, book.author)
        .from(book)
        .where(lf.op.and(
            book.title.match(regexpTitle),
            book.author.match(regexpAuthor)
        ))
        .exec().then(
        function(results) {

            $(results).each(function(index, result) {
                $bookLists.append('
' + result.title + ' - ' + result.author + '
');
            });
        }
    );
}

function main() {
    return book.db.getSchemaBuilder().connect({
        storeType: lf.schema.DataStoreType.INDEXED_DB
    }).then(function(database) {
        db = database;
        return checkForExistingData();
    }).then(function(dataExist) {
        return dataExist ? Promise.resolve() : addData();
    });
}

/**
 * Adds sample data to the database.
 * @return {!IThenable}
 */
function addData() {
    return Promise.all([
        insertData('books.json', db.getSchema().table('Book'))
    ]).then(function(queries) {
        var tx = db.createTransaction();
        return tx.exec(queries);
    });
}

/**
 * Inserts data in the database.
 * @param {string} filename The name of the file holding JSON data.
 * @param {!lf.schema.Table} tableSchema The schema of the table corresponding
 *     to the data.
 * @return {!IThenable<!lf.query.Insert>}
 */
function insertData(filename, tableSchema) {
    return getData(filename).then(
        function(data) {
            var rows = data.map(function(obj) {
                return tableSchema.createRow(obj);
            });
            return db.insert().into(tableSchema).values(rows);
        });
}

/**
 * Reads the sample data from a JSON file.
 * @param {string} filename The name of the JSON file to be loaded.
 * @return {!IThenable}
 */
function getData(filename) {
    return /** @type {!IThenable} */ ($.getJSON('data/' + filename));
}

/**
 * @return {!IThenable.<boolean>} Whether the DB is already populated with
 * sample data.
 */
function checkForExistingData() {
    var book = db.getSchema().table('Book');
    var column = lf.fn.count(book.title);
    return db.select(column).from(book).exec().then(
        function(rows) {
            return rows[0][column.getName()] > 0;
        });
}<commit_msg>Ooops<commit_after>/** @type {?lf.Database} */
var db = null;

/**
 * The data model observed by UI.
 * @type {{count: number}}
 */
var model = {
    count: 0
};

var query;

var title = ".+";

var author = ".+";

// When the page loads.
$(function() {
    main().then(function() {
        // Simulate Controller/Model bindings.
        setUpBinding();
        setUpSearch();
        selectAllBooks();
    });
});

function setUpSearch() {

    $('#title').keyup(function() {

        var value = $(this).val();
        if (value.length <= 3) {
            value = ".+";
        }

        title = value;
        selectAllBooks();
    });

    $('#author').keyup(function() {

        var value = $(this).val();
        if (value.length <= 3) {
            value = ".+";
        }

        author = value;
        selectAllBooks();
    });
}

function setUpBinding() {
    var book = db.getSchema().table('Book');
    query = db.select(lf.fn.count(book.title).as('num')).
        from(book)
    ;

    db.observe(query, function(changes) {
        model.count = changes[0].object[0]['num'];
    });
}

/**
 * Selects all books.
 */
function selectAllBooks() {

    var $bookLists = $('#books-list');
    $bookLists.empty();

    var $titleFormGroup = $("#titleFormGroup");
    var $titleHelpBox = $("#titleHelpBox");

    var $authorFormGroup = $("#authorFormGroup");
    var $authorHelpBox =$("#authorHelpBox");

    try {
        var regexpTitle = new RegExp(title, 'i');
    } catch (e) {

        $titleFormGroup.addClass('has-error');
        $titleHelpBox.show();

        return;
    }

    try {
        var regexpAuthor = new RegExp(author, 'i');
    } catch (e) {

        $authorFormGroup.addClass('has-error');
        $authorHelpBox.show();

        return;
    }

    $titleFormGroup.removeClass('has-error');
    $titleHelpBox.hide();
    $authorFormGroup.removeClass('has-error');
    $authorHelpBox.hide();

    var book = db.getSchema().table('Book');
    db.select(book.title, book.author)
        .from(book)
        .where(lf.op.and(
            book.title.match(regexpTitle),
            book.author.match(regexpAuthor)
        ))
        .exec().then(
        function(results) {

            $(results).each(function(index, result) {
                $bookLists.append('
' + result.title + ' - ' + result.author + '
');
            });
        }
    );
}

function main() {
    return book.db.getSchemaBuilder().connect({
        storeType: lf.schema.DataStoreType.INDEXED_DB
    }).then(function(database) {
        db = database;
        return checkForExistingData();
    }).then(function(dataExist) {
        return dataExist ? Promise.resolve() : addData();
    });
}

/**
 * Adds sample data to the database.
 * @return {!IThenable}
 */
function addData() {
    return Promise.all([
        insertData('books.json', db.getSchema().table('Book'))
    ]).then(function(queries) {
        var tx = db.createTransaction();
        return tx.exec(queries);
    });
}

/**
 * Inserts data in the database.
 * @param {string} filename The name of the file holding JSON data.
 * @param {!lf.schema.Table} tableSchema The schema of the table corresponding
 *     to the data.
 * @return {!IThenable<!lf.query.Insert>}
 */
function insertData(filename, tableSchema) {
    return getData(filename).then(
        function(data) {
            var rows = data.map(function(obj) {
                return tableSchema.createRow(obj);
            });
            return db.insert().into(tableSchema).values(rows);
        }
    );
}

/**
 * Reads the sample data from a JSON file.
 * @param {string} filename The name of the JSON file to be loaded.
 * @return {!IThenable}
 */
function getData(filename) {
    return /** @type {!IThenable} */ ($.getJSON('data/' + filename));
}

/**
 * @return {!IThenable.<boolean>} Whether the DB is already populated with
 * sample data.
 */
function checkForExistingData() {
    var book = db.getSchema().table('Book');
    var column = lf.fn.count(book.title);
    return db.select(column).from(book).exec().then(
        function(rows) {
            return rows[0][column.getName()] > 0;
        }
    );
}<|endoftext|>


<commit_before>/**
 * Percentage JS
 */

"use strict";

var Percentage = (function(){

    var p = {},
        time_suffix = { // in seconds
            ms  : 0.0001,
            sec : 1,
            min : 60,
            h   : 3600,
            d   : 86400,    // day
            w   : 604800,   // week  (7 days)
            m   : 2628000,  // month (based on 365days/12months = 30.41days)
            y   : 31536000, // year  (based on 365days)
        },
        filesize_suffix = {
            b   : 1,
            kb  : 10,
            mb  : 20,
            gb  : 30,
            tb  : 40,
            pb  : 50,
            eb  : 60,
            zb  : 70,
            yb  : 80,
        },
        length = {
            mm: 3,
            cm: 2,
            dm: 1,
            m : 1,
            ft: 1,
            in: 1,

        };

    /**
     * Calc percentage
     *
     * @param  integer n1
     * @param  integer n2
     * @param  integer dec
     *
     * @return
     */
    function perc(n1, n2, dec) {
        dec = (dec !== undefined) ? dec : perc.DEFAULT_DEMIMAL;
        var r = (n1/n2)*100;
        return r.toFixed(dec);
    }

    /**
     * Percentage of date
     *
     * @param  string d
     * @param  string start
     * @param  string end
     * @param  mixed  dec
     * @return integer
     */
    function dates(d, start, end, dec) {

        //firefox dont like '-', ie fail with space
        //so we replace '-'' by '/''
        d = d.replace(/-/g, '/');
        start = start.replace(/-/g, '/');
        end = end.replace(/-/g, '/');

        var d     = new Date(d).getTime(),
            start = new Date(start).getTime(),
            end   = new Date(end).getTime(),
            d1    = d - start,
            d2    = end - start;

        return perc(d1,d2,dec);
    }

    /**
     * Times
     *
     * @param  mixed t1
     * @param  mixed t2
     * @param  mixed dec
     * @return integer
     */
    function times(t1, t2, dec) {
        t1 = regexTimeTokens(t1) || regexTimeTokens2(t1);
        t2 = regexTimeTokens(t2) || regexTimeTokens2(t2);
        return perc(t1,t2,dec);
    }

    /**
     * File size (in bytes)
     *
     * @param  str     s1
     * @param  str     s2
     * @param  integer dec
     * @return integer
     */
    function filesize(s1, s2, dec) {
        s1 = regexFileSize(s1) || s1;
        s2 = regexFileSize(s2) || s2;
        return perc(s1,s2,dec);
    }

    /**
     * Regex time tokens (ex: 1d22min38sec)
     *
     * @param  string  str
     * @return integer
     */
    function regexTimeTokens(str) {

        var regex  = /([0-9]+)(h|min|sec|ms|y|d|m|w)/gi;
        var match = getMatches(regex, str), r = 0;

        if(match.length < 1) return false;

        // transform to matches to millisecond
        for(var i=0;i<match.length;++i) {
            var num = match[i][1];
            var str = match[i][2];
            r += (num * (time_suffix[str] * 1000));
        }

        return r;
    }

    /**
     * Regex time tokens (ex: 111:32:21.1553)
     *
     * @param  string str
     * @return integer
     */
    function regexTimeTokens2(str) {

        var regex = /:?([0-9]+)|(.[0-9]+)/gi;
        var match = getMatches(regex, str),
            r = 0, ms = 0,
            l = match.length;

        if(l > 0) {

            //millisecond
            if(match[l-1][2] !== undefined) {
                ms = match[l-1][2];
                match = match.slice(0,l-1);
                --l;
            }

            if(l == 3) {
                r = r + match[2][1]*1000;
                r = r + match[1][1]*60*1000;
                r = r + match[0][1]*60*60*1000;
            }
            else if(l == 2) {
                r = r + match[1][1]*1000;
                r = r + match[0][1]*60*1000;
            }
            else {
                r = r + match[0][1]*1000;
            }
        }

        return r*1 + ms*1;
    }

    /**
     * Regex for file size
     *
     * @param  string str
     * @return integer
     */
    function regexFileSize(str) {

        var regex  = /([0-9]*\.?[0-9]+)\s?(b|kb|mb|gb|tb|pb|eb|zb|yb)/gi;
        var match = getMatches(regex, str), r = 0;

        if(match.length < 1) return false;

        return match[0][1] * Math.pow(2, filesize_suffix[match[0][2].toLowerCase()]);
    }

    /**
     * Get matches
     *
     * @param  string regex
     * @param  string str
     * @return array
     */
    function getMatches(regex, str) {
        var m, match = [];

        while ((m = regex.exec(str)) != null) {
            match.push(m);
        }

        return match;
    }

    /**
     * Public stuff
     */
    perc.DEFAULT_DEMIMAL = 2,
    perc.dates    = dates;
    perc.times    = times;
    perc.num      = perc;
    perc.filesize = filesize;

    return perc;

})();<commit_msg>added lengths stuff, moved regex to top<commit_after>/**
 * Percentage JS
 */

"use strict";

var Percentage = (function(){

    var p = {},
        regex = {
            time1    : /([0-9]+)\s?(h|min|sec|ms|y|d|m|w)/gi,
            time2    : /:?([0-9]+)|(.[0-9]+)/gi,
            filesize : /([0-9]*\.?[0-9]+)\s?(b|kb|mb|gb|tb|pb|eb|zb|yb)/gi,
            length   : /([0-9]*\.?[0-9]+)\s?(mm|cm|dm|km|m|ft|in|yd)/gi
        },
        time_suffix = { // in seconds
            ms  : 0.0001,
            sec : 1,
            min : 60,
            h   : 3600,
            d   : 86400,    // day
            w   : 604800,   // week  (7 days)
            m   : 2628000,  // month (based on 365days/12months = 30.41days)
            y   : 31536000, // year  (based on 365days)
        },
        filesize_suffix = { // binary measurement
            b   : 1,
            kb  : 10,
            mb  : 20,
            gb  : 30,
            tb  : 40,
            pb  : 50,
            eb  : 60,
            zb  : 70,
            yb  : 80,
        },
        lengths_suffix = { // based on 1 meter
            mm: 0.001,
            cm: 0.01,
            dm: 0.1,
            m : 1,
            km: 1000,
            ft: 3.28084,
            in: 39.3701,
            yd: 1.0936
        };

    /**
     * Calc percentage
     *
     * @param  integer n1
     * @param  integer n2
     * @param  integer dec
     *
     * @return
     */
    function perc(n1, n2, dec) {
        dec = (dec !== undefined) ? dec : perc.DEFAULT_DEMIMAL;
        var r = (n1/n2)*100;
        return r.toFixed(dec);
    }

    /**
     * Percentage of date
     *
     * @param  string d
     * @param  string start
     * @param  string end
     * @param  mixed  dec
     * @return integer
     */
    function dates(d, start, end, dec) {

        //firefox dont like '-', ie fail with space
        //so we replace '-'' by '/''
        d = d.replace(/-/g, '/');
        start = start.replace(/-/g, '/');
        end = end.replace(/-/g, '/');

        var d     = new Date(d).getTime(),
            start = new Date(start).getTime(),
            end   = new Date(end).getTime(),
            d1    = d - start,
            d2    = end - start;

        return perc(d1,d2,dec);
    }

    /**
     * Times
     *
     * @param  mixed t1
     * @param  mixed t2
     * @param  mixed dec
     * @return integer
     */
    function times(t1, t2, dec) {
        t1 = regexTimeTokens(t1) || regexTimeTokens2(t1);
        t2 = regexTimeTokens(t2) || regexTimeTokens2(t2);
        return perc(t1,t2,dec);
    }

    /**
     * File size (in bytes)
     *
     * @param  str     s1
     * @param  str     s2
     * @param  integer dec
     * @return integer
     */
    function filesize(s1, s2, dec) {
        s1 = regexFileSize(s1) || s1;
        s2 = regexFileSize(s2) || s2;
        return perc(s1,s2,dec);
    }

    /**
     * Lengths
     *
     * @param  str     l1
     * @param  str     l2
     * @param  integer dec
     * @return integer
     */
    function lengths(l1, l2, dec) {
        l1 = regexLengths(l1) || l1;
        l2 = regexLengths(l2) || l2;
        return perc(l1,l2,dec);
    }

    /**
     * Regex time tokens (ex: 1d22min38sec)
     *
     * @param  string  str
     * @return integer
     */
    function regexTimeTokens(str) {

        var match = getMatches(regex.time1, str), r = 0;

        if(match.length < 1) return false;

        // transform to matches to millisecond
        for(var i=0;i<match.length;++i) {
            var num = match[i][1];
            var str = match[i][2];
            r += (num * (time_suffix[str] * 1000));
        }

        return r;
    }

    /**
     * Regex time tokens (ex: 111:32:21.1553)
     *
     * @param  string str
     * @return integer
     */
    function regexTimeTokens2(str) {

        var match = getMatches(regex.time2, str),
            r = 0, ms = 0,
            l = match.length;

        if(l > 0) {

            //millisecond
            if(match[l-1][2] !== undefined) {
                ms = match[l-1][2];
                match = match.slice(0,l-1);
                --l;
            }

            if(l == 3) {
                r = r + match[2][1]*1000;
                r = r + match[1][1]*60*1000;
                r = r + match[0][1]*60*60*1000;
            }
            else if(l == 2) {
                r = r + match[1][1]*1000;
                r = r + match[0][1]*60*1000;
            }
            else {
                r = r + match[0][1]*1000;
            }
        }

        return r*1 + ms*1;
    }

    /**
     * Regex for file size
     *
     * @param  string str
     * @return integer
     */
    function regexFileSize(str) {

        var match = getMatches(regex.filesize, str), r = 0;

        if(match.length < 1) return false;

        return match[0][1] * Math.pow(2, filesize_suffix[match[0][2].toLowerCase()]);
    }

    /**
     * Regex time tokens (ex: 1d22min38sec)
     *
     * @param  string  str
     * @return integer
     */
    function regexLengths(str) {

        var match = getMatches(regex.length, str), r = 0;

        //console.log(match)

        if(match.length < 1) return false;

        // transform to matches to meters
        for(var i=0;i<match.length;++i) {
            var num = match[i][1];
            var str = match[i][2];
            if(str == "yd" || str == "ft" || str == "in") {
                r += (num / lengths_suffix[str]);
                console.log(lengths_suffix[str], num);
            }
            else {
                r += (num * lengths_suffix[str]);
            }

            //console.log(lengths_suffix[str]);
        }

        return r;
    }

    /**
     * Get matches
     *
     * @param  string regex
     * @param  string str
     * @return array
     */
    function getMatches(regex, str) {
        var m, match = [];

        while ((m = regex.exec(str)) != null) {
            match.push(m);
        }

        return match;
    }

    /**
     * Public stuff
     */
    perc.DEFAULT_DEMIMAL = 2,
    perc.dates    = dates;
    perc.times    = times;
    perc.num      = perc;
    perc.filesize = filesize;
    perc.lengths  = lengths;

    return perc;

})();<|endoftext|>


<commit_before>/**
 * Created by Pjer1 on 10/5/2016.
 */

var demo="True";

 function upload_file(){

     var waiting=jQuery('#loading');
    waiting.removeClass("hide");
     var btn = jQuery('#upload_btn');
    var f_upload = new FormData();
    f_upload.append('file', $('#pdb-file')[0].files[0]);
    f_upload.append('plugin','ABACUS');
    f_upload.append('demo',demo);
     f_upload.append('amount',$('#amount')[0].value);
     f_upload.append('tag',$('#tag')[0].value);
     f_upload.append('action','design');
     //console.log(f_upload);
     $.ajax({
         type: "POST",
         url: "/plugin/",
         responseTime: 2000,
         data:f_upload,
         processData: false,
         contentType: false,
         success: function(response){
             var Jr = JSON.parse(response);
             if(Jr['success']==Jr['success']){//true) {
                 alert('The file has been accepted by server and being processed,it may take some time,we will email to inform you when finished', 3000, 'rounded');
                waiting.addClass(" hide");
                 btn.addClass(" disabled");
                 btn.onclick=function () {}
             }
             else {
                 Materialize.toast('Error : '+Jr['error'], 3000, 'rounded');
                waiting.addClass(" hide");
             }
         }
     });
    //.done(L.addClass("hide"));
    //console.log("haha")
}

function  get_status() {

    var data={"plugin":"ABACUS","action":"getstatus"};
    $.ajax({
        type:"POST",
        url:"/plugin/",
        data:data,
        success:function (response) {
            var Jr = JSON.parse(response);

        }
    })
}
<commit_msg>abacus connect<commit_after>/**
 * Created by Pjer1 on 10/5/2016.
 */

var demo="True";

 function upload_file(){

     var waiting=jQuery('#loading');
    waiting.removeClass("hide");
     var btn = jQuery('#upload_btn');
    var f_upload = new FormData();
    f_upload.append('file', $('#pdb-file')[0].files[0]);
    f_upload.append('plugin','ABACUS');
    f_upload.append('demo',demo);
     f_upload.append('amount',$('#amount')[0].value);
     f_upload.append('tag',$('#tag')[0].value);
     f_upload.append('action','design');
     //console.log(f_upload);
     $.ajax({
         type: "POST",
         url: "/plugin/",
         responseTime: 2000,
         data:f_upload,
         processData: false,
         contentType: false,
         success: function(response){
             var Jr = JSON.parse(response);
             if(Jr['success']==Jr['success']){//true) {
                 alert('The file has been accepted by server and being processed,it may take some time,we will email to inform you when finished', 3000, 'rounded');
                waiting.addClass(" hide");
                 btn.addClass(" disabled");
                 btn.onclick=function () {}
             }
             else {
                 Materialize.toast('Error : '+Jr['error'], 3000, 'rounded');
                waiting.addClass(" hide");
             }
         }
     });
    //.done(L.addClass("hide"));
    //console.log("haha")
}

function  get_status() {

    var data={"plugin":"ABACUS","action":"getstatus"};
    $.ajax({
        type:"POST",
        url:"/plugin/",
        data:data,
        success:function (response) {
            if (response.length>0){
                var Jr = JSON.parse(response);
                if(Jr.status == "Clear"){
                    alert("Ready to design")
                }
                if(Jr.status == "Failed"){
                    alert("reason : "+Jr.reason)
                }
                if(Jr.status == "Running"){
                    alert("Designing....(be patient)")
                }
                if(Jr.status == "Success"){
                    var sel_s = $('#get_status')[0];
                    sel_s.innerHTML = "Download File";
                    sel_s.href = Jr.url;
                }
            }
            else {alert("please connect to the server Admin for help")}
        }
    })
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
const co = require('co');
const prompt = require('co-prompt');
const program = require('commander');
const fs = require('fs');
const request = require('superagent');

console.log('welcome, let\'s create some plugins!');
console.log('run: syn-plugin <pluginName> or syn-plugin -h');
program
  .arguments('<pluginName>')
  .action(function (pluginName) {
    co(function *() {
      let mountPoint= yield prompt('mount point -> dashboard, post-feed or post-view: ');
      let description = yield prompt('plugin description: ');
      console.log(mountPoint, description, pluginName);
      // creating plugin directory and config file
      createDirAndFiles(pluginName, mountPoint);
      editServerFile(pluginName);
      createPlugin(pluginName, mountPoint);
    })
  })
  .parse(process.argv);
// console.log('it worked, feel safe to ctrl+C');

function createDirAndFiles(dirName, mountPoint) {
    let path = './plugins/'+dirName;
    let componentsDir = './plugins/'+dirName+'/components';
    let serverDir = './plugins/'+dirName+'/server';

    fs.mkdir(path, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('plugin dir created');

        //creating synth.js file
        fs.readFile('./tpl-plugin/synth.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/i, dirName);
          fileContents = fileContents.replace(/%mount_point%/i, mountPoint);
          fs.writeFile(path + "/synth.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('synth.js writing file succeeded');
              }
          });
        });

        //creating actions.js file
        fs.readFile('./tpl-plugin/actions.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(path + "/actions.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('actions.js writing file succeeded');
              }
          });
        });

        //creating actionTypes.js file
        fs.readFile('./tpl-plugin/actionTypes.js', 'utf8', function(err, fileContents) {
          fileContents = fileContents.replace(/%name%/gi, dirName);
          if (err) throw err;
          fs.writeFile(path + "/actionTypes.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('actionTypes.js writing file succeeded');
              }
          });
        });

        //creating constants.js file
        fs.readFile('./tpl-plugin/constants.js', 'utf8', function(err, fileContents) {
          fileContents = fileContents.replace(/%name%/gi, dirName);
          if (err) throw err;
          fs.writeFile(path + "/constants.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('constants.js writing file succeeded');
              }
          });
        });

        //creating index.js file
        fs.readFile('./tpl-plugin/index.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(path + "/index.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('index.js writing file succeeded');
              }
          });
        });

        //creating reducer.js file
        fs.readFile('./tpl-plugin/reducer.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(path + "/reducer.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('reducer.js writing file succeeded');
              }
          });
        });

      }
    });

    fs.mkdir(componentsDir, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('components dir created');
        fs.readFile('./tpl-plugin/components/Plugin.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(componentsDir+'/'+firstLetterUpperCase(dirName)+'.js', fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('components plugin writing file succeeded');
              }
          });
        });
      }
    });

    fs.mkdir(serverDir, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('server dir created');

        //creating controller.js in server folder
        fs.readFile('./tpl-plugin/server/controller.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/controller.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('server/controller.js writing file succeeded');
              }
          });
        });

        //creating routes.js in server folder
        fs.readFile('./tpl-plugin/server/routes.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/routes.js", fileContents, function(err) {
              if (err) {
                  console.log('server/routes.js error writing file', err);
              } else {
                  console.log('routes.js writing file succeeded');
              }
          });
        });

        //creating model.js in server folder
        fs.readFile('./tpl-plugin/server/model.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/model.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('server/model.js writing file succeeded');
              }
          });
        });

        //creating index.js in server folder
        fs.readFile('./tpl-plugin/server/index.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/index.js", fileContents, function(err) {
              if (err) {
                  console.log('error writing file', err);
              } else {
                  console.log('server/index.js writing file succeeded');
              }
          });
        });

      }
    });
}

function editServerFile(pluginName) {
    let pathServerFile = './admin/server/server.js';
    let requireStr = '//%%begin%%\nconst '+pluginName+'Routes = require(\'./plugins/'+pluginName+'/server\');\nrequire(\'./plugins/'+pluginName+'/server/routes\')(app);'
    fs.readFile(pathServerFile, 'utf8', function(err, fileContents) {
      if (err) throw err;
      console.log(typeof fileContents);
      fileContents = fileContents.replace(/\/\/%%begin%%/i, requireStr);
      fs.writeFile(pathServerFile, fileContents, function(err) {
          if (err) {
              console.log('error writing file', err);
          } else {
              console.log('writing file succeeded');
          }
      });
    });
  }

  function firstLetterUpperCase(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  function createPlugin(pluginName, mountPoint) {
      // creating the plugin on database
      let newPlugin = {};
      newPlugin.name = pluginName;
      newPlugin.mount_point = mountPoint;
      newPlugin.plugin_properties = [];

      console.log("...");
      console.log("... creating plugin");
      request
       .post('http://localhost:3000/api/plugin')
       .set('Accept', 'application/json')
       .send(newPlugin)
       .end(function (err, res) {
         if (err) {
          //  console.log(err.status);
           console.log('closing connection...');
        //    process.exit();
         } else {
          console.log("... OK... DONE");
         }
       });
  }<commit_msg>cli: synth-plugin cleaning<commit_after>#!/usr/bin/env node
const co = require('co');
const prompt = require('co-prompt');
const program = require('commander');
const fs = require('fs');
const request = require('superagent');

console.log('welcome, let\'s create some plugins!');
console.log('run: syn-plugin <pluginName> or syn-plugin -h');
program
  .arguments('<pluginName>')
  .action(function (pluginName) {
    co(function *() {
      let mountPoint= yield prompt('mount point -> dashboard, post-feed or post-view: ');
      let description = yield prompt('plugin description: ');
      console.log(mountPoint, description, pluginName);
      // creating plugin directory and config file
      createDirAndFiles(pluginName, mountPoint);
      editServerFile(pluginName);
      createPlugin(pluginName, mountPoint);
    })
  })
  .parse(process.argv);
// console.log('it worked, feel safe to ctrl+C');

function createDirAndFiles(dirName, mountPoint) {
    let path = './plugins/'+dirName;
    let componentsDir = './plugins/'+dirName+'/components';
    let serverDir = './plugins/'+dirName+'/server';

    fs.mkdir(path, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('plugin dir created');

        //creating synth.js file
        fs.readFile('./tpl-plugin/synth.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/i, dirName);
          fileContents = fileContents.replace(/%mount_point%/i, mountPoint);
          fs.writeFile(path + "/synth.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('synth.js writing file succeeded');
            }
          });
        });

        //creating actions.js file
        fs.readFile('./tpl-plugin/actions.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(path + "/actions.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('actions.js writing file succeeded');
            }
          });
        });

        //creating actionTypes.js file
        fs.readFile('./tpl-plugin/actionTypes.js', 'utf8', function(err, fileContents) {
          fileContents = fileContents.replace(/%name%/gi, dirName);
          if (err) throw err;
          fs.writeFile(path + "/actionTypes.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('actionTypes.js writing file succeeded');
            }
          });
        });

        //creating constants.js file
        fs.readFile('./tpl-plugin/constants.js', 'utf8', function(err, fileContents) {
          fileContents = fileContents.replace(/%name%/gi, dirName);
          if (err) throw err;
          fs.writeFile(path + "/constants.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('constants.js writing file succeeded');
            }
          });
        });

        //creating index.js file
        fs.readFile('./tpl-plugin/index.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(path + "/index.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('index.js writing file succeeded');
            }
          });
        });

        //creating reducer.js file
        fs.readFile('./tpl-plugin/reducer.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(path + "/reducer.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('reducer.js writing file succeeded');
            }
          });
        });

      }
    });

    fs.mkdir(componentsDir, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('components dir created');
        fs.readFile('./tpl-plugin/components/Plugin.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(componentsDir+'/'+firstLetterUpperCase(dirName)+'.js', fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('components plugin writing file succeeded');
            }
          });
        });
      }
    });

    fs.mkdir(serverDir, function(err) {
      if (err) {
        console.log(err);
      } else {
        console.log('server dir created');

        //creating controller.js in server folder
        fs.readFile('./tpl-plugin/server/controller.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/controller.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('server/controller.js writing file succeeded');
            }
          });
        });

        //creating routes.js in server folder
        fs.readFile('./tpl-plugin/server/routes.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/routes.js", fileContents, function(err) {
            if (err) {
                console.log('server/routes.js error writing file', err);
            } else {
                console.log('routes.js writing file succeeded');
            }
          });
        });

        //creating model.js in server folder
        fs.readFile('./tpl-plugin/server/model.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/model.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('server/model.js writing file succeeded');
            }
          });
        });

        //creating index.js in server folder
        fs.readFile('./tpl-plugin/server/index.js', 'utf8', function(err, fileContents) {
          if (err) throw err;
          fileContents = fileContents.replace(/%name%/gi, dirName);
          fs.writeFile(serverDir + "/index.js", fileContents, function(err) {
            if (err) {
                console.log('error writing file', err);
            } else {
                console.log('server/index.js writing file succeeded');
            }
          });
        });

      }
    });
}

function editServerFile(pluginName) {
    let pathServerFile = './admin/server/server.js';
    let requireStr = '//%%begin%%\nconst '+pluginName+'Routes = require(\'./plugins/'+pluginName+'/server\');\nrequire(\'./plugins/'+pluginName+'/server/routes\')(app);'
    fs.readFile(pathServerFile, 'utf8', function(err, fileContents) {
      if (err) throw err;
      console.log(typeof fileContents);
      fileContents = fileContents.replace(/\/\/%%begin%%/i, requireStr);
      fs.writeFile(pathServerFile, fileContents, function(err) {
        if (err) {
            console.log('error writing file', err);
        } else {
            console.log('writing file succeeded');
        }
      });
    });
  }

  function firstLetterUpperCase(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  function createPlugin(pluginName, mountPoint) {
      // creating the plugin on database
      let newPlugin = {};
      newPlugin.name = pluginName;
      newPlugin.mount_point = mountPoint;
      newPlugin.plugin_properties = [];

      console.log("...");
      console.log("... creating plugin");
      request
       .post('http://localhost:3000/api/plugin')
       .set('Accept', 'application/json')
       .send(newPlugin)
       .end(function (err, res) {
         if (err) {
          //  console.log(err.status);
           console.log('closing connection...');
        //    process.exit();
         } else {
          console.log("... OK... DONE");
         }
       });
  }<|endoftext|>


<commit_before>var paused = true,
    spiro,
    canvas,
    context,
    line_canvas,
    line_context,
    circle_canvas,
    circle_context,
    center,
    point;

function Gear(x, y, radius) {
    'use strict';
    this.x = x;
    this.y = y;
    this.radius = radius;
}

function Line(length, speed) {
    'use strict';
    this.length = length;
    this.speed = speed;
    this.rotation = 0;
}

Line.prototype.step = function() {
    'use strict';
    var x, y, rads;
    this.rotation += this.speed;
    rads = Math.PI * this.rotation / 360;
    x = this.length * Math.cos(rads);
    y = this.length * Math.sin(rads);
    return [x, y];
};

function Spirograph() {
    'use strict';
    this.lines = [];
    this.lines.push(new Line(400, 2));
    this.gears = [];
    this.gears.push(new Gear(center[0], center[1], 400));
    this.size = 0;
}

Spirograph.prototype.add_gear = function(percent, direction) {
    'use strict';
    var line_len, last_line, new_line, new_speed;
    last_line = this.lines[this.lines.length - 1];
    line_len = last_line.length * percent / 100;
    new_speed = Math.abs(last_line.speed / (percent / 100)) / 2;
    if (direction) {
        new_speed *= -1;
    }
    last_line.length *= ((100 - percent) / 100);
    new_line = new Line(line_len, new_speed);
    new_line.rotation = last_line.rotation;
    this.lines.push(new_line);
    this.gears.push(new Gear(center[0] * 2 - line_len, center[1], line_len));
    update_gearlist();
};

Spirograph.prototype.step = function() {
    'use strict';
    var len, i, line, gear, vector, delta;
    delta = [0, 0];
    delta[0] += center[0];
    delta[1] += center[1];
    for (i = 0; i < this.lines.length; i++) {
        this.gears[i].x = delta[0];
        this.gears[i].y = delta[1];
        line = this.lines[i];
        vector = line.step();
        delta[0] += vector[0];
        delta[1] += vector[1];
    }
    return delta;
};

function mainloop() {
    'use strict';
    if (paused === false) {
        draw_lines();
        draw_circles();

        // draw everything on the visible canvas
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(circle_canvas, 0, 0);
        context.drawImage(line_canvas, 0, 0);

        setTimeout(mainloop, 10);
    }
}

function draw_lines() {
        // update the line on off-screen canvas
        line_context.moveTo(point[0], point[1]);
        point = spiro.step();
        line_context.lineTo(point[0], point[1]);
        line_context.stroke();
}

function draw_circles() {
        // predraw the circles on off-screen canvas
        var i, lines, gear;
        lines = spiro.lines;
        circle_context.clearRect(0, 0, canvas.width, canvas.height);
        circle_context.beginPath();
        circle_context.arc(point[0], point[1], 3, 0, Math.PI * 2, false);
        for (i = 0; i < spiro.gears.length; i++) {
            gear = spiro.gears[i];
            circle_context.moveTo(gear.x + gear.radius, gear.y);
            circle_context.arc(gear.x, gear.y, gear.radius, 0,
                    Math.PI * 2, false);
        }
        circle_context.stroke();
}

function toggle_pause() {
    'use strict';
    var pause = document.getElementById("pause");
    if (paused === true) {
        paused = false;
        pause.innerHTML = "Pause";
        mainloop();
    } else {
        paused = true;
        pause.innerHTML = "Start";
    }
    return false;
}

function new_gear() {
    var percent = parseInt(document.getElementById('gearsize').value);
    var direction = document.getElementById('direction').checked;
    line_context.clearRect(0, 0, canvas.width, canvas.height);
    spiro.add_gear(percent, direction);
    draw_circles();
    line_context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(circle_canvas, 0, 0);
}

function del_gear() {
    var line = spiro.lines.pop();
    spiro.lines[spiro.lines.length - 1].length += line.length;
    spiro.gears.pop();
    update_gearlist();
}

function readKey(event) {
    'use strict';
    switch (event.keyCode) {
        case 32:
            toggle_pause();
            break;
    }
    // console.log(event.keyCode);
}

function update_gearlist() {
    'use strict';
    var gearlist, content, i, gears;
    gearlist = document.getElementById('list');
    gears = spiro.gears;
    content = "";
    content += 'You have ' + gears.length + ' gears.
';
    for (i = 0; i < gears.length; i++) {
        content += "Gear " + (i + 1) + ": " + gears[i].radius + '
';
    }
    gearlist.innerHTML = content;
}

function init() {
    'use strict';

    // visible "main" canvas
    canvas = document.getElementById('canv');
    context = canvas.getContext('2d');

    // own context for spirograph line since it doesn't need redrawing
    line_canvas = document.createElement('canvas');
    line_canvas.width = canvas.width;
    line_canvas.height = canvas.height;
    line_context = line_canvas.getContext('2d');
    line_context.clearRect(0, 0, canvas.width, canvas.height);
    line_context.strokeStyle = '#666666';

    // own context for spirograph "gears" since they are redrawn each frame
    circle_canvas = document.createElement('canvas');
    circle_canvas.width = canvas.width;
    circle_canvas.height = canvas.height;
    circle_context = circle_canvas.getContext('2d');
    circle_context.clearRect(0, 0, canvas.width, canvas.height);
    circle_context.strokeStyle = '#888888';

    center = [canvas.width / 2, canvas.height / 2];
    spiro = new Spirograph();
    update_gearlist();
    document.getElementById('sizeout').value = document.getElementById("gearsize").value;
    point = spiro.step();
    paused = true;
    draw_circles();
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(circle_canvas, 0, 0);
    mainloop();
}
<commit_msg>added gear direction indicator<commit_after>var paused = true,
    spiro,
    canvas,
    context,
    line_canvas,
    line_context,
    circle_canvas,
    circle_context,
    center,
    point;

function Gear(x, y, radius) {
    'use strict';
    this.x = x;
    this.y = y;
    this.radius = radius;
}

function Line(length, speed) {
    'use strict';
    this.length = length;
    this.speed = speed;
    this.rotation = 0;
}

Line.prototype.step = function() {
    'use strict';
    var x, y, rads;
    this.rotation += this.speed;
    rads = Math.PI * this.rotation / 360;
    x = this.length * Math.cos(rads);
    y = this.length * Math.sin(rads);
    return [x, y];
};

function Spirograph() {
    'use strict';
    this.lines = [];
    this.lines.push(new Line(400, 2));
    this.gears = [];
    this.gears.push(new Gear(center[0], center[1], 400));
    this.size = 0;
}

Spirograph.prototype.add_gear = function(percent, direction) {
    'use strict';
    var line_len, last_line, new_line, new_speed;
    last_line = this.lines[this.lines.length - 1];
    line_len = last_line.length * percent / 100;
    new_speed = Math.abs(last_line.speed / (percent / 100)) / 2;
    if (direction) {
        new_speed *= -1;
    }
    last_line.length *= ((100 - percent) / 100);
    new_line = new Line(line_len, new_speed);
    new_line.rotation = last_line.rotation;
    this.lines.push(new_line);
    this.gears.push(new Gear(center[0] * 2 - line_len, center[1], line_len));
    update_gearlist();
};

Spirograph.prototype.step = function() {
    'use strict';
    var len, i, line, gear, vector, delta;
    delta = [0, 0];
    delta[0] += center[0];
    delta[1] += center[1];
    for (i = 0; i < this.lines.length; i++) {
        this.gears[i].x = delta[0];
        this.gears[i].y = delta[1];
        line = this.lines[i];
        vector = line.step();
        delta[0] += vector[0];
        delta[1] += vector[1];
    }
    return delta;
};

function mainloop() {
    'use strict';
    if (paused === false) {
        draw_lines();
        draw_circles();

        // draw everything on the visible canvas
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.drawImage(circle_canvas, 0, 0);
        context.drawImage(line_canvas, 0, 0);

        setTimeout(mainloop, 10);
    }
}

function draw_lines() {
        // update the line on off-screen canvas
        line_context.moveTo(point[0], point[1]);
        point = spiro.step();
        line_context.lineTo(point[0], point[1]);
        line_context.stroke();
}

function draw_circles() {
        // predraw the circles on off-screen canvas
        var i, lines, gear;
        lines = spiro.lines;
        circle_context.clearRect(0, 0, canvas.width, canvas.height);
        circle_context.beginPath();
        circle_context.arc(point[0], point[1], 3, 0, Math.PI * 2, false);
        for (i = 0; i < spiro.gears.length; i++) {
            gear = spiro.gears[i];
            circle_context.moveTo(gear.x + gear.radius, gear.y);
            circle_context.arc(gear.x, gear.y, gear.radius, 0,
                    Math.PI * 2, false);
        }
        circle_context.stroke();
}

function toggle_pause() {
    'use strict';
    var pause = document.getElementById("pause");
    if (paused === true) {
        paused = false;
        pause.innerHTML = "Pause";
        mainloop();
    } else {
        paused = true;
        pause.innerHTML = "Start";
    }
    return false;
}

function new_gear() {
    var percent = parseInt(document.getElementById('gearsize').value);
    var direction = document.getElementById('direction').checked;
    line_context.clearRect(0, 0, canvas.width, canvas.height);
    spiro.add_gear(percent, direction);
    draw_circles();
    line_context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(circle_canvas, 0, 0);
}

function del_gear() {
    var line = spiro.lines.pop();
    spiro.lines[spiro.lines.length - 1].length += line.length;
    spiro.gears.pop();
    update_gearlist();
}

function readKey(event) {
    'use strict';
    switch (event.keyCode) {
        case 32:
            toggle_pause();
            break;
    }
    // console.log(event.keyCode);
}

function update_gearlist() {
    'use strict';
    var gearlist, content, i, gears, lines;
    gearlist = document.getElementById('list');
    gears = spiro.gears;
    lines = spiro.lines;
    content = "";
    content += 'You have ' + gears.length + ' gears.
';
    for (i = 0; i < gears.length; i++) {
        content += "Gear " + (i + 1) + ": " + gears[i].radius + " ";
        if (lines[i].speed > 0) {
            content += "->";
        } else {
            content += "<-";
        }
        content += "
";
    }
    gearlist.innerHTML = content;
}

function init() {
    'use strict';

    // visible "main" canvas
    canvas = document.getElementById('canv');
    context = canvas.getContext('2d');

    // own context for spirograph line since it doesn't need redrawing
    line_canvas = document.createElement('canvas');
    line_canvas.width = canvas.width;
    line_canvas.height = canvas.height;
    line_context = line_canvas.getContext('2d');
    line_context.clearRect(0, 0, canvas.width, canvas.height);
    line_context.strokeStyle = '#666666';

    // own context for spirograph "gears" since they are redrawn each frame
    circle_canvas = document.createElement('canvas');
    circle_canvas.width = canvas.width;
    circle_canvas.height = canvas.height;
    circle_context = circle_canvas.getContext('2d');
    circle_context.clearRect(0, 0, canvas.width, canvas.height);
    circle_context.strokeStyle = '#888888';

    center = [canvas.width / 2, canvas.height / 2];
    spiro = new Spirograph();
    update_gearlist();
    document.getElementById('sizeout').value = document.getElementById("gearsize").value;
    point = spiro.step();
    paused = true;
    draw_circles();
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(circle_canvas, 0, 0);
    mainloop();
}
<|endoftext|>


<commit_before>(function (exports, node) {

	/*
	 * GameTimer
	 *
	 * Sends DATA msgs
	 *
	 */

	exports.GameTimer = GameTimer;

	JSUS = node.JSUS;

	GameTimer.STOPPED = -2
	GameTimer.PAUSED = -1;
	GameTimer.UNITIALIZED = 0;
	GameTimer.LOADING = 1;
	GameTimer.RUNNING = 2;

	function GameTimer (options) {
		var options = options || {};
		this.options = options;

		this.timer = null; 		// the ID of the interval
		this.timeLeft = null;
		this.timePassed = 0;

		this.hooks = [];
		this.init(this.options);

		// TODO: remove into a new addon
		this.listeners();
	};

	GameTimer.prototype.init = function (options) {
		this.status = GameTimer.UNITIALIZED;
		if (this.timer) clearInterval(this.timer);
		this.milliseconds = options.milliseconds || 0;
		this.timeLeft = this.milliseconds;
		this.timePassed = 0;
		this.update = options.update || 1000;
		this.timeup = options.timeup || 'TIMEUP'; // event to be fire when timer is expired
		// TODO: update and milliseconds must be multiple now
		if (options.hooks) {
			for (var i=0; i < options.hooks.length; i++){
				this.addHook(options.hooks[i]);
			}
		}
	};

	/**
	 * Fire a registered hook. If it is a string it is emitted
	 * as an event, otherwise it called as a function.
	 */
	GameTimer.prototype.fire = function (h) {
		if (!h && !h.hook) return;
		var hook = h.hook || h;
		if (hook instanceof Function) {
			var ctx = h.ctx || node.game;
			hook.call(ctx);
		}
		else {
			node.emit(hook);
		}
	};

	GameTimer.prototype.start = function() {
		this.status = GameTimer.LOADING;
		// fire the event immediately if time is zero
		if (this.options.milliseconds === 0) {
			node.emit(this.timeup);
			return;
		}
		//console.log('Interval about to start');
		var that = this;
		this.timer = setInterval(function() {
			that.status = GameTimer.RUNNING;
			//console.log('INTERVAL CALLED' + that.timeLeft);
			that.timePassed = that.timePassed + that.update;
			that.timeLeft = that.milliseconds - that.timePassed;
			// Fire custom hooks from the latest to the first if any
			for (var i = that.hooks.length; i > 0; i--) {
				that.fire(that.hooks[(i-1)]);
			}
			// Fire Timeup Event
			if (that.timeLeft <= 0) {
				// First stop the timer and then call the timeup
				that.stop();
				that.fire(that.timeup);
				//console.log('fired timeup and stopping: ' + that.timeup);
			}

		}, this.update);
	};

	/**
	 * Add an hook to the hook list after performing conformity checks.
	 * The first parameter hook can be a string, a function, or an object
	 * containing an hook property.
	 */
	GameTimer.prototype.addHook = function (hook, ctx) {
		if (!hook) return;
		var ctx = ctx || node.game;
		if (hook.hook) {
			ctx = hook.ctx || ctx;
			var hook = hook.hook;
		}
		this.hooks.push({hook: hook, ctx: ctx});
	};

	GameTimer.prototype.pause = function() {
		if (this.status > 0) {
			this.status = GameTimer.PAUSED;
			//console.log('Clearing Interval... pause')
			clearInterval(this.timer);
		}
	};

	GameTimer.prototype.resume = function() {
		if (this.status !== GameTimer.PAUSED) return; // timer was not paused
		var options = JSUS.extend({milliseconds: this.milliseconds - this.timePassed}, this.options);
		this.restart(options);
	};

	GameTimer.prototype.stop = function() {
		if (this.status === GameTimer.UNITIALIZED) return;
		if (this.status === GameTimer.STOPPED) return;
		this.status = GameTimer.STOPPED;
		//console.log('Clearing Interval... stop')
		clearInterval(this.timer);
		this.timePassed = 0;
		this.timeLeft = null;
	};

	GameTimer.prototype.restart = function (options) {
		var options = options || this.options;
		this.init(options);
		this.start();
	};

	GameTimer.prototype.listeners = function () {
		var that = this;

//		node.on('GAME_TIMER_START', function() {
//			that.start();
//		});
//
//		node.on('GAME_TIMER_PAUSE', function() {
//			that.pause();
//		});
//
//		node.on('GAME_TIMER_RESUME', function() {
//			that.resume();
//		});
//
//		node.on('GAME_TIMER_STOP', function() {
//			that.stop();
//		});

//		node.on('DONE', function(){
//			console.log('TIMER PAUSED');
//			that.pause();
//		});

		// TODO: check what is right behavior for this
//		node.on('WAITING...', function(){
//			that.pause();
//		});

	};

})(
	'undefined' != typeof node ? node : module.exports
  , 'undefined' != typeof node ? node : module.parent.exports
);<commit_msg>fix difference between function and string in fire function<commit_after>(function (exports, node) {

	/*
	 * GameTimer
	 *
	 * Sends DATA msgs
	 *
	 */

	exports.GameTimer = GameTimer;

	JSUS = node.JSUS;

	GameTimer.STOPPED = -2
	GameTimer.PAUSED = -1;
	GameTimer.UNITIALIZED = 0;
	GameTimer.LOADING = 1;
	GameTimer.RUNNING = 2;

	function GameTimer (options) {
		var options = options || {};
		this.options = options;

		this.timer = null; 		// the ID of the interval
		this.timeLeft = null;
		this.timePassed = 0;

		this.hooks = [];
		this.init(this.options);

		// TODO: remove into a new addon
		this.listeners();
	};

	GameTimer.prototype.init = function (options) {
		this.status = GameTimer.UNITIALIZED;
		if (this.timer) clearInterval(this.timer);
		this.milliseconds = options.milliseconds || 0;
		this.timeLeft = this.milliseconds;
		this.timePassed = 0;
		this.update = options.update || 1000;
		this.timeup = options.timeup || 'TIMEUP'; // event to be fire when timer is expired
		// TODO: update and milliseconds must be multiple now
		if (options.hooks) {
			for (var i=0; i < options.hooks.length; i++){
				this.addHook(options.hooks[i]);
			}
		}
	};

	/**
	 * Fire a registered hook. If it is a string it is emitted
	 * as an event, otherwise it called as a function.
	 */
	GameTimer.prototype.fire = function (h) {
		if (!h && !h.hook) return;
		var hook = h.hook || h;
		if ('function' === typeof hook) {
			var ctx = h.ctx || node.game;
			hook.call(ctx);
		}
		else {
			node.emit(hook);
		}
	};

	GameTimer.prototype.start = function() {
		this.status = GameTimer.LOADING;
		// fire the event immediately if time is zero
		if (this.options.milliseconds === 0) {
			node.emit(this.timeup);
			return;
		}
		//console.log('Interval about to start');
		var that = this;
		this.timer = setInterval(function() {
			that.status = GameTimer.RUNNING;
			//console.log('INTERVAL CALLED' + that.timeLeft);
			that.timePassed = that.timePassed + that.update;
			that.timeLeft = that.milliseconds - that.timePassed;
			// Fire custom hooks from the latest to the first if any
			for (var i = that.hooks.length; i > 0; i--) {
				that.fire(that.hooks[(i-1)]);
			}
			// Fire Timeup Event
			if (that.timeLeft <= 0) {
				// First stop the timer and then call the timeup
				that.stop();
				that.fire(that.timeup);
				//console.log('fired timeup and stopping: ' + that.timeup);
			}

		}, this.update);
	};

	/**
	 * Add an hook to the hook list after performing conformity checks.
	 * The first parameter hook can be a string, a function, or an object
	 * containing an hook property.
	 */
	GameTimer.prototype.addHook = function (hook, ctx) {
		if (!hook) return;
		var ctx = ctx || node.game;
		if (hook.hook) {
			ctx = hook.ctx || ctx;
			var hook = hook.hook;
		}
		this.hooks.push({hook: hook, ctx: ctx});
	};

	GameTimer.prototype.pause = function() {
		if (this.status > 0) {
			this.status = GameTimer.PAUSED;
			//console.log('Clearing Interval... pause')
			clearInterval(this.timer);
		}
	};

	GameTimer.prototype.resume = function() {
		if (this.status !== GameTimer.PAUSED) return; // timer was not paused
		var options = JSUS.extend({milliseconds: this.milliseconds - this.timePassed}, this.options);
		this.restart(options);
	};

	GameTimer.prototype.stop = function() {
		if (this.status === GameTimer.UNITIALIZED) return;
		if (this.status === GameTimer.STOPPED) return;
		this.status = GameTimer.STOPPED;
		//console.log('Clearing Interval... stop')
		clearInterval(this.timer);
		this.timePassed = 0;
		this.timeLeft = null;
	};

	GameTimer.prototype.restart = function (options) {
		var options = options || this.options;
		this.init(options);
		this.start();
	};

	GameTimer.prototype.listeners = function () {
		var that = this;

//		node.on('GAME_TIMER_START', function() {
//			that.start();
//		});
//
//		node.on('GAME_TIMER_PAUSE', function() {
//			that.pause();
//		});
//
//		node.on('GAME_TIMER_RESUME', function() {
//			that.resume();
//		});
//
//		node.on('GAME_TIMER_STOP', function() {
//			that.stop();
//		});

//		node.on('DONE', function(){
//			console.log('TIMER PAUSED');
//			that.pause();
//		});

		// TODO: check what is right behavior for this
//		node.on('WAITING...', function(){
//			that.pause();
//		});

	};

})(
	'undefined' != typeof node ? node : module.exports
  , 'undefined' != typeof node ? node : module.parent.exports
);<|endoftext|>


<commit_before>import {actionCreatorsFor} from 'redux-crud';
import $ from 'jquery'
import * as displayErrorsActions from 'gModules/displayErrors/actions.js'
import {rootUrl} from 'servers/guesstimate-api/constants.js'
import {captureApiError, generalError} from 'lib/errors/index.js'
import {setupGuesstimateApi} from 'servers/guesstimate-api/constants.js'

let sActions = actionCreatorsFor('organizations');

function api(state) {
  function getToken(state) {
    return _.get(state, 'me.token')
  }
  return setupGuesstimateApi(getToken(state))
}

export function fetchById(organizationId) {
  return (dispatch, getState) => {
    api(getState()).organizations.get({organizationId}, (err, organization) => {
      if (err) {
        dispatch(displayErrorsActions.newError())
        captureApiError('OrganizationssFetch', null, null, err, {url: 'fetch'})
      } else if (organization) {
        dispatch(sActions.fetchSuccess([organization]))
      }
    })
  }
}

export function fromSearch(spaces) {
  return (dispatch) => {
    const organizations = spaces.map(s => s.organization_info)
    const formatted = organizations.map(d => _.pick(d, ['id', 'name']))
    dispatch(sActions.fetchSuccess(formatted))
  }
}
<commit_msg>Removing unnecessary import.<commit_after>import {actionCreatorsFor} from 'redux-crud'
import $ from 'jquery' // TODO(matthew): Is this needed at all?
import * as displayErrorsActions from 'gModules/displayErrors/actions.js'
import {rootUrl} from 'servers/guesstimate-api/constants.js'
import {captureApiError} from 'lib/errors/index.js'
import {setupGuesstimateApi} from 'servers/guesstimate-api/constants.js'

let sActions = actionCreatorsFor('organizations')

function api(state) {
  function getToken(state) {
    return _.get(state, 'me.token')
  }
  return setupGuesstimateApi(getToken(state))
}

export function fetchById(organizationId) {
  return (dispatch, getState) => {
    api(getState()).organizations.get({organizationId}, (err, organization) => {
      if (err) {
        dispatch(displayErrorsActions.newError())
        captureApiError('OrganizationssFetch', null, null, err, {url: 'fetch'})
      } else if (organization) {
        dispatch(sActions.fetchSuccess([organization]))
      }
    })
  }
}

export function fromSearch(spaces) {
  return (dispatch) => {
    const organizations = spaces.map(s => s.organization_info)
    const formatted = organizations.map(d => _.pick(d, ['id', 'name']))
    dispatch(sActions.fetchSuccess(formatted))
  }
}
<|endoftext|>


<commit_before>import { expect } from 'chai';
import testUtils from './utils';

describe('application launch', function () {

    beforeEach(testUtils.beforeEach);
    afterEach(testUtils.afterEach);

    it('shows hello world text on screen after launch', function () {
        return this.app.client.getText('#greet').then(function (text) {
            expect(text).to.equal('Hello World!');
        });
    });
});
<commit_msg>added spectron test<commit_after>import {expect} from 'chai';
import testUtils from './utils';

describe('application launch', function () {

    beforeEach(testUtils.beforeEach);
    afterEach(testUtils.afterEach);

    // TODO (hans-permana, 20161104: broken. Need to understand more on how mocha and chai are being used.
    // it('launches the application at the right size', function () {
    //     return this.app.client.windowHandles().then(function (response) {
    //         expect(response.value.length).to.equal(1);
    //     }).browserWindow.getBounds().should.eventually.deep.equal({
    //         x: 25,
    //         y: 35,
    //         width: 200,
    //         height: 100
    //     }).waitUntilTextExists('html', 'Hello')
    //         .getTitle().should.eventually.equal('Test')
    // });
    it('launches the application', function () {
        return this.app.client.windowHandles().then(function (response) {
            expect(response.value.length).to.equal(1);
        });
    });
    it('shows hello world text on screen after launch', function () {
        return this.app.client.getText('#title').then(function (text) {
            expect(text).to.equal('Welcome to DeDop Studio!');
        });
    });
});
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var _ = require('underscore');
var OrganizationModel = require('./organization-model');

/**
 *  User model
 *
 */

var UserModel = Backbone.Model.extend({
  url: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v1/users';
  },

  defaults: {
    avatar_url: 'http://cartodb.s3.amazonaws.com/static/public_dashboard_default_avatar.png',
    username: '',
    email: ''
  },

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');
    this._configModel = opts.configModel;

    if (!_.isEmpty(this.get('organization'))) {
      this._organizationModel = new OrganizationModel(
        this.get('organization'),
        {
          configModel: this._configModel,
          currentUserId: this.id
        }
      );
    }
  },

  canCreateDatasets: function () {
    if (!this.get('remaining_byte_quota') || this.get('remaining_byte_quota') <= 0) {
      return false;
    }
    return true;
  },

  canCreateTwitterDataset: function () {
    return !((this.get('twitter').quota - this.get('twitter').monthly_use) <= 0 && this.get('twitter').hard_limit);
  },

  canStartTrial: function () {
    return !this.isInsideOrg() && this.get('account_type') === 'FREE' && this.get('table_count') > 0;
  },

  isActionEnabled: function (action) {
    return this.get('actions') && this.get('actions')[action];
  },

  canCreatePrivateDatasets: function () {
    var actions = this.get('actions');
    return actions && actions.private_tables;
  },

  isInsideOrg: function () {
    if (this._organizationModel) {
      return !!this._organizationModel.id || this.isOrgAdmin();
    }
    return false;
  },

  isOrgAdmin: function () {
    if (this._organizationModel) {
      return this._organizationModel.getOwnerId() === this.get('id');
    }
    return false;
  },

  featureEnabled: function (name) {
    var featureFlags = this.get('feature_flags');
    if (!featureFlags || featureFlags.length === 0 || !name) {
      return false;
    }
    return _.contains(featureFlags, name);
  },

  upgradeContactEmail: function () {
    if (this.isInsideOrg()) {
      if (this.isOrgAdmin()) {
        return 'enterprise-support@cartodb.com';
      } else {
        return this._organizationModel.getOwnerEmail();
      }
    } else {
      return 'support@cartodb.com';
    }
  },

  nameOrUsername: function () {
    return this.get('name') || this.get('username');
  },

  getMaxConcurrentImports: function () {
    return (this.get('limits') && this.get('limits').concurrent_imports) || 1;
  },

  renderData: function (currentUser) {
    var name = this.get('username');
    if (currentUser && currentUser.id === this.id) {
      name = _t('user.you');
    }
    return {
      username: name,
      avatar_url: this.get('avatar_url')
    };
  },

  clone: function () {
    var attrs = _.clone(this.attributes);
    delete attrs.id;
    return new UserModel(attrs, {
      configModel: this._configModel
    });
  }
});

module.exports = UserModel;
<commit_msg>adds getschemaname to user model<commit_after>var Backbone = require('backbone');
var _ = require('underscore');
var OrganizationModel = require('./organization-model');

/**
 *  User model
 *
 */

var UserModel = Backbone.Model.extend({
  url: function () {
    var baseUrl = this._configModel.get('base_url');
    return baseUrl + '/api/v1/users';
  },

  defaults: {
    avatar_url: 'http://cartodb.s3.amazonaws.com/static/public_dashboard_default_avatar.png',
    username: '',
    email: ''
  },

  initialize: function (attrs, opts) {
    if (!opts.configModel) throw new Error('configModel is required');
    this._configModel = opts.configModel;

    if (!_.isEmpty(this.get('organization'))) {
      this._organizationModel = new OrganizationModel(
        this.get('organization'),
        {
          configModel: this._configModel,
          currentUserId: this.id
        }
      );
    }
  },

  canCreateDatasets: function () {
    if (!this.get('remaining_byte_quota') || this.get('remaining_byte_quota') <= 0) {
      return false;
    }
    return true;
  },

  canCreateTwitterDataset: function () {
    return !((this.get('twitter').quota - this.get('twitter').monthly_use) <= 0 && this.get('twitter').hard_limit);
  },

  canStartTrial: function () {
    return !this.isInsideOrg() && this.get('account_type') === 'FREE' && this.get('table_count') > 0;
  },

  isActionEnabled: function (action) {
    return this.get('actions') && this.get('actions')[action];
  },

  canCreatePrivateDatasets: function () {
    var actions = this.get('actions');
    return actions && actions.private_tables;
  },

  isInsideOrg: function () {
    if (this._organizationModel) {
      return !!this._organizationModel.id || this.isOrgAdmin();
    }
    return false;
  },

  isOrgAdmin: function () {
    if (this._organizationModel) {
      return this._organizationModel.getOwnerId() === this.get('id');
    }
    return false;
  },

  featureEnabled: function (name) {
    var featureFlags = this.get('feature_flags');
    if (!featureFlags || featureFlags.length === 0 || !name) {
      return false;
    }
    return _.contains(featureFlags, name);
  },

  upgradeContactEmail: function () {
    if (this.isInsideOrg()) {
      if (this.isOrgAdmin()) {
        return 'enterprise-support@cartodb.com';
      } else {
        return this._organizationModel.getOwnerEmail();
      }
    } else {
      return 'support@cartodb.com';
    }
  },

  nameOrUsername: function () {
    return this.get('name') || this.get('username');
  },

  getMaxConcurrentImports: function () {
    return (this.get('limits') && this.get('limits').concurrent_imports) || 1;
  },

  getSchemaName: function () {
    return this.isInsideOrg() ? this.get('username') : 'public';
  },

  renderData: function (currentUser) {
    var name = this.get('username');
    if (currentUser && currentUser.id === this.id) {
      name = _t('user.you');
    }
    return {
      username: name,
      avatar_url: this.get('avatar_url')
    };
  },

  clone: function () {
    var attrs = _.clone(this.attributes);
    delete attrs.id;
    return new UserModel(attrs, {
      configModel: this._configModel
    });
  }
});

module.exports = UserModel;
<|endoftext|>


<commit_before>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

        windows: {

            modal: {

                // functions are objects in js
                new: function (contentSource, options) {

                    var
                        ConstructorReference = $module.windows.modal.new,
                        self = this,

                        $ = esPhinx,
                        ajax = Ajax,
                        body = $("body"),

                        modal,
                        mask,
                        main,
                        container,
                        btnClose,
                        btnHide,
                        headers,
                        params,
                        asynchronousAnswer,
                        imgControl,
                        singleton,

                        maskTransitionDuration = function (mask) {
                            return parseFloat(mask
                                .css("transition-duration")) * 1000;
                        },

                        restartTransition = function (mask) {
                            mask.css("transition", "opacity 0s");
                        },

                        resolveParams = function () {
                            options = options || {};

                            if (typeof options.windowController !== "boolean") {
                                options.windowController = true;
                            }

                            if (typeof options.remote !== "boolean") {
                                options.remote = true;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                header,
                                actions;

                            if (options.windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                btnClose = $('')
                                    .addClass("btn-close");
                                btnHide = $('')
                                    .addClass("btn-hide");

                                header.append(actions);
                                actions.append(btnClose);
                                actions.append(btnHide);

                                main
                                    .prepend(header)
                                    .css({
                                        "max-height": $(document).height(),
                                        "max-width": $(document).width()
                                    });

                                bindHeaderEventListeners();
                            }
                        },

                        bindHeaderEventListeners = function () {
                            // $(document).off("keydown").on("keydown", function (e) {
                            //     if (e.keyCode === 27) {
                            //         self.hide();
                            //     }
                            // });

                            btnHide.on("click", function () {
                                self.hide();
                            });

                            btnClose.on("click", function () {
                                self.close();
                            });
                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            main.observe(function (observer) {
                                imgs = main.find("img");
                                if (imgs.any()) {
                                    imgs.each(function (img) {
                                        $(img).on("load", function (e) {
                                            // debugger
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function () {
                                            if (length === imgs.length) {
                                                return true;
                                            }

                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                }
                                                self.show();
                                            }

                                            return false;
                                        },
                                        ready: function () {
                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            length = 0;
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                self.hide(false);

                                                options.complete.call(self);
                                            }
                                        }
                                    });
                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete.call(self);
                                    }
                                }

                                // talvez tenha que remanejar o disconnect
                                observer.disconnect();
                            });
                        },

                        create = function (remote) {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            body.append(modal);

                            observeContent();

                            if (options.remote) {
                                headers = options.header || options.headers
                                || null;
                                params = options.param || options.params
                                || null;
                                ajax.new(contentSource, {
                                    params: params,
                                    headers: headers,
                                    progress: function () {
                                        if (options.loading) {
                                            // callback
                                            options.loading(main);
                                            self.show();
                                            // debugger
                                        }
                                    },
                                    success: function (a) {
                                        asynchronousAnswer = a;
                                        container.html(asynchronousAnswer);
                                        // because here the processing is asynchronous, it's not linear
                                        self.hide(false);
                                        main.html(container);
                                    }
                                });
                            } else {
                                container.html(contentSource);
                                main.html(container);
                            }

                        };

                    if (!(this instanceof ConstructorReference)) {
                        singleton = Singleton.exists(ConstructorReference, arguments);

                        if (!singleton) {
                            return ConstructorReference.instance(arguments);
                        } else {
                            singleton.show();
                        }
                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        resolveParams();
                        create();
                    }

                    // global scope (public)
                    this.close = function () {
                        main.hide();

                        restartTransition(mask);
                        if (options.fadeOut) {
                            mask.css("transition", "opacity " + options.fadeOut);
                        }
                        mask.addClass("transparent");

                        setTimeout(function () {
                            modal.remove();
                        }, maskTransitionDuration(mask));

                        self.deleteSingleton();
                    };

                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

                        if (animation) {
                            if (options.fadeOut) {
                                mask.css("transition", "opacity " + options.fadeOut);
                                setTimeout(function () {
                                    modal.css("z-index", -1);
                                }, maskTransitionDuration(mask));
                            }
                        }

                        mask.addClass("transparent");
                    };

                    this.show = function () {
                        modal.css("z-index", 0);

                        restartTransition(mask);
                        if (options.fadeIn) {
                            mask.css("transition", "opacity " + options.fadeIn);
                        }
                        mask.removeClass("transparent");

                        main.centralizeAt(document);
                        main.show();
                    };

                    return self;
                }

            }

        }

    });

}(esPhinx.ui));
<commit_msg>improves modal<commit_after>// require ../support/jquery
// require esphinx_ui
// require esphinx/support/ajax
// require esphinx/support/function
// require esphinx/support/array
// require esphinx/observer

"use strict";

var
    jQuery,
    esPhinx,
    Singleton,
    Ajax,
    Constructor;

(function ($module) {

    $module.extend({

        windows: {

            modal: {

                // functions are objects in js
                new: function (contentSource, options) {

                    var
                        self = $module.windows.modal.new,
                        instance = this,
                        args = Array.from(arguments),

                        $ = esPhinx,
                        ajax = Ajax,
                        body = $("body"),

                        modal,
                        mask,
                        main,
                        container,
                        btnClose,
                        btnHide,
                        headers,
                        params,
                        asynchronousAnswer,
                        imgControl,
                        singleton,

                        maskTransitionDuration = function (mask) {
                            return parseFloat(mask
                                .css("transition-duration")) * 1000;
                        },

                        restartTransition = function (mask) {
                            mask.css("transition", "opacity 0s");
                        },

                        resolveParams = function () {
                            options = options || {};

                            if (typeof options.windowController !== "boolean") {
                                options.windowController = true;
                            }

                            if (typeof options.remote !== "boolean") {
                                options.remote = true;
                            }
                        },

                        resolveHeaderActions = function (main, options) {
                            var
                                header,
                                actions;

                            if (options.windowController) {
                                header = $("");
                                actions = $("

").addClass("actions");
                                btnClose = $('')
                                    .addClass("btn-close");
                                btnHide = $('')
                                    .addClass("btn-hide");

                                header.append(actions);
                                actions.append(btnClose);
                                actions.append(btnHide);

                                main
                                    .prepend(header)
                                    .css({
                                        "max-height": $(document).height(),
                                        "max-width": $(document).width()
                                    });

                                bindHeaderEventListeners();
                            }
                        },

                        bindHeaderEventListeners = function () {
                            // $(document).off("keydown").on("keydown", function (e) {
                            //     if (e.keyCode === 27) {
                            //         self.hide();
                            //     }
                            // });

                            btnHide.on("click", function () {
                                instance.hide();
                            });

                            btnClose.on("click", function () {
                                instance.close();
                            });
                        },

                        observeContent = function () {
                            var
                                imgs,
                                length = 0;

                            main.observe(function (observer) {
                                imgs = main.find("img");
                                if (imgs.any()) {
                                    imgs.each(function (img) {
                                        $(img).on("load", function (e) {
                                            // debugger
                                            length += 1;
                                        });
                                    });

                                    FlowControl.new({
                                        condition: function () {
                                            if (length === imgs.length) {
                                                return true;
                                            }

                                            // when processing is synchronous
                                            if (!options.remote) {
                                                if (options.loading) {
                                                    options.loading(main);
                                                }
                                                instance.show();
                                            }

                                            return false;
                                        },
                                        ready: function () {
                                            if (!asynchronousAnswer) {
                                                container.html(contentSource);
                                                main.html(container);
                                            }

                                            length = 0;
                                            resolveHeaderActions(main, options);

                                            if (options.complete) {
                                                instance.hide(false);

                                                options.complete.call(instance);
                                            }
                                        }
                                    });
                                } else {
                                    resolveHeaderActions(main, options);

                                    if (options.complete) {
                                        options.complete.call(instance);
                                    }
                                }

                                // talvez tenha que remanejar o disconnect
                                observer.disconnect();
                            });
                        },

                        create = function (remote) {
                            modal = $("

")
                                .addClass("esphinx ui modal");
                            main = $("")
                                .addClass("basicss hidden");
                            mask = $("

")
                                .addClass("basicss fixed transparent mask");
                            container = $("

").addClass("container");

                            modal
                                .append(mask)
                                .append(main);

                            body.append(modal);

                            observeContent();

                            if (options.remote) {
                                headers = options.header || options.headers
                                || null;
                                params = options.param || options.params
                                || null;
                                ajax.new(contentSource, {
                                    params: params,
                                    headers: headers,
                                    progress: function () {
                                        if (options.loading) {
                                            // callback
                                            options.loading(main);
                                            instance.show();
                                            // debugger
                                        }
                                    },
                                    success: function (a) {
                                        asynchronousAnswer = a;
                                        container.html(asynchronousAnswer);
                                        // because here the processing is asynchronous, it's not linear
                                        instance.hide(false);
                                        main.html(container);
                                    }
                                });
                            } else {
                                container.html(contentSource);
                                main.html(container);
                            }

                        };

                    if (!(this instanceof self)) {
                        // debugger
                        if (self.instance) {
                            self.instance.show();
                        } else {
                            return self.singleton(arguments);
                        }

                        // singleton = Singleton
                        //     .exists(self, arguments);
                        // // debugger
                        // if (!singleton) {
                        //     return Singleton.new(self, arguments);
                        // } else {
                        //     singleton.show();
                        // }

                    // that "else" will should to exit for the "show" method can be used by who instanciates it
                    } else {
                        resolveParams();
                        create();
                    }

                    // global scope (public)
                    this.close = function () {
                        main.hide();

                        restartTransition(mask);
                        if (options.fadeOut) {
                            mask.css("transition", "opacity " + options.fadeOut);
                        }
                        mask.addClass("transparent");

                        setTimeout(function () {
                            modal.remove();
                        }, maskTransitionDuration(mask));

                        instance.deleteSingleton();
                    };

                    this.hide = function (animation = true) {
                        main.hide();

                        restartTransition(mask);

                        if (animation) {
                            if (options.fadeOut) {
                                mask.css("transition", "opacity " + options.fadeOut);
                                setTimeout(function () {
                                    modal.css("z-index", -1);
                                }, maskTransitionDuration(mask));
                            }
                        }

                        mask.addClass("transparent");
                    };

                    this.show = function () {
                        modal.css("z-index", 0);

                        restartTransition(mask);
                        if (options.fadeIn) {
                            mask.css("transition", "opacity " + options.fadeIn);
                        }
                        mask.removeClass("transparent");

                        main.centralizeAt(document);
                        main.show();
                    };

                    return instance;
                }

            }

        }

    });

}(esPhinx.ui));
<|endoftext|>