<commit_before>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

var path = require('path');
var fs = require('fs');
var url = require('url');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  // PROMETHEUS: Allow override via env var.
  if (process.env.REACT_SCRIPTS_ROOT != null) {
    return path.join(process.env.REACT_SCRIPTS_ROOT, relativePath);
  }
  return path.resolve(appDirectory, relativePath);
}

function resolveSrc() {
  if (fs.exists(resolveApp('src'))) {
    return resolveApp('src');
  } else {
    return resolveApp('lib');
  }
}

function resolveBuild() {
  if (process.env.REACT_SCRIPTS_BUILD != null) {
    return process.env.REACT_SCRIPTS_BUILD;
  }
  return resolveApp('build');
}

function resolveIndexJS() {
  var packageJSONFilename = resolveApp('package.json');
  if (!fs.existsSync(packageJSONFilename)) {
    return resolveApp('src/index.js');
  }
  var packageJSON = JSON.parse(fs.readFileSync(packageJSONFilename, 'utf8'));
  return resolveApp(packageJSON.main) || resolveApp('src/index.js');
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421

var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .filter(folder => !path.isAbsolute(folder))
  .map(resolveApp);

var envPublicUrl = process.env.PUBLIC_URL;

function ensureSlash(path, needsSlash) {
  var hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return path + '/';
  } else {
    return path;
  }
}

function getPublicUrl(appPackageJson) {
  return envPublicUrl || require(appPackageJson).homepage;
}

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
  var publicUrl = getPublicUrl(appPackageJson);
  var servedUrl = envPublicUrl || (
    publicUrl ? url.parse(publicUrl).pathname : '/'
  );
  return ensureSlash(servedUrl, true);
}

// config after eject: we're in ./config/
module.exports = {
  appBuild: resolveBuild(),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveIndexJS(),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveSrc(),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths,
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json'))
};

// @remove-on-eject-begin
function resolveOwn(relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  appPath: resolveApp('.'),
  appBuild: resolveBuild(),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveIndexJS(),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveSrc(),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths,
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
  // These properties only exist before ejecting:
  ownPath: resolveOwn('.'),
  ownNodeModules: resolveOwn('node_modules'), // This is empty on npm 3
};

var ownPackageJson = require('../package.json');
var reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`);
var reactScriptsLinked = fs.existsSync(reactScriptsPath) && fs.lstatSync(reactScriptsPath).isSymbolicLink();

// config before publish: we're in ./packages/react-scripts/config/
//if (!reactScriptsLinked && __dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) {
//  module.exports = {
//    appPath: resolveApp('.'),
//    appBuild: resolveOwn('../../build'),
//    appPublic: resolveOwn('template/public'),
//    appHtml: resolveOwn('template/public/index.html'),
//    appIndexJs: resolveOwn('template/src/index.js'),
//    appPackageJson: resolveOwn('package.json'),
//    appSrc: resolveOwn('template/src'),
//    yarnLockFile: resolveOwn('template/yarn.lock'),
//    testsSetup: resolveOwn('template/src/setupTests.js'),
//    appNodeModules: resolveOwn('node_modules'),
//    nodePaths: nodePaths,
//    publicUrl: getPublicUrl(resolveOwn('package.json')),
//    servedPath: getServedPath(resolveOwn('package.json')),
//    // These properties only exist before ejecting:
//    ownPath: resolveOwn('.'),
//    ownNodeModules: resolveOwn('node_modules'),
//  };
//}
// @remove-on-eject-end
<commit_msg>Fix to use existsSync() instead of exists()<commit_after>// @remove-on-eject-begin
/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */
// @remove-on-eject-end
'use strict';

var path = require('path');
var fs = require('fs');
var url = require('url');

// Make sure any symlinks in the project folder are resolved:
// https://github.com/facebookincubator/create-react-app/issues/637
var appDirectory = fs.realpathSync(process.cwd());
function resolveApp(relativePath) {
  // PROMETHEUS: Allow override via env var.
  if (process.env.REACT_SCRIPTS_ROOT != null) {
    return path.join(process.env.REACT_SCRIPTS_ROOT, relativePath);
  }
  return path.resolve(appDirectory, relativePath);
}

function resolveSrc() {
  if (fs.existsSync(resolveApp('src'))) {
    return resolveApp('src');
  } else {
    return resolveApp('lib');
  }
}

function resolveBuild() {
  if (process.env.REACT_SCRIPTS_BUILD != null) {
    return process.env.REACT_SCRIPTS_BUILD;
  }
  return resolveApp('build');
}

function resolveIndexJS() {
  var packageJSONFilename = resolveApp('package.json');
  if (!fs.existsSync(packageJSONFilename)) {
    return resolveApp('src/index.js');
  }
  var packageJSON = JSON.parse(fs.readFileSync(packageJSONFilename, 'utf8'));
  return resolveApp(packageJSON.main) || resolveApp('src/index.js');
}

// We support resolving modules according to `NODE_PATH`.
// This lets you use absolute paths in imports inside large monorepos:
// https://github.com/facebookincubator/create-react-app/issues/253.

// It works similar to `NODE_PATH` in Node itself:
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders

// We will export `nodePaths` as an array of absolute paths.
// It will then be used by Webpack configs.
// Jest doesn’t need this because it already handles `NODE_PATH` out of the box.

// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
// Otherwise, we risk importing Node.js core modules into an app instead of Webpack shims.
// https://github.com/facebookincubator/create-react-app/issues/1023#issuecomment-265344421

var nodePaths = (process.env.NODE_PATH || '')
  .split(process.platform === 'win32' ? ';' : ':')
  .filter(Boolean)
  .filter(folder => !path.isAbsolute(folder))
  .map(resolveApp);

var envPublicUrl = process.env.PUBLIC_URL;

function ensureSlash(path, needsSlash) {
  var hasSlash = path.endsWith('/');
  if (hasSlash && !needsSlash) {
    return path.substr(path, path.length - 1);
  } else if (!hasSlash && needsSlash) {
    return path + '/';
  } else {
    return path;
  }
}

function getPublicUrl(appPackageJson) {
  return envPublicUrl || require(appPackageJson).homepage;
}

// We use `PUBLIC_URL` environment variable or "homepage" field to infer
// "public path" at which the app is served.
// Webpack needs to know it to put the right <script> hrefs into HTML even in
// single-page apps that may serve index.html for nested URLs like /todos/42.
// We can't use a relative path in HTML because we don't want to load something
// like /todos/42/static/js/bundle.7289d.js. We have to know the root.
function getServedPath(appPackageJson) {
  var publicUrl = getPublicUrl(appPackageJson);
  var servedUrl = envPublicUrl || (
    publicUrl ? url.parse(publicUrl).pathname : '/'
  );
  return ensureSlash(servedUrl, true);
}

// config after eject: we're in ./config/
module.exports = {
  appBuild: resolveBuild(),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveIndexJS(),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveSrc(),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths,
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json'))
};

// @remove-on-eject-begin
function resolveOwn(relativePath) {
  return path.resolve(__dirname, '..', relativePath);
}

// config before eject: we're in ./node_modules/react-scripts/config/
module.exports = {
  appPath: resolveApp('.'),
  appBuild: resolveBuild(),
  appPublic: resolveApp('public'),
  appHtml: resolveApp('public/index.html'),
  appIndexJs: resolveIndexJS(),
  appPackageJson: resolveApp('package.json'),
  appSrc: resolveSrc(),
  yarnLockFile: resolveApp('yarn.lock'),
  testsSetup: resolveApp('src/setupTests.js'),
  appNodeModules: resolveApp('node_modules'),
  nodePaths: nodePaths,
  publicUrl: getPublicUrl(resolveApp('package.json')),
  servedPath: getServedPath(resolveApp('package.json')),
  // These properties only exist before ejecting:
  ownPath: resolveOwn('.'),
  ownNodeModules: resolveOwn('node_modules'), // This is empty on npm 3
};

var ownPackageJson = require('../package.json');
var reactScriptsPath = resolveApp(`node_modules/${ownPackageJson.name}`);
var reactScriptsLinked = fs.existsSync(reactScriptsPath) && fs.lstatSync(reactScriptsPath).isSymbolicLink();

// config before publish: we're in ./packages/react-scripts/config/
//if (!reactScriptsLinked && __dirname.indexOf(path.join('packages', 'react-scripts', 'config')) !== -1) {
//  module.exports = {
//    appPath: resolveApp('.'),
//    appBuild: resolveOwn('../../build'),
//    appPublic: resolveOwn('template/public'),
//    appHtml: resolveOwn('template/public/index.html'),
//    appIndexJs: resolveOwn('template/src/index.js'),
//    appPackageJson: resolveOwn('package.json'),
//    appSrc: resolveOwn('template/src'),
//    yarnLockFile: resolveOwn('template/yarn.lock'),
//    testsSetup: resolveOwn('template/src/setupTests.js'),
//    appNodeModules: resolveOwn('node_modules'),
//    nodePaths: nodePaths,
//    publicUrl: getPublicUrl(resolveOwn('package.json')),
//    servedPath: getServedPath(resolveOwn('package.json')),
//    // These properties only exist before ejecting:
//    ownPath: resolveOwn('.'),
//    ownNodeModules: resolveOwn('node_modules'),
//  };
//}
// @remove-on-eject-end
<|endoftext|>


<commit_before>/*global PhoneGap:false, require:false */
(function (window, navigator, console) {
    "use strict";

    /**
     * Defines log messages and add a generic handler for caching.
     */

    // See http://www.html5rocks.com/en/tutorials/cache/beginner
    var cache = window.applicationCache,
        app = window["jolira-app"] = window["jolira-app"] || {};

    app.debug =
        app.log = function () {
            console.log.apply(console, arguments);
        }

    app.error = function () {
        console.error.apply(console, arguments);
    }

    window.addEventListener("error", function(message, url, linenumber) {
        app.error(message, url, linenumber);
    });

    app.cache = app.cache || {};

    /**
     * Override this handler if you would like to handle the update differently
     */
    app.cache.updateReady = app.cache.updateReady || function () {
        if (confirm('Program updates are available. Load them now?')) {
            window.location.reload();
        }
    };

    function getCacheStatus() {
        switch (cache.status) {
            case cache.UNCACHED: // UNCACHED == 0
                return 'UNCACHED';
            case cache.IDLE: // IDLE == 1
                return 'IDLE';
            case cache.CHECKING: // CHECKING == 2
                return 'CHECKING';
            case cache.DOWNLOADING: // DOWNLOADING == 3
                return 'DOWNLOADING';
            case cache.UPDATEREADY:  // UPDATEREADY == 4
                return 'UPDATEREADY';
            case cache.OBSOLETE: // OBSOLETE == 5
                return 'OBSOLETE';
        }
        return 'UNKNOWN';
    }

    function logEvent(e) {
        var type = e.type,
            status = getCacheStatus(),
            onLine = (navigator.onLine) ? 'yes' : 'no',
            message = 'online: ' + onLine + ', event: ' + type + ', status: ' + status;

        if (type === 'error' && navigator.onLine) {
            message += '; There was an unknown error, check your Cache Manifest.';
        }

        app.log(message);
    }

    window.addEventListener('load', function (e) {
        cache.addEventListener('cached', logEvent, false);
        cache.addEventListener('checking', logEvent, false);
        cache.addEventListener('downloading', logEvent, false);
        cache.addEventListener('error', logEvent, false);
        cache.addEventListener('noupdate', logEvent, false);
        cache.addEventListener('obsolete', logEvent, false);
        cache.addEventListener('progress', logEvent, false);
        cache.addEventListener('updateready', function (e) {
            logEvent(e);

            if (cache.status === cache.UPDATEREADY) {
                cache.swapCache();

                app.log('Swapped/updated the Cache Manifest.');
                app.cache.updateReady();
            }
        }, false);
    }, false);
})(window, navigator, console);<commit_msg>automatic reload<commit_after>/*global PhoneGap:false, require:false */
(function (window, navigator, console) {
    "use strict";

    /**
     * Defines log messages and add a generic handler for caching.
     */

    // See http://www.html5rocks.com/en/tutorials/cache/beginner
    var cache = window.applicationCache,
        app = window["jolira-app"] = window["jolira-app"] || {};

    app.debug =
        app.log = function () {
            console.log.apply(console, arguments);
        }

    app.error = function () {
        console.error.apply(console, arguments);
    }

    window.addEventListener("error", function(message, url, linenumber) {
        app.error(message, url, linenumber);
    });

    app.cache = app.cache || {};

    /**
     * Override this handler if you would like to handle the update differently
     */
    app.cache.updateReady = app.cache.updateReady || function () {
//        if (confirm('Program updates are available. Load them now?')) {
            window.location.reload();
//        }
    };

    function getCacheStatus() {
        switch (cache.status) {
            case cache.UNCACHED: // UNCACHED == 0
                return 'UNCACHED';
            case cache.IDLE: // IDLE == 1
                return 'IDLE';
            case cache.CHECKING: // CHECKING == 2
                return 'CHECKING';
            case cache.DOWNLOADING: // DOWNLOADING == 3
                return 'DOWNLOADING';
            case cache.UPDATEREADY:  // UPDATEREADY == 4
                return 'UPDATEREADY';
            case cache.OBSOLETE: // OBSOLETE == 5
                return 'OBSOLETE';
        }
        return 'UNKNOWN';
    }

    function logEvent(e) {
        var type = e.type,
            status = getCacheStatus(),
            onLine = (navigator.onLine) ? 'yes' : 'no',
            message = 'online: ' + onLine + ', event: ' + type + ', status: ' + status;

        if (type === 'error' && navigator.onLine) {
            message += '; There was an unknown error, check your Cache Manifest.';
        }

        app.log(message);
    }

    window.addEventListener('load', function (e) {
        cache.addEventListener('cached', logEvent, false);
        cache.addEventListener('checking', logEvent, false);
        cache.addEventListener('downloading', logEvent, false);
        cache.addEventListener('error', logEvent, false);
        cache.addEventListener('noupdate', logEvent, false);
        cache.addEventListener('obsolete', logEvent, false);
        cache.addEventListener('progress', logEvent, false);
        cache.addEventListener('updateready', function (e) {
            logEvent(e);

            if (cache.status === cache.UPDATEREADY) {
                cache.swapCache();

                app.log('Swapped/updated the Cache Manifest.');
                app.cache.updateReady();
            }
        }, false);
    }, false);
})(window, navigator, console);<|endoftext|>


<commit_before>$(function () {
    var topicid = sg.common.param("id", 0);
    sg.topic.more(topicid, 0);

    $("#btn_join").on("click", click_join);

    function click_join () {
        if (!sg.common.is_login()) {
            if (confirm("需要登录后才能发表看法，快去登录吧")) sg.common.redirect_login();
        } else {
            var html = "";
            html += "<textarea id='reply_content' placeholder='说说你的看法吧（200字以内）' />";
            html += "<button id='btn_reply' class='btn-main'>发表</button>";
            html += "<button id='btn_cancel' class='btn-main'>取消</button>";

            $(".content").addClass("has-textarea");
            $(".footer").addClass("has-textarea");
            $(".footer").html(html);
            $('#reply_content').focus();
            $("#btn_reply").on("click", click_reply);
            $("#btn_cancel").on("click", click_cancel);
        }
    }

    function click_reply () {
        var content = $("#reply_content").val();
        if (!content || content == "") {
            alert("内容不能为空");
        } else if (content.length > 200) {
            alert("字数超出限制");
        } else {
            sg.common.post(sg.config.api + "/discuss/reply", {
                utoken: sg.common.cookie.get("utoken"),
                topicid: sg.common.param("id"),
                content: content,
            }, function () {
                alert("发表成功");
                $(".new-reply").append("
新发表：" + content + "
");
                $("#no-reply").remove();
                click_cancel();
            });
        }
    }

    function click_cancel () {
        $(".footer").html("<button id='btn_join' class='btn-orange'>参与讨论</button>");
        $(".content").removeClass("has-textarea");
        $(".footer").removeClass("has-textarea");

        $("#btn_join").on("click", click_join);
    }
});

sg.topic = {
    more: function (topicid, start) {
        sg.common.get(sg.config.api + "/discuss/topic", {
            utoken: sg.common.cookie.get("utoken"),
            id: topicid,
            start: start
        }, sg.topic.success);
    },

    success: function (data) {
        var topic = data.topic;
        if (topic != undefined) {
            $("#title").html(topic.title);
            $("#body").html(topic.content);
        }

        var replies = data.replies;
        var totalCount = replies.totalCount;
        if (totalCount > 0) {
            $("#totalCount").html(totalCount);
            var list = replies.list;
            sg.common.unbind_scrollin();

            var html = "";
            html += "
";
            for (var i = 0; i < list.length; i++) {
                html += generate_replie_html(list[i]);
                if (i < list.length - 1) html += "
";
            }
            html += "
";

            $(".topic").append(html);

            if (replies.nextIndex != undefined) sg.common.bind_scrollin(function () {
                sg.topic.more(sg.common.param("id"), replies.nextIndex);
            });
        } else {
            var html = "";
            html += "
";
            html += "
目前还没有人参与讨论，快来发表下你的观点吧~
";
            html += "
";

            $(".topic").append(html);
        }

        function generate_replie_html(reply) {
            var html = "";

            html += "
";
            html += "
";
            if (reply.avatar.length> 0) html += "";
            else html += "";
            html += "
";
            html += "
";
            html += "
";
            html += "
" + reply.nickName + "
";
            html += "
" + reply.addTime + "
";
            html += "

";
            html += "
";
            html += "
";
            if (reply.children.length > 0) html += "
" + reply.children[0] + "
";
            html += "

";
            html += "
";
            html += "
" + reply.content + "
";
            html += "
";
            if (reply.stared) html += "";
            else html += "";
            html += "" + reply.staredCount + "";
            html += "
";
            html += "
";
            html += "

";
            html += "
";

            return html;
        }

        $(".star").on("click", function () {
            if (!sg.common.is_login()) {
                if (confirm("需要登录后才能操作，快去登录吧")) sg.common.redirect_login();
            } else {
                var reply_id = $(this).attr("reply-id");
                var stared = $(this).attr("stared");
                var star_count = $(this).attr("star-count");
                var star = $(this);
                if (stared == 1) {
                    sg.common.post(sg.config.api + "/discuss/reply/unstar", {
                        utoken: sg.common.cookie.get("utoken"),
                        replyid: reply_id
                    }, function () {
                        star.attr("src", "/img/zan3x.png");
                        star.attr("stared", 0);
                        star.attr("star-count", Math.max(0, star_count - 1));
                        star.next().html(Math.max(0, star_count - 1));
                    });
                } else {
                    sg.common.post(sg.config.api + "/discuss/reply/star", {
                        utoken: sg.common.cookie.get("utoken"),
                        replyid: reply_id
                    }, function () {
                        star.attr("src", "/img/zan_active3x.png");
                        star.attr("stared", 1);
                        star.attr("star-count", Math.max(0, star_count + 1));
                        star.next().html(Math.max(0, star_count + 1));
                    });
                }
            }
        });
    }
};<commit_msg>数字显示不对的问题<commit_after>$(function () {
    var topicid = sg.common.param("id", 0);
    sg.topic.more(topicid, 0);

    $("#btn_join").on("click", click_join);

    function click_join () {
        if (!sg.common.is_login()) {
            if (confirm("需要登录后才能发表看法，快去登录吧")) sg.common.redirect_login();
        } else {
            var html = "";
            html += "<textarea id='reply_content' placeholder='说说你的看法吧（200字以内）' />";
            html += "<button id='btn_reply' class='btn-main'>发表</button>";
            html += "<button id='btn_cancel' class='btn-main'>取消</button>";

            $(".content").addClass("has-textarea");
            $(".footer").addClass("has-textarea");
            $(".footer").html(html);
            $('#reply_content').focus();
            $("#btn_reply").on("click", click_reply);
            $("#btn_cancel").on("click", click_cancel);
        }
    }

    function click_reply () {
        var content = $("#reply_content").val();
        if (!content || content == "") {
            alert("内容不能为空");
        } else if (content.length > 200) {
            alert("字数超出限制");
        } else {
            sg.common.post(sg.config.api + "/discuss/reply", {
                utoken: sg.common.cookie.get("utoken"),
                topicid: sg.common.param("id"),
                content: content,
            }, function () {
                alert("发表成功");
                $(".new-reply").append("
新发表：" + content + "
");
                $("#no-reply").remove();
                click_cancel();
            });
        }
    }

    function click_cancel () {
        $(".footer").html("<button id='btn_join' class='btn-orange'>参与讨论</button>");
        $(".content").removeClass("has-textarea");
        $(".footer").removeClass("has-textarea");

        $("#btn_join").on("click", click_join);
    }
});

sg.topic = {
    more: function (topicid, start) {
        sg.common.get(sg.config.api + "/discuss/topic", {
            utoken: sg.common.cookie.get("utoken"),
            id: topicid,
            start: start
        }, sg.topic.success);
    },

    success: function (data) {
        var topic = data.topic;
        if (topic != undefined) {
            $("#title").html(topic.title);
            $("#body").html(topic.content);
        }

        var replies = data.replies;
        var totalCount = replies.totalCount;
        if (totalCount > 0) {
            $("#totalCount").html(totalCount);
            var list = replies.list;
            sg.common.unbind_scrollin();

            var html = "";
            html += "
";
            for (var i = 0; i < list.length; i++) {
                html += generate_replie_html(list[i]);
                if (i < list.length - 1) html += "
";
            }
            html += "
";

            $(".topic").append(html);

            if (replies.nextIndex != undefined) sg.common.bind_scrollin(function () {
                sg.topic.more(sg.common.param("id"), replies.nextIndex);
            });
        } else {
            var html = "";
            html += "
";
            html += "
目前还没有人参与讨论，快来发表下你的观点吧~
";
            html += "
";

            $(".topic").append(html);
        }

        function generate_replie_html(reply) {
            var html = "";

            html += "
";
            html += "
";
            if (reply.avatar.length> 0) html += "";
            else html += "";
            html += "
";
            html += "
";
            html += "
";
            html += "
" + reply.nickName + "
";
            html += "
" + reply.addTime + "
";
            html += "

";
            html += "
";
            html += "
";
            if (reply.children.length > 0) html += "
" + reply.children[0] + "
";
            html += "

";
            html += "
";
            html += "
" + reply.content + "
";
            html += "
";
            if (reply.stared) html += "";
            else html += "";
            html += "" + reply.staredCount + "";
            html += "
";
            html += "
";
            html += "

";
            html += "
";

            return html;
        }

        $(".star").on("click", function () {
            if (!sg.common.is_login()) {
                if (confirm("需要登录后才能操作，快去登录吧")) sg.common.redirect_login();
            } else {
                var reply_id = $(this).attr("reply-id");
                var stared = $(this).attr("stared");
                var star_count = new Number($(this).attr("star-count"));
                var star = $(this);
                if (stared == 1) {
                    sg.common.post(sg.config.api + "/discuss/reply/unstar", {
                        utoken: sg.common.cookie.get("utoken"),
                        replyid: reply_id
                    }, function () {
                        star.attr("src", "/img/zan3x.png");
                        star.attr("stared", 0);
                        star.attr("star-count", Math.max(0, star_count - 1));
                        star.next().html(Math.max(0, star_count - 1));
                    });
                } else {
                    sg.common.post(sg.config.api + "/discuss/reply/star", {
                        utoken: sg.common.cookie.get("utoken"),
                        replyid: reply_id
                    }, function () {
                        star.attr("src", "/img/zan_active3x.png");
                        star.attr("stared", 1);
                        star.attr("star-count", Math.max(0, star_count + 1));
                        star.next().html(Math.max(0, star_count + 1));
                    });
                }
            }
        });
    }
};<|endoftext|>


<commit_before>/**
 * Advanced OpenReports, SugarCRM Reporting.
 * @package Advanced OpenReports for SugarCRM
 * @copyright SalesAgility Ltd http://www.salesagility.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author SalesAgility <info@salesagility.com>
 */

var condln = 0;
var condln_count = 0;
var report_fields =  new Array();
var report_module = '';

function loadConditionLine(condition){

    var prefix = 'aor_conditions_';
    var ln = 0;

    ln = insertConditionLine();

    for(var a in condition){
        var elem = document.getElementById(prefix + a + ln);
        if(elem != null){
            if(elem.nodeName != 'INPUT') {
                elem.innerHTML = condition[a];
            }else {
                elem.value = condition[a];
            }
        }
    }

    //var select_field = document.getElementById('aor_conditions_field'+ln);
    //document.getElementById('aor_conditions_field_label'+ln).innerHTML = select_field.options[select_field.selectedIndex].text;

    if (condition['value'] instanceof Array) {
        condition['value'] = JSON.stringify(condition['value'])
    }

    showConditionModuleField(ln, condition['operator'], condition['value_type'], condition['value'])

    //getView(ln,action['id']);

}

function showConditionCurrentModuleFields(ln, value){

    if (typeof value === 'undefined') { value = ''; }

    report_module = document.getElementById('report_module').value;
    var rel_field = document.getElementById('aor_conditions_module_path' + ln).value;

    if(report_module != '' && rel_field != ''){

        var callback = {
            success: function(result) {
                var fields = JSON.parse(result.responseText);

                document.getElementById('aor_conditions_field'+ln).innerHTML = '';

                var selector = document.getElementById('aor_conditions_field'+ln);
                for (var i in fields) {
                    selector.options[selector.options.length] = new Option(fields[i], i);
                }

                if(fields[value] != null ){
                    document.getElementById('aor_conditions_field'+ln).value = value;
                }

                if(value == '') showConditionModuleField(ln);

            }
        }

        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleFields&aor_module="+report_module+"&view=JSON&rel_field="+rel_field+"&aor_value="+value,callback);

    }

}

function showConditionModuleField(ln, operator_value, type_value, field_value){
    if (typeof operator_value === 'undefined') { operator_value = ''; }
    if (typeof type_value === 'undefined') { type_value = ''; }
    if (typeof field_value === 'undefined') { field_value = ''; }

    var rel_field = document.getElementById('aor_conditions_module_path'+ln).value;
    var aor_field = document.getElementById('aor_conditions_field'+ln).value;
    if(aor_field != ''){

        var callback = {
            success: function(result) {
                document.getElementById('aor_conditions_operatorInput'+ln).innerHTML = result.responseText;
                SUGAR.util.evalScript(result.responseText);
            },
            failure: function(result) {
                document.getElementById('aor_conditions_operatorInput'+ln).innerHTML = '';
            }
        }
        var callback2 = {
            success: function(result) {
                document.getElementById('aor_conditions_fieldTypeInput'+ln).innerHTML = result.responseText;
                SUGAR.util.evalScript(result.responseText);
                document.getElementById('aor_conditions_fieldTypeInput'+ln).onchange = function(){showConditionModuleFieldType(ln);};
            },
            failure: function(result) {
                document.getElementById('aor_conditions_fieldTypeInput'+ln).innerHTML = '';
            }
        }
        var callback3 = {
            success: function(result) {
                document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = result.responseText;
                SUGAR.util.evalScript(result.responseText);
                enableQS(false);
            },
            failure: function(result) {
                document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = '';
            }
        }

        var aor_operator_name = "aor_conditions_operator["+ln+"]";
        var aor_field_type_name = "aor_conditions_value_type["+ln+"]";
        var aor_field_name = "aor_conditions_value["+ln+"]";

        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleOperatorField&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_operator_name+"&aor_value="+operator_value+"&rel_field="+rel_field,callback);
        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getFieldTypeOptions&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_field_type_name+"&aor_value="+type_value+"&rel_field="+rel_field,callback2);
        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleFieldType&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_field_name+"&aor_value="+field_value+"&aor_type="+type_value+"&rel_field="+rel_field,callback3);

    } else {
        document.getElementById('aor_conditions_operatorInput'+ln).innerHTML = ''
        document.getElementById('aor_conditions_fieldTypeInput'+ln).innerHTML = '';
        document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = '';
    }
}

function showConditionModuleFieldType(ln, value){
    if (typeof value === 'undefined') { value = ''; }

    var callback = {
        success: function(result) {
            document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = result.responseText;
            SUGAR.util.evalScript(result.responseText);
            enableQS(false);
        },
        failure: function(result) {
            document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = '';
        }
    }

    var rel_field = document.getElementById('aor_conditions_module_path'+ln).value;
    var aor_field = document.getElementById('aor_conditions_field'+ln).value;
    var type_value = document.getElementById("aor_conditions_value_type["+ln+"]").value;
    var aor_field_name = "aor_conditions_value["+ln+"]";

    YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleFieldType&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_field_name+"&aor_value="+value+"&aor_type="+type_value+"&rel_field="+rel_field,callback);

}

/**
 * Insert Header
 */

function insertConditionHeader(){
    tablehead = document.createElement("thead");
    tablehead.id = "conditionLines_head";
    document.getElementById('conditionLines').appendChild(tablehead);

    var x=tablehead.insertRow(-1);
    x.id='conditionLines_head';

    var a=x.insertCell(0);
    //a.style.color="rgb(68,68,68)";

    var b=x.insertCell(1);
    b.style.color="rgb(0,0,0)";
    b.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_MODULE_PATH');

    var c=x.insertCell(2);
    c.style.color="rgb(0,0,0)";
    c.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_FIELD');

    var d=x.insertCell(3);
    d.style.color="rgb(0,0,0)";
    d.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_OPERATOR');

    var e=x.insertCell(4);
    e.style.color="rgb(0,0,0)";
    e.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_VALUE_TYPE');

    var f=x.insertCell(5);
    f.style.color="rgb(0,0,0)";
    f.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_VALUE');
}

function insertConditionLine(){

    if (document.getElementById('conditionLines_head') == null) {
        insertConditionHeader();
    } else {
        document.getElementById('conditionLines_head').style.display = '';
    }

    tablebody = document.createElement("tbody");
    tablebody.id = "aor_conditions_body" + condln;
    document.getElementById('conditionLines').appendChild(tablebody);

    var x = tablebody.insertRow(-1);
    x.id = 'product_line' + condln;

    var a = x.insertCell(0);
    if(action_sugar_grp1 == 'EditView'){
        a.innerHTML = "<button type='button' id='aor_conditions_delete_line" + condln + "' class='button' value='' tabindex='116' onclick='markConditionLineDeleted(" + condln + ")'></button>
";
        a.innerHTML += "<input type='hidden' name='aor_conditions_deleted[" + condln + "]' id='aor_conditions_deleted" + condln + "' value='0'><input type='hidden' name='aor_conditions_id[" + condln + "]' id='aor_conditions_id" + condln + "' value=''>";
    } else{
        a.innerHTML = condln +1;
    }
    a.style.width = '5%';

    var b = x.insertCell(1);
    b.style.width = '15%';
    var viewStyle = 'display:none';
    if(action_sugar_grp1 == 'EditView'){viewStyle = '';}
    b.innerHTML = "<input type='hidden' name='aor_conditions_module_path["+ condln +"][0]' id='aor_conditions_module_path" + condln + "' value=''>";
    if(action_sugar_grp1 == 'EditView'){viewStyle = 'display:none';}else{viewStyle = '';}
    b.innerHTML += "";

    var c = x.insertCell(2);
    c.style.width = '15%';
    var viewStyle = 'display:none';
    if(action_sugar_grp1 == 'EditView'){viewStyle = '';}
    c.innerHTML = "<input type='hidden' name='aor_conditions_field["+ condln +"]' id='aor_conditions_field" + condln + "' value=''>";
    if(action_sugar_grp1 == 'EditView'){viewStyle = 'display:none';}else{viewStyle = '';}
    c.innerHTML += "";

    var d = x.insertCell(3);
    d.id='aor_conditions_operatorInput'+condln;
    d.style.width = '15%';

    var e = x.insertCell(4);
    e.id='aor_conditions_fieldTypeInput'+condln;
    e.style.width = '15%';

    var f = x.insertCell(5);
    f.id='aor_conditions_fieldInput'+condln;
    f.style.width = '30%';

    condln++;
    condln_count++;

    return condln -1;
}

function markConditionLineDeleted(ln)
{
    // collapse line; update deleted value
    document.getElementById('aor_conditions_body' + ln).style.display = 'none';
    document.getElementById('aor_conditions_deleted' + ln).value = '1';
    document.getElementById('aor_conditions_delete_line' + ln).onclick = '';

    condln_count--;
    if(condln_count == 0){
        document.getElementById('conditionLines_head').style.display = "none";
    }
}

function clearConditionLines(){

    if(document.getElementById('conditionLines') != null){
        var cond_rows = document.getElementById('conditionLines').getElementsByTagName('tr');
        var cond_row_length = cond_rows.length;
        var i;
        for (i=0; i < cond_row_length; i++) {
            if(document.getElementById('aor_conditions_delete_line'+i) != null){
                document.getElementById('aor_conditions_delete_line'+i).click();
            }
        }
    }
}

function hideElem(id){
    if(document.getElementById(id)){
        document.getElementById(id).style.display = "none";
        document.getElementById(id).value = "";
    }
}

function showElem(id){
    if(document.getElementById(id)){
        document.getElementById(id).style.display = "";
    }
}

function date_field_change(field){
    if(document.getElementById(field + '[1]').value == 'now'){
        hideElem(field + '[2]');
        hideElem(field + '[3]');
    } else {
        showElem(field + '[2]');
        showElem(field + '[3]');
    }
}

function addNodeToConditions(node){
    loadConditionLine(
        {
            'label' : node.name,
            'module_path' : node.module,
            'module_path_display' : node.module,
            'field' : node.id,
            'field_label' : node.name});
}<commit_msg>Make the conditions module display match the fields<commit_after>/**
 * Advanced OpenReports, SugarCRM Reporting.
 * @package Advanced OpenReports for SugarCRM
 * @copyright SalesAgility Ltd http://www.salesagility.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with this program; if not, see http://www.gnu.org/licenses
 * or write to the Free Software Foundation,Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301  USA
 *
 * @author SalesAgility <info@salesagility.com>
 */

var condln = 0;
var condln_count = 0;
var report_fields =  new Array();
var report_module = '';

function loadConditionLine(condition){

    var prefix = 'aor_conditions_';
    var ln = 0;

    ln = insertConditionLine();

    for(var a in condition){
        var elem = document.getElementById(prefix + a + ln);
        if(elem != null){
            if(elem.nodeName != 'INPUT') {
                elem.innerHTML = condition[a];
            }else {
                elem.value = condition[a];
            }
        }
    }

    //var select_field = document.getElementById('aor_conditions_field'+ln);
    //document.getElementById('aor_conditions_field_label'+ln).innerHTML = select_field.options[select_field.selectedIndex].text;

    if (condition['value'] instanceof Array) {
        condition['value'] = JSON.stringify(condition['value'])
    }

    showConditionModuleField(ln, condition['operator'], condition['value_type'], condition['value'])

    //getView(ln,action['id']);

}

function showConditionCurrentModuleFields(ln, value){

    if (typeof value === 'undefined') { value = ''; }

    report_module = document.getElementById('report_module').value;
    var rel_field = document.getElementById('aor_conditions_module_path' + ln).value;

    if(report_module != '' && rel_field != ''){

        var callback = {
            success: function(result) {
                var fields = JSON.parse(result.responseText);

                document.getElementById('aor_conditions_field'+ln).innerHTML = '';

                var selector = document.getElementById('aor_conditions_field'+ln);
                for (var i in fields) {
                    selector.options[selector.options.length] = new Option(fields[i], i);
                }

                if(fields[value] != null ){
                    document.getElementById('aor_conditions_field'+ln).value = value;
                }

                if(value == '') showConditionModuleField(ln);

            }
        }

        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleFields&aor_module="+report_module+"&view=JSON&rel_field="+rel_field+"&aor_value="+value,callback);

    }

}

function showConditionModuleField(ln, operator_value, type_value, field_value){
    if (typeof operator_value === 'undefined') { operator_value = ''; }
    if (typeof type_value === 'undefined') { type_value = ''; }
    if (typeof field_value === 'undefined') { field_value = ''; }

    var rel_field = document.getElementById('aor_conditions_module_path'+ln).value;
    var aor_field = document.getElementById('aor_conditions_field'+ln).value;
    if(aor_field != ''){

        var callback = {
            success: function(result) {
                document.getElementById('aor_conditions_operatorInput'+ln).innerHTML = result.responseText;
                SUGAR.util.evalScript(result.responseText);
            },
            failure: function(result) {
                document.getElementById('aor_conditions_operatorInput'+ln).innerHTML = '';
            }
        }
        var callback2 = {
            success: function(result) {
                document.getElementById('aor_conditions_fieldTypeInput'+ln).innerHTML = result.responseText;
                SUGAR.util.evalScript(result.responseText);
                document.getElementById('aor_conditions_fieldTypeInput'+ln).onchange = function(){showConditionModuleFieldType(ln);};
            },
            failure: function(result) {
                document.getElementById('aor_conditions_fieldTypeInput'+ln).innerHTML = '';
            }
        }
        var callback3 = {
            success: function(result) {
                document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = result.responseText;
                SUGAR.util.evalScript(result.responseText);
                enableQS(false);
            },
            failure: function(result) {
                document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = '';
            }
        }

        var aor_operator_name = "aor_conditions_operator["+ln+"]";
        var aor_field_type_name = "aor_conditions_value_type["+ln+"]";
        var aor_field_name = "aor_conditions_value["+ln+"]";

        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleOperatorField&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_operator_name+"&aor_value="+operator_value+"&rel_field="+rel_field,callback);
        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getFieldTypeOptions&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_field_type_name+"&aor_value="+type_value+"&rel_field="+rel_field,callback2);
        YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleFieldType&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_field_name+"&aor_value="+field_value+"&aor_type="+type_value+"&rel_field="+rel_field,callback3);

    } else {
        document.getElementById('aor_conditions_operatorInput'+ln).innerHTML = ''
        document.getElementById('aor_conditions_fieldTypeInput'+ln).innerHTML = '';
        document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = '';
    }
}

function showConditionModuleFieldType(ln, value){
    if (typeof value === 'undefined') { value = ''; }

    var callback = {
        success: function(result) {
            document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = result.responseText;
            SUGAR.util.evalScript(result.responseText);
            enableQS(false);
        },
        failure: function(result) {
            document.getElementById('aor_conditions_fieldInput'+ln).innerHTML = '';
        }
    }

    var rel_field = document.getElementById('aor_conditions_module_path'+ln).value;
    var aor_field = document.getElementById('aor_conditions_field'+ln).value;
    var type_value = document.getElementById("aor_conditions_value_type["+ln+"]").value;
    var aor_field_name = "aor_conditions_value["+ln+"]";

    YAHOO.util.Connect.asyncRequest ("GET", "index.php?module=AOR_Reports&action=getModuleFieldType&view="+action_sugar_grp1+"&aor_module="+report_module+"&aor_fieldname="+aor_field+"&aor_newfieldname="+aor_field_name+"&aor_value="+value+"&aor_type="+type_value+"&rel_field="+rel_field,callback);

}

/**
 * Insert Header
 */

function insertConditionHeader(){
    tablehead = document.createElement("thead");
    tablehead.id = "conditionLines_head";
    document.getElementById('conditionLines').appendChild(tablehead);

    var x=tablehead.insertRow(-1);
    x.id='conditionLines_head';

    var a=x.insertCell(0);
    //a.style.color="rgb(68,68,68)";

    var b=x.insertCell(1);
    b.style.color="rgb(0,0,0)";
    b.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_MODULE_PATH');

    var c=x.insertCell(2);
    c.style.color="rgb(0,0,0)";
    c.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_FIELD');

    var d=x.insertCell(3);
    d.style.color="rgb(0,0,0)";
    d.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_OPERATOR');

    var e=x.insertCell(4);
    e.style.color="rgb(0,0,0)";
    e.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_VALUE_TYPE');

    var f=x.insertCell(5);
    f.style.color="rgb(0,0,0)";
    f.innerHTML=SUGAR.language.get('AOR_Conditions', 'LBL_VALUE');
}

function insertConditionLine(){

    if (document.getElementById('conditionLines_head') == null) {
        insertConditionHeader();
    } else {
        document.getElementById('conditionLines_head').style.display = '';
    }

    tablebody = document.createElement("tbody");
    tablebody.id = "aor_conditions_body" + condln;
    document.getElementById('conditionLines').appendChild(tablebody);

    var x = tablebody.insertRow(-1);
    x.id = 'product_line' + condln;

    var a = x.insertCell(0);
    if(action_sugar_grp1 == 'EditView'){
        a.innerHTML = "<button type='button' id='aor_conditions_delete_line" + condln + "' class='button' value='' tabindex='116' onclick='markConditionLineDeleted(" + condln + ")'></button>
";
        a.innerHTML += "<input type='hidden' name='aor_conditions_deleted[" + condln + "]' id='aor_conditions_deleted" + condln + "' value='0'><input type='hidden' name='aor_conditions_id[" + condln + "]' id='aor_conditions_id" + condln + "' value=''>";
    } else{
        a.innerHTML = condln +1;
    }
    a.style.width = '5%';

    var b = x.insertCell(1);
    b.style.width = '15%';
    var viewStyle = 'display:none';
    if(action_sugar_grp1 == 'EditView'){viewStyle = '';}
    b.innerHTML = "<input type='hidden' name='aor_conditions_module_path["+ condln +"][0]' id='aor_conditions_module_path" + condln + "' value=''>";
    if(action_sugar_grp1 == 'EditView'){viewStyle = 'display:none';}else{viewStyle = '';}
    b.innerHTML += "";

    var c = x.insertCell(2);
    c.style.width = '15%';
    var viewStyle = 'display:none';
    if(action_sugar_grp1 == 'EditView'){viewStyle = '';}
    c.innerHTML = "<input type='hidden' name='aor_conditions_field["+ condln +"]' id='aor_conditions_field" + condln + "' value=''>";
    if(action_sugar_grp1 == 'EditView'){viewStyle = 'display:none';}else{viewStyle = '';}
    c.innerHTML += "";

    var d = x.insertCell(3);
    d.id='aor_conditions_operatorInput'+condln;
    d.style.width = '15%';

    var e = x.insertCell(4);
    e.id='aor_conditions_fieldTypeInput'+condln;
    e.style.width = '15%';

    var f = x.insertCell(5);
    f.id='aor_conditions_fieldInput'+condln;
    f.style.width = '30%';

    condln++;
    condln_count++;

    return condln -1;
}

function markConditionLineDeleted(ln)
{
    // collapse line; update deleted value
    document.getElementById('aor_conditions_body' + ln).style.display = 'none';
    document.getElementById('aor_conditions_deleted' + ln).value = '1';
    document.getElementById('aor_conditions_delete_line' + ln).onclick = '';

    condln_count--;
    if(condln_count == 0){
        document.getElementById('conditionLines_head').style.display = "none";
    }
}

function clearConditionLines(){

    if(document.getElementById('conditionLines') != null){
        var cond_rows = document.getElementById('conditionLines').getElementsByTagName('tr');
        var cond_row_length = cond_rows.length;
        var i;
        for (i=0; i < cond_row_length; i++) {
            if(document.getElementById('aor_conditions_delete_line'+i) != null){
                document.getElementById('aor_conditions_delete_line'+i).click();
            }
        }
    }
}

function hideElem(id){
    if(document.getElementById(id)){
        document.getElementById(id).style.display = "none";
        document.getElementById(id).value = "";
    }
}

function showElem(id){
    if(document.getElementById(id)){
        document.getElementById(id).style.display = "";
    }
}

function date_field_change(field){
    if(document.getElementById(field + '[1]').value == 'now'){
        hideElem(field + '[2]');
        hideElem(field + '[3]');
    } else {
        showElem(field + '[2]');
        showElem(field + '[3]');
    }
}

function addNodeToConditions(node){
    loadConditionLine(
        {
            'label' : node.name,
            'module_path' : node.module,
            'module_path_display' : node.module_path_display,
            'field' : node.id,
            'field_label' : node.name});
}<|endoftext|>


<commit_before>// Initializes jQuery plugins
$(function() {
    // Initialize sidebar
    $('#sidebar-menu').bandoneon();

    // ScrollTo
    $('#sidebar .sub-menu > a').click(function () {
        var o = ($(this).offset());
        diff = 250 - o.top;
        if (diff > 0) {
            $('#sidebar').scrollTo('-=' + Math.abs(diff), 500);
        } else {
            $('#sidebar').scrollTo('+=' + Math.abs(diff), 500);
        }
    });

    // Sidebar toggle on resize
    $(window).on('load resize', function () {
        var wSize = $(window).width();
        if (wSize <= 768) {
            $('#container').addClass('sidebar-close');
            $('#sidebar > ul').hide();
        } else if (wSize > 768) {
            $('#container').removeClass('sidebar-close');
            $('#sidebar > ul').show();
        }
    });

    // Toggle navigation icon
    var sidevarVisible = $(window).width() <= 768 ? false : !!$('#sidebar > ul').is(':visible');

    if (!sidevarVisible) {
        $('#sidebar-toggle').addClass('closed');
    }

    $('.fa-bars').click(function () {
        if (sidevarVisible) {
            $('#main-content').css('margin-left', '0px');
            $('#sidebar').css('margin-left', '-210px');
            $('#sidebar > ul').hide();
            $('#container').addClass('sidebar-closed');
            $('#sidebar-toggle').addClass('closed');
            sidevarVisible = false;
        } else {
            $('#main-content').css('margin-left', '210px');
            $('#sidebar > ul').show();
            $('#sidebar').css('margin-left', '0');
            $('#container').removeClass('sidebar-closed');
            $('#sidebar-toggle').removeClass('closed');
            sidevarVisible = true;
        }
    });

    // Menu slides
    $('.panel .tools .fa-chevron-down').click(function () {
        var el = $(this).parents('.panel').children('.panel-body');
        if ($(this).hasClass('fa-chevron-down')) {
            $(this).removeClass('fa-chevron-down').addClass('fa-chevron-up');
            el.slideUp(150);
        } else {
            $(this).removeClass('fa-chevron-up').addClass('fa-chevron-down');
            el.slideDown(150);
        }
    });

    $('.panel .tools .fa-times').click(function () {
        $(this).parents(".panel").parent().remove();
    });

    // Tooltips
    $('.tooltips').tooltip();

    // Popovers
    $('.popovers').popover();
});
<commit_msg>scrollTo en go-top<commit_after>// Initializes jQuery plugins
$(function() {
    // Initialize sidebar
    $('#sidebar-menu').bandoneon();

    // ScrollTo
    $('#sidebar .sub-menu > a').click(function () {
        var o = ($(this).offset());
        diff = 250 - o.top;
        if (diff > 0) {
            $('#sidebar').scrollTo('-=' + Math.abs(diff), 500);
        } else {
            $('#sidebar').scrollTo('+=' + Math.abs(diff), 500);
        }
    });

    // Sidebar toggle on resize
    $(window).on('load resize', function () {
        var wSize = $(window).width();
        if (wSize <= 768) {
            $('#container').addClass('sidebar-close');
            $('#sidebar > ul').hide();
        } else if (wSize > 768) {
            $('#container').removeClass('sidebar-close');
            $('#sidebar > ul').show();
        }
    });

    // Toggle navigation icon
    var sidevarVisible = $(window).width() <= 768 ? false : !!$('#sidebar > ul').is(':visible');

    if (!sidevarVisible) {
        $('#sidebar-toggle').addClass('closed');
    }

    $('#sidebar-toggle').click(function () {
        if (sidevarVisible) {
            $('#main-content').css('margin-left', '0px');
            $('#sidebar').css('margin-left', '-210px');
            $('#sidebar > ul').hide();
            $('#container').addClass('sidebar-closed');
            $('#sidebar-toggle').addClass('closed');
            sidevarVisible = false;
        } else {
            $('#main-content').css('margin-left', '210px');
            $('#sidebar > ul').show();
            $('#sidebar').css('margin-left', '0');
            $('#container').removeClass('sidebar-closed');
            $('#sidebar-toggle').removeClass('closed');
            sidevarVisible = true;
        }
    });

    // Go-Top button
    $('footer .go-top').click(function (e) {
        e.preventDefault();
        $(window).scrollTo(0);
    });

    // Tooltips
    $('.tooltips').tooltip();

    // Popovers
    $('.popovers').popover();
});
<|endoftext|>


<commit_before>export { ArrayInterleaver };

/**
 *
 */
class ArrayInterleaver {

//!!! ...unfinished... (2022/07/08)
// Needs another kinds channel shuffling: along input channel (not along output channel)

// !!! ...unfinished... (2022/07/08) along output channel (axis X)
//     { // Shuffle filters.
//       let filtersWeightsCount = this.inputChannelCount * this.outputChannelCount;
//
//       for ( let indexBegin = 0; indexBegin < filtersWeightsCount; indexBegin += this.outputChannelCount ) {
//         FloatValue.ArrayInterleaver.interleave_asGrouptTwo(
//           this.filtersArray, indexBegin, this.outputChannelCount, arrayTemp_forInterleave_asGrouptTwo );
//       }
//     }

  /**
   * Rearrange array elements by interleaving.
   *   - Only ( groupCount == 2 ) is supported.
   *
   * @param {Array} arrayIn
   *   The array to be re-arranged.
   *
   * @param {number} indexBegin
   *   Re-arrange the arrayIn from which element.
   *
   * @param {number} elementCount
   *   How many elements (begin at indexBegin) will be interleaved. It must be even (i.e. divisible by 2).
   *
   * @param {Array} arrayTemp
   *   A temporary array for placing the original elements (from arrayIn) temporarily. Providing this array could reduce memory
   * re-allocation and improve performance.
   *
   * @return {Array}
   *   Retrun the (modified) arrayIn itself.
   */
  static interleave_asGrouptTwo( arrayIn, indexBegin, elementCount, arrayTemp = [] ) {

    if ( ( elementCount % 2 ) != 0 )
      throw Error( `ArrayInterleaver.interleave_byGrouptTwo(): `
        + `elementCount ( ${elementCount} ) must be even (i.e. divisible by 2).`
      );

    // Copy the elements to be re-arrange.
    arrayTemp.length = elementCount;
    for ( let i = 0; i < elementCount; ++i ) {
      arrayTemp[ i ] = arrayIn[ indexBegin + i ];
    }

    // Interleave the elements order.
    let elementCountHalf = Math.floor( elementCount / 2 );
    for ( let i = 0, toIndex = indexBegin; i < elementCountHalf; ++i, toIndex += 2 ) {
      arrayIn[ toIndex     ] = arrayTemp[ i ];
      arrayIn[ toIndex + 1 ] = arrayTemp[ i + elementCountHalf ];
    }

    return arrayIn;
  }

}
<commit_msg>Update ArrayInterleaver.js<commit_after>export { ArrayInterleaver };

/**
 *
 */
class ArrayInterleaver {

//!!! ...unfinished... (2022/07/08)
// Needs another kinds channel shuffling: along input channel (not along output channel)

  /**
   * Rearrange array elements along width by interleaving.
   *   - Only ( groupCount == 2 ) is supported.
   *
   * @param {Array} arrayIn
   *   The array to be re-arranged. It is an 1D array but represents a 2D array.
   *
   * @param {number} height
   *   The virtual 2D array's height.
   *
   * @param {number} width
   *   The virtual 2D array's width.
   *
   * @param {Array} arrayTemp
   *   A temporary array for placing the original elements (from arrayIn) temporarily. Providing this array could reduce memory
   * re-allocation and improve performance.
   *
   * @return {Array}
   *   Retrun the (modified) arrayIn itself.
   */
  static interleave_asGrouptTwo_alongWidth( arrayIn, height, width, arrayTemp = [] ) {

    let elementCount = height * width;

    if ( elementCount != arrayIn.length )
      throw Error( `ArrayInterleaver.interleave_asGrouptTwo_alongWidth(): `
        + `( height * width ) = ( ${height} * ${width} ) = ${elementCount} `
        + ` should be the same as input array length ( ${arrayIn.length} ).`
      );

    if ( ( width % 2 ) != 0 )
      throw Error( `ArrayInterleaver.interleave_asGrouptTwo_alongWidth(): `
        + `width ( ${width} ) must be even (i.e. divisible by 2).`
      );

    arrayTemp.length = width;
    let widthHalf = Math.floor( width / 2 );

    for ( let indexBegin = 0; indexBegin < elementCount; indexBegin += width ) {

      // Copy the elements to be re-arrange.
      for ( let i = 0; i < width; ++i ) {
        arrayTemp[ i ] = arrayIn[ indexBegin + i ];
      }

      // Interleave the elements order.
      for ( let i = 0, toIndex = indexBegin; i < widthHalf; ++i, toIndex += 2 ) {
        arrayIn[ toIndex     ] = arrayTemp[ i ];
        arrayIn[ toIndex + 1 ] = arrayTemp[ i + widthHalf ];
      }
    }

    return arrayIn;
  }

  /**
   * Rearrange array elements by interleaving.
   *   - Only ( groupCount == 2 ) is supported.
   *
   * @param {Array} arrayIn
   *   The array to be re-arranged.
   *
   * @param {number} indexBegin
   *   Re-arrange the arrayIn from which element.
   *
   * @param {number} elementCount
   *   How many elements (begin at indexBegin) will be interleaved. It must be even (i.e. divisible by 2).
   *
   * @param {Array} arrayTemp
   *   A temporary array for placing the original elements (from arrayIn) temporarily. Providing this array could reduce memory
   * re-allocation and improve performance.
   *
   * @return {Array}
   *   Retrun the (modified) arrayIn itself.
   */
  static interleave_asGrouptTwo( arrayIn, indexBegin, elementCount, arrayTemp = [] ) {

    if ( ( elementCount % 2 ) != 0 )
      throw Error( `ArrayInterleaver.interleave_byGrouptTwo(): `
        + `elementCount ( ${elementCount} ) must be even (i.e. divisible by 2).`
      );

    // Copy the elements to be re-arrange.
    arrayTemp.length = elementCount;
    for ( let i = 0; i < elementCount; ++i ) {
      arrayTemp[ i ] = arrayIn[ indexBegin + i ];
    }

    // Interleave the elements order.
    let elementCountHalf = Math.floor( elementCount / 2 );
    for ( let i = 0, toIndex = indexBegin; i < elementCountHalf; ++i, toIndex += 2 ) {
      arrayIn[ toIndex     ] = arrayTemp[ i ];
      arrayIn[ toIndex + 1 ] = arrayTemp[ i + elementCountHalf ];
    }

    return arrayIn;
  }

}
<|endoftext|>


<commit_before>//
//

function collect_headers(table) {
    headers = {}
    $(table).children("li").each(function (index){
        var inputs = $(this).find("input");
        var header = $.trim(inputs[0].value);
        var value = inputs[1].type == "file" ? inputs[1].files[0] : inputs[1].value;
        if (header && value) {
            headers[header] = value;
        }
    });
    return headers;
}

function reload_history() {
    // Clean history
    $('#HistoryList > li:not(.template-item)').remove();
    // Re-populate history.
    var history = restman.storage.getAll('requests', function(item) {
        var clone = $('#HistoryList .template-item').clone(true);
        // Set id
        var a = clone.children('a');
        a.attr('data-history-item', item.timestamp);
        a.children('.history-method').text(item.method);
        a.children('.history-url').text(item.url);
        clone.removeClass('template-item');
        $('#HistoryList').append(clone);
    });
}

var onProgressHandler = function(event) {
    if(event.lengthComputable) {
        var howmuch = (event.loaded / event.total) * 100;
                document.querySelector('#progress').value = Math.ceil(howmuch);
    } else {
        console.log("Can't determine the size of the file.");
    }
}

var editors = {}
editors["#ResponseContent"] = CodeMirror.fromTextArea(document.getElementById("ResponseContent"), {
      lineNumbers: true,
      matchBrackets: true,
      readOnly: true
    });

editors["#RequestContent"] = CodeMirror.fromTextArea(document.getElementById("RequestContent"), {
      lineNumbers: true,
      matchBrackets: true
    });

$("#Send").click(function(event) {
    request = new Request();

    $(".shouldwait").addClass('loading');

    var method = $("#Method").val();
    var url = $("#Url").val();
    var headers = collect_headers("#HeadersTable");
    var ctype = $("#ContentType").val();
    var body = {};
    var data = null;

    if (method !== "GET") {
        if (ctype == "raw") {
            body.type = "raw";
            body.content = editors["#RequestContent"].getValue().replace(/\n/g, "\r\n") + "\r\n";
            data = body.content;
        }
        if (ctype == "form") {
            data = new FormData();
            body.type = "form";
            body.content = collect_headers("#FormData");
            for (var i in body.content) {
                data.append(i, body.content[i]);
            }
        }
    }

    // Save request for loading later.
    restman.storage.saveRequest(method, url, headers, body, function (evt){});

    request.send(
        url,
        method,
        function(data, textStatus, jqXHR, duration) {
            $('#ResponseStatus').text(jqXHR.status + " " + jqXHR.statusText).addClass("code" + jqXHR.status);

            content_type = jqXHR.getResponseHeader("Content-type");
            content_simple_type = "htmlmixed"; // By default, assume XML, HTML
            if (content_type != null) {
                if (content_type.indexOf("application/json") >= 0) {
                    data = js_beautify(data);
                } else {
                    if (content_type.indexOf("text/html") >= 0) {
                    data = html_beautify(data);
                    }
                }
            }

            // Calculate length of response
            content_length = jqXHR.getResponseHeader("Content-Length");
            if (content_length == null) {
                content_length = data.length
            }

            $('#ResponseType').text(content_type);
            $('#ResponseSize').text(content_length + " bytes");

            $('#ResponseTime').text(parseFloat(duration).toFixed(2) + " ms");

            output = data;
            editors["#ResponseContent"].setValue(output);
            $(".shouldwait").removeClass('loading');
        },
        headers,
        data,
        onProgressHandler
    );
})

$("a.switch-xml").click(function(event) {
    /* Act on the event */
    var textarea = $(this).attr("href");
    editor = editors[textarea];
    editor.setOption("mode", "htmlmixed");

    $(this).parent().parent().children(".active").removeClass('active');
    $(this).parent().addClass('active');
});

$("a.switch-json").click(function(event) {
    /* Act on the event */
    var textarea = $(this).attr("href");
    editor = editors[textarea];
    editor.setOption("mode", "javascript");

    $(this).parent().parent().children(".active").removeClass('active');
    $(this).parent().addClass('active');
});

$("a.switch-plain").click(function(event) {
    /* Act on the event */
    var textarea = $(this).attr("href");
    editor = editors[textarea];
    editor.setOption("mode", "text");

    $(this).parent().parent().children(".active").removeClass('active');
    $(this).parent().addClass('active');
});

/*
 * HEADERS TABLE
 */
$("a.delete-parent").click(function(event) {
    /* Act on the event */
    var row = $(this).parent();
    row.remove();
    // Avoid going to href
    return false;
});

$("a.template-item-cloner").click(function(event) {
    // Get the id for the container
    var anchor = $(this)[0];
    var target = anchor.href.replace(anchor.baseURI, "");
    var parent = $(target);

    // Get the template child to clone
    var original = parent.children(".template-item");

    // Clone and clean
    if (original) {
        // Clone template (with data and events!)
        var cloned = original.clone(true);
        // Remove id for the clones
        cloned.each(function(index, elem) { elem.id = ""; });
        cloned.removeClass("template-item");

        // Add the new born to the container
        parent.append(cloned);
    }
    // Avoid going to href
    return false;
});

/*
 * FILE DROP ON TEXT INPUTS (Only for the FormData form)
 *
 * Turn a normal `input[type="text"]` component into a drop-zone for files. When
 * a file is dropped over the input element, it will be converted to a
 * `type="file" element`. This will allow an user to drop a file over the
 * 'value' input element to add a file to the form data.
 *
 */
$('#FormData input[type="text"]').on("dragover drop", function(e) {
    return e.preventDefault();
}).on("drop", function(e) {
    // Change type of this input to file
    target = $(e.target);
    target.attr("type", "file");
    target.prop("files", e.originalEvent.dataTransfer.files);
    return $();
});

/*
 * EXPANDABLES
 */
$("section.expandable .expander").click(function(event) {
    /* Act on the event */
    var section = $(this).parent();

    if (section.hasClass("closed")) {
        section.removeClass("closed");
    } else {
        section.addClass("closed");
    }
    // Avoid going to href when coming from a link
    return false;
});

/*
 * TAB SELECT
 *
 * Turn a normal select into a tab switcher. This works by invoking the
 * "toggle_active_tab" when the select changes. The code needed is like
 * the following:
 *
 *     <select data-tab data-tab-select>
 *         <option value="value1" data-tab-panel="#panel1">Raw</option>
 *         <option value="value2" data-tab-panel="#panel2">Form data</option>
 *     </select>
 *

 *

 *
Title Panel1

 *

 *

 *
Title Panel2

 *

 *

 */
$("[data-tab-select]").change(function (event) {
    self = $(event.target);
    panel = self.children("option:selected").attr('data-tab-panel');

    self.children = function (until, selector) {
        return $('Hi');
    };
    Foundation.libs.tab.toggle_active_tab(self);
});

$(document).ready(function(event) {
    /*
     * LOAD HISTORY ITEM
     *
     * Cargar
     *
     */
    $("[data-history-item]").click(function (event) {
        // Load history item.
        restman.storage.getRequest(parseInt($(this).attr('data-history-item')), function (item){
            $("#Method").val(item.method);
            $("#Url").val(item.url);
            // TODO
        });
        return false;
    });

    reload_history();
});<commit_msg>Adding load of the headers and body from the history.<commit_after>//
//

function collect_headers(table) {
    headers = {}
    $(table).children("li").each(function (index){
        var inputs = $(this).find("input");
        var header = $.trim(inputs[0].value);
        var value = inputs[1].type == "file" ? inputs[1].files[0] : inputs[1].value;
        if (header && value) {
            headers[header] = value;
        }
    });
    return headers;
}

function reload_history() {
    // Clean history
    $('#HistoryList > li:not(.template-item)').remove();
    // Re-populate history.
    var history = restman.storage.getAll('requests', function(item) {
        var clone = $('#HistoryList .template-item').clone(true);
        // Set id
        var a = clone.children('a');
        a.attr('data-history-item', item.timestamp);
        a.children('.history-method').text(item.method);
        a.children('.history-url').text(item.url);
        clone.removeClass('template-item');
        $('#HistoryList').append(clone);
    });
}

var onProgressHandler = function(event) {
    if(event.lengthComputable) {
        var howmuch = (event.loaded / event.total) * 100;
                document.querySelector('#progress').value = Math.ceil(howmuch);
    } else {
        console.log("Can't determine the size of the file.");
    }
}

var editors = {}
editors["#ResponseContent"] = CodeMirror.fromTextArea(document.getElementById("ResponseContent"), {
      lineNumbers: true,
      matchBrackets: true,
      readOnly: true
    });

editors["#RequestContent"] = CodeMirror.fromTextArea(document.getElementById("RequestContent"), {
      lineNumbers: true,
      matchBrackets: true
    });

$("#Send").click(function(event) {
    request = new Request();

    $(".shouldwait").addClass('loading');

    var method = $("#Method").val();
    var url = $("#Url").val();
    var headers = collect_headers("#HeadersTable");
    var ctype = $("#ContentType").val();
    var body = {};
    var data = null;

    if (method !== "GET") {
        if (ctype == "raw") {
            body.type = "raw";
            body.content = editors["#RequestContent"].getValue().replace(/\n/g, "\r\n") + "\r\n";
            data = body.content;
        }
        if (ctype == "form") {
            data = new FormData();
            body.type = "form";
            body.content = collect_headers("#FormData");
            for (var i in body.content) {
                data.append(i, body.content[i]);
            }
        }
    }

    // Save request for loading later.
    restman.storage.saveRequest(method, url, headers, body, function (evt){});

    request.send(
        url,
        method,
        function(data, textStatus, jqXHR, duration) {
            $('#ResponseStatus').text(jqXHR.status + " " + jqXHR.statusText).addClass("code" + jqXHR.status);

            content_type = jqXHR.getResponseHeader("Content-type");
            content_simple_type = "htmlmixed"; // By default, assume XML, HTML
            if (content_type != null) {
                if (content_type.indexOf("application/json") >= 0) {
                    data = js_beautify(data);
                } else {
                    if (content_type.indexOf("text/html") >= 0) {
                    data = html_beautify(data);
                    }
                }
            }

            // Calculate length of response
            content_length = jqXHR.getResponseHeader("Content-Length");
            if (content_length == null) {
                content_length = data.length
            }

            $('#ResponseType').text(content_type);
            $('#ResponseSize').text(content_length + " bytes");

            $('#ResponseTime').text(parseFloat(duration).toFixed(2) + " ms");

            output = data;
            editors["#ResponseContent"].setValue(output);
            $(".shouldwait").removeClass('loading');
        },
        headers,
        data,
        onProgressHandler
    );
})

$("a.switch-xml").click(function(event) {
    /* Act on the event */
    var textarea = $(this).attr("href");
    editor = editors[textarea];
    editor.setOption("mode", "htmlmixed");

    $(this).parent().parent().children(".active").removeClass('active');
    $(this).parent().addClass('active');
});

$("a.switch-json").click(function(event) {
    /* Act on the event */
    var textarea = $(this).attr("href");
    editor = editors[textarea];
    editor.setOption("mode", "javascript");

    $(this).parent().parent().children(".active").removeClass('active');
    $(this).parent().addClass('active');
});

$("a.switch-plain").click(function(event) {
    /* Act on the event */
    var textarea = $(this).attr("href");
    editor = editors[textarea];
    editor.setOption("mode", "text");

    $(this).parent().parent().children(".active").removeClass('active');
    $(this).parent().addClass('active');
});

/*
 * HEADERS TABLE
 */
$("a.delete-parent").click(function(event) {
    /* Act on the event */
    var row = $(this).parent();
    row.remove();
    // Avoid going to href
    return false;
});

$("a.template-item-cloner").click(function(event) {
    // Get the id for the container
    var anchor = $(this)[0];
    var target = anchor.href.replace(anchor.baseURI, "");
    var parent = $(target);

    cloneListItem(parent);
    // Avoid going to href
    return false;
});

/*
 * CHILD TEMPLATE ITEM
 *
 * This works for things that have a template item and should clone it on
 * demand and append it to the target object.
 *
 */
function cloneListItem(target) {
    // Get the template child to clone
    var original = $(target).children(".template-item");

    // Clone and clean
    if (original) {
        // Clone template (with data and events!)
        var cloned = original.clone(true);
        // Remove id for the clones
        cloned.each(function(index, elem) { elem.id = ""; });
        cloned.removeClass("template-item");

        // Add the new born to the container
        $(target).append(cloned);
        return cloned;
    }
    return false;
}

/*
 * FILE DROP ON TEXT INPUTS (Only for the FormData form)
 *
 * Turn a normal `input[type="text"]` component into a drop-zone for files. When
 * a file is dropped over the input element, it will be converted to a
 * `type="file" element`. This will allow an user to drop a file over the
 * 'value' input element to add a file to the form data.
 *
 */
$('#FormData input[type="text"]').on("dragover drop", function(e) {
    return e.preventDefault();
}).on("drop", function(e) {
    // Change type of this input to file
    target = $(e.target);
    target.attr("type", "file");
    target.prop("files", e.originalEvent.dataTransfer.files);
    return $();
});

/*
 * EXPANDABLES
 */
$("section.expandable .expander").click(function(event) {
    /* Act on the event */
    var section = $(this).parent();

    if (section.hasClass("closed")) {
        section.removeClass("closed");
    } else {
        section.addClass("closed");
    }
    // Avoid going to href when coming from a link
    return false;
});

/*
 * TAB SELECT
 *
 * Turn a normal select into a tab switcher. This works by invoking the
 * "toggle_active_tab" when the select changes. The code needed is like
 * the following:
 *
 *     <select data-tab data-tab-select>
 *         <option value="value1" data-tab-panel="#panel1">Raw</option>
 *         <option value="value2" data-tab-panel="#panel2">Form data</option>
 *     </select>
 *

 *

 *
Title Panel1

 *

 *

 *
Title Panel2

 *

 *

 */
$("[data-tab-select]").change(function (event) {
    self = $(event.target);
    panel = self.children("option:selected").attr('data-tab-panel');

    self.children = function (until, selector) {
        return $('Hi');
    };
    Foundation.libs.tab.toggle_active_tab(self);
});

$(document).ready(function(event) {
    /*
     * LOAD HISTORY ITEM
     *
     * Cargar
     *
     */
    $('[data-history-item]').click(function (event) {
        // Load history item.
        restman.storage.getRequest(parseInt($(this).attr('data-history-item')), function (item){
            $('#Method').val(item.method);
            $('#Url').val(item.url);

            // Load Headers
            // Cleanup headers
            $('#HeadersTable > li:not(.template-item)').remove();
            for (var d in item.headers) {
                var row = cloneListItem($('#HeadersTable'));
                row.find('label.name input').val(d);
                row.find('label.value input').val(item.headers[d]);
            }

            if (!('type' in item.body)) {
                item.body.type = 'raw';
            }
            // Load Body
            if (item.body.type == 'raw') {
                editors["#RequestContent"].setValue(item.body.content);
            }
            if (item.body.type == 'form') {
                // Cleanup form
                $('#FormData > li:not(.template-item)').remove();
                for (var d in item.body.content) {
                    var row = cloneListItem($('#FormData'));
                    row.find('label.name input').val(d);
                    row.find('label.value input').val(item.body.content[d]);
                }
            }
            $('#ContentType').val(item.body.type).change();
            }
        });
        return false;
    });

    reload_history();
});<|endoftext|>


<commit_before>const gulp = require('gulp');
const gutil = require('gulp-util');

const buildAndroid = require('./helpers/buildAndroid');
const buildServer = require('./helpers/buildServer');
const buildWeb = require('./helpers/buildWeb');

/**
 * Build the project
 */
gulp.task('build', ['switch'], () => {
  return new Promise((resolve, reject) => {
    switch (global.settings.platform) {
      case 'android':
        buildAndroid(resolve, reject);
        break;
      case 'web':
        buildWeb(resolve, reject);
        break;
      case 'server': {
        global.settings.platform = 'web';
        buildWeb(() => {
          buildServer('build', resolve);
        }, reject);
        break;
      }
      default:
        gutil.log(gutil.colors.yellow('Not yet implemented'));
        resolve();
    }
  });
});
<commit_msg>Add hints for Windows, iOS, and macOS CLI build commands<commit_after>const gulp = require('gulp');
const gutil = require('gulp-util');

const buildAndroid = require('./helpers/buildAndroid');
const buildServer = require('./helpers/buildServer');
const buildWeb = require('./helpers/buildWeb');

/**
 * Build the project
 */
gulp.task('build', ['switch'], () => {
  return new Promise((resolve, reject) => {
    switch (global.settings.platform) {
      case 'android':
        buildAndroid(resolve, reject);
        break;
      case 'web':
        buildWeb(resolve, reject);
        break;
      case 'server': {
        global.settings.platform = 'web';
        buildWeb(() => {
          buildServer('build', resolve);
        }, reject);
        break;
      }
      case 'ios':
      case 'macos':
        gutil.log(gutil.colors.yellow('Please use XCode to complete the operation.'));
        resolve();
        break;
      case 'windows':
        gutil.log(gutil.colors.yellow('Please use Visual Studio to complete the operation.'));
        resolve();
        break;
      default:
        gutil.log(gutil.colors.yellow('Not yet implemented'));
        resolve();
    }
  });
});
<|endoftext|>


<commit_before>/**
 * Room I/O is a socket wrapper which implements the basic functions of io part
 * @type {*|exports|module.exports}
 */
var express = require('express');
var io = require('socket.io')();
var rooms = require ('./models/rooms');
var app = require('../app');
var auth = require('./auth');

var lobby = rooms.getLobby();
var hashOfUserObjects = {};

var listen = function (server) {
	io.listen(server);
	console.log(app.locals);
	console.log('Server Started and Socket listened on ' + app.get('server-port'));
}

var roomio = io.of('/room');

roomio.on('connection', function (socket) {

	var clientId;
	var clientName;
	auth.verify(socket.handshake.token, function(err, decoded){
		if(err){
			console.log(err);
		} else{
			clientId = decoded.id;
			clientName = decoded.name;
		}
	});

	console.log('a user: ' + clientId + ' connected');
	console.log(socket.request.headers);

	hashOfUserObjects[clientId] = [];
	var socketClient = new rooms.SocketClient(clientId, socket);

	/**
	 * Message IO Handler
	 * */
	socketClient.on('msgToGroup', msgToGroup(clientId, clientName));

	socketClient.on('msgToRoom', msgToRoom(clientId, clientName));

	socketClient.on('msgToUser', msgToUser(socketClient, clientId, clientName));

	/**
	 * Canvas IO Handler
	 * */
	roomio.emit('canvasState', getAllCanvasObjects());

	socketClient.on('canvasAction', canvasAction);

	socketClient.on('canvasUndo', canvasUndo);

	socketClient.on('canvasClear', canvasClear);

	/*
	* WebRTC IO Handler
	* */
	socketClient.on('Emit Message', onSetupMessage(socketClient));

	/*
	* User Status Handler
	* */
	socketClient.on('New User', onNewUser(socketClient, socketClient.socketID));

    socketClient.on('disconnect', onDisconnection(socketClient));

	socketClient.on('joinRoom', joinRoom(clientId));

	socketClient.on('disconnect', leaveRoom(clientId));
	// -------- End of Web RTC IO -----------//
});

/**
 * ================ User Status IO =================
 * =================================================
 * */
function joinRoom(clientId){
	return function(msg){
		var roomId = msg.body.roomId;
		lobby.getUser(clientId).joinRoom(roomId);
		lobby.getUser(clientId).roomBroadcast('joinRoom', clientId);
	}
}

function leaveRoom(clientId){
	return function(){
		lobby.getUser(clientId).leaveRoom();
		lobby.getUser(clientId).roomBroadcast('leaveRoom', clientId);
	}
}

function onNewUser(socketClient, clientId) {
	return function(message) {
		console.log('===================================== Got New User:', message);	        // for a real app, would be room only (not broadcast)

		addNewUserToList(clientId);
		responseIDToClient(socketClient, clientId);
		responseExistingUserToClient(socketClient);
		broadCastID(socketClient, clientId);
	}
}

function broadCastID(socketClient, ID) {
	socketClient.roomBroadcast('New Joined', {'userID':ID});
}

function onDisconnection(socketClient) {
	return function() {
		console.log('Disconnection: ', socketClient.userID);

		// Set disconnect value
		socketClient.setDisconnect();

		// Notify client side WebRTC on user leave
		socketClient.notifyGroupUsersOnUserLeave(socketClient.userID);
	}
}

/**
 * ================== WebRTC IO ===================
 * =================================================
 * */
var userIDList = [];
function addNewUserToList(curID) {
	userIDList.push(curID);
}

function responseIDToClient(socketClient, ID) {
	socketClient.emit('Assigned ID', {'assignedID': ID});
}

// Repond with all existing connected user in current group except myself
function responseExistingUserToClient(socketClient) {
	var currentGroupUserList = socketClient.getCurrentGroupUserList();
	var groupUserIDList = [];
	for (var index in currentGroupUserList) {
		if (currentGroupUserList[index].socketID != socketClient.socketID) {
			groupUserIDList.push(currentGroupUserList[index].socketID);
		}
	}
	socketClient.emit('Existing UserList', {'userIDList': groupUserIDList});
}

function onSetupMessage(socketClient) {
	return function(message) {
		console.log('!!!!!!! Set Up MESSAGE');
		socketClient.roomBroadcast('Setup Message', message);
	}
}

/**
 * ================== Message IO ===================
 * =================================================
 * */
var msgToGroup = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
		}else{
			lobby.getUser(clientId).groupBroadcast('msgToGroup', clientName + msg);
		}
	}
};

var msgToRoom = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
		}else{
			lobby.getUser(clientId).roomBroadcast('msgToRoom', clientName + msg);
		}
	};
};

var msgToUser = function (socketClient, clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var receiverId = getReceiverId(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
			socketClient.emit('systemMsg', 'no such user');
		}else{
			lobby.getUser(clientId).personalMessage('msgToUser', clientName + msg, receiverId);
		}
	}
};

var getReceiverId = function (msg) {
	return msg.receiverId;
};

/**
 * =================== Canvas IO ===================
 * =================================================
 * */
var canvasAction = function (action) {
	var clientId = socket.id;
	console.log(clientId);
	hashOfUserObjects[clientId].push(action);

	roomio.emit('canvasState', getAllCanvasObjects());

	// console.log(redisClient.lpush('canvasAction', action));

	// canvasio.emit('canvasAction', action);
	console.log(hashOfUserObjects);
};

var canvasUndo = function () {
	var clientId = socket.id;
	hashOfUserObjects[clientId].pop();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var canvasClear = function(){
	clearAllCanvasObjects();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var getAllCanvasObjects = function () {
	var currentCavansObjects = [];
	for (var userObjectsKey in hashOfUserObjects) {
		currentCavansObjects = currentCavansObjects.concat(hashOfUserObjects[userObjectsKey]);
		// console.log(hashOfUserObjects[userObjectsKey]);
	}
	return currentCavansObjects;
};

var clearAllCanvasObjects = function () {
	for (var userObjectsKey in hashOfUserObjects) {
		hashOfUserObjects[userObjectsKey] = [];
	}
};

module.exports.listen = listen;<commit_msg>revert room.io<commit_after>/**
 * Room I/O is a socket wrapper which implements the basic functions of io part
 * @type {*|exports|module.exports}
 */
var express = require('express');
var io = require('socket.io')();
var rooms = require ('./models/rooms');
var app = require('../app');
var auth = require('./auth');

var lobby = rooms.getLobby();
var hashOfUserObjects = {};

var listen = function (server) {
	io.listen(server);
	console.log(app.locals);
	console.log('Server Started and Socket listened on ' + app.get('server-port'));
}

var roomio = io.of('/room');

roomio.on('connection', function (socket) {

	var clientId;
	var clientName;
	auth.verify(socket.handshake.token, function(err, decoded){
		if(err){
			console.log(err);
		} else{
			clientId = decoded.id;
			clientName = decoded.name;
		}
	});

	console.log('a user: ' + clientId + ' connected');
	console.log(socket.request.headers);

	hashOfUserObjects[clientId] = [];
	var socketClient = new rooms.SocketClient(clientId, socket);
	socketClient.joinRoom('0dab2c05-af24-46f3-80b0-41e4dd3d64bf');
	socketClient.groupBroadcast('message', {});

	/**
	 * Message IO Handler
	 * */
	socketClient.on('msgToGroup', msgToGroup(clientId, clientName));

	socketClient.on('msgToRoom', msgToRoom(clientId, clientName));

	socketClient.on('msgToUser', msgToUser(socketClient, clientId, clientName));

	/**
	 * Canvas IO Handler
	 * */
	roomio.emit('canvasState', getAllCanvasObjects());

	socketClient.on('canvasAction', canvasAction);

	socketClient.on('canvasUndo', canvasUndo);

	socketClient.on('canvasClear', canvasClear);

	/*
	* WebRTC IO Handler
	* */
	socketClient.on('Emit Message', onSetupMessage(socketClient));

	/*
	* User Status Handler
	* */
	socketClient.on('New User', onNewUser(socketClient, socketClient.socketID));

    socketClient.on('disconnect', onDisconnection(socketClient));

	socketClient.on('joinRoom', joinRoom(clientId));

	socketClient.on('disconnect', leaveRoom(clientId));
	// -------- End of Web RTC IO -----------//
});

/**
 * ================ User Status IO =================
 * =================================================
 * */
function joinRoom(clientId){
	return function(msg){
		var roomId = msg.body.roomId;
		lobby.getUser(clientId).joinRoom(roomId);
		lobby.getUser(clientId).roomBroadcast('joinRoom', clientId);
	}
}

function leaveRoom(clientId){
	return function(){
		lobby.getUser(clientId).leaveRoom();
		lobby.getUser(clientId).roomBroadcast('leaveRoom', clientId);
	}
}

function onNewUser(socketClient, clientId) {
	return function(message) {
		console.log('===================================== Got New User:', message);	        // for a real app, would be room only (not broadcast)

		addNewUserToList(clientId);
		responseIDToClient(socketClient, clientId);
		responseExistingUserToClient(socketClient);
		broadCastID(socketClient, clientId);
	}
}

function broadCastID(socketClient, ID) {
	socketClient.roomBroadcast('New Joined', {'userID':ID});
}

function onDisconnection(socketClient) {
	return function() {
		console.log('Disconnection: ', socketClient.userID);

		// Set disconnect value
		socketClient.setDisconnect();

		// Notify client side WebRTC on user leave
		socketClient.notifyGroupUsersOnUserLeave(socketClient.userID);
	}
}

/**
 * ================== WebRTC IO ===================
 * =================================================
 * */
var userIDList = [];
function addNewUserToList(curID) {
	userIDList.push(curID);
}

function responseIDToClient(socketClient, ID) {
	socketClient.emit('Assigned ID', {'assignedID': ID});
}

// Repond with all existing connected user in current group except myself
function responseExistingUserToClient(socketClient) {
	var currentGroupUserList = socketClient.getCurrentGroupUserList();
	var groupUserIDList = [];
	for (var index in currentGroupUserList) {
		if (currentGroupUserList[index].socketID != socketClient.socketID) {
			groupUserIDList.push(currentGroupUserList[index].socketID);
		}
	}
	socketClient.emit('Existing UserList', {'userIDList': groupUserIDList});
}

function onSetupMessage(socketClient) {
	return function(message) {
		console.log('!!!!!!! Set Up MESSAGE');
		socketClient.roomBroadcast('Setup Message', message);
	}
}

/**
 * ================== Message IO ===================
 * =================================================
 * */
var msgToGroup = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
		}else{
			lobby.getUser(clientId).groupBroadcast('msgToGroup', clientName + msg);
		}
	}
};

var msgToRoom = function (clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
		}else{
			lobby.getUser(clientId).roomBroadcast('msgToRoom', clientName + msg);
		}
	};
};

var msgToUser = function (socketClient, clientId, clientName) {
	return function(msg) {
		console.log(msg);
		var receiverId = getReceiverId(msg);
		var user = lobby.getUser(clientId);
		if(user == null){
			console.log('no such user');
			socketClient.emit('systemMsg', 'no such user');
		}else{
			lobby.getUser(clientId).personalMessage('msgToUser', clientName + msg, receiverId);
		}
	}
};

var getReceiverId = function (msg) {
	return msg.receiverId;
}

/**
 * =================== Canvas IO ===================
 * =================================================
 * */
var canvasAction = function (action) {
	var clientId = socket.id;
	console.log(clientId);
	hashOfUserObjects[clientId].push(action);

	roomio.emit('canvasState', getAllCanvasObjects());

	// console.log(redisClient.lpush('canvasAction', action));

	// canvasio.emit('canvasAction', action);
	console.log(hashOfUserObjects);
};

var canvasUndo = function () {
	var clientId = socket.id;
	hashOfUserObjects[clientId].pop();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var canvasClear = function(){
	clearAllCanvasObjects();
	roomio.emit('canvasState', getAllCanvasObjects());
};

var getAllCanvasObjects = function () {
	var currentCavansObjects = [];
	for (var userObjectsKey in hashOfUserObjects) {
		currentCavansObjects = currentCavansObjects.concat(hashOfUserObjects[userObjectsKey]);
		// console.log(hashOfUserObjects[userObjectsKey]);
	}
	return currentCavansObjects;
};

var clearAllCanvasObjects = function () {
	for (var userObjectsKey in hashOfUserObjects) {
		hashOfUserObjects[userObjectsKey] = [];
	}
};

module.exports.listen = listen;<|endoftext|>