<commit_before>/**
 * Created by demis.bellot@gmail.com
 * Open Source under the New BSD Licence: https://github.com/AjaxStack/AjaxStack/blob/master/LICENSE
 */

//for non-modern browsers i.e: <=IE8
!window.JSON && document.write(unescape('%3Cscript src=""http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js""%3E%3C/script%3E'));

var cssText =
  ".jsonreport TABLE { border-collapse:collapse; border: solid 1px #ccc; clear: left; }\r\n" +
  ".jsonreport TH { text-align: left; padding: 4px 8px; text-shadow: #fff 1px 1px -1px; background: #f1f1f1; white-space:nowrap; cursor:pointer; font-weight: bold; }\r\n" +
  ".jsonreport TH, .jsonreport TD, .jsonreport TD DT, .jsonreport TD DD { font-size: 13px; font-family: Arial; }\r\n" +
  ".jsonreport TD { padding: 8px 8px 0 8px; vertical-align: top; }\r\n" +
  ".jsonreport DL { clear: left; }\r\n" +
  ".jsonreport DT { margin: 10px 0 5px 0; font: bold 18px Helvetica, Verdana, Arial; width: 200px; clear: left; float: left; display:block; white-space:nowrap; }\r\n" +
  ".jsonreport DD { margin: 5px 10px; font: 18px Arial; padding: 2px; display: block; float: left; }\r\n" +
  ".jsonreport DL DL DT { font: bold 16px Arial; }\r\n" +
  ".jsonreport DL DL DD { font: 16px Arial; }\r\n" +
  ".jsonreport HR { display:none; }\r\n" +
  ".jsonreport TD DL HR { display:block; padding: 0; clear: left; border: none; }\r\n" +
  ".jsonreport TD DL { padding: 4px; margin: 0; height:100%; max-width: 700px; }\r\n" +
  ".jsonreport DL TD DL DT { padding: 2px; margin: 0 10px 0 0; font-weight: bold; font-size: 13px; width: 120px; overflow: hidden; clear: left; float: left; display:block; }\r\n" +
  ".jsonreport DL TD DL DD { margin: 0; padding: 2px; font-size: 13px; display: block; float: left; }\r\n" +
  ".jsonreport TBODY>TR:last-child>TD { padding: 8px; }\r\n" +
  ".jsonreport THEAD { -webkit-user-select:none; -moz-user-select:none; }\r\n" +
  ".jsonreport .desc, .jsonreport .asc { background-color: #FAFAD2; }\r\n" +
  ".jsonreport .desc { background-color: #D4EDC9; }\r\n" +
  ".jsonreport TH B { display:block; float:right; margin: 0 0 0 5px; width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #ccc; border-bottom: none; }\r\n" +
  ".jsonreport .asc B { border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #333; border-bottom: none; }\r\n" +
  ".jsonreport .desc B { border-left: 5px solid transparent; border-right: 5px solid transparent; border-bottom: 5px solid #333; border-top: none; }\r\n" +
  ".jsonreport H3 { font-size: 18px; margin: 0 0 10px 0; }";

document.write('\r\n');

if (!_) var _ = {};
_.jsonreport = (function(){
    var root = this, doc = document,
        $ = function(id) { return doc.getElementById(id); },
        $$ = function(sel) { return doc.getElementsByTagName(sel); },
        $each = function(fn) { for (var i=0,len=this.length; i<len; i++) fn(i, this[i], this); },
        isIE = /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);

    $.each = function(arr, fn) { $each.call(arr, fn); };

    var splitCase = function(t) { return typeof t != 'string' ? t : t.replace(/([A-Z]|[0-9]+)/g, ' $1').replace('_',' '); },
        uniqueKeys = function(m){ var h={}; for (var i=0,len=m.length; i<len; i++) for (var k in m[i]) h[k] = k; return h; },
        keys = function(o){ var a=[]; for (var k in o) a.push(k); return a; }
    var tbls = [];

    function val(m) {
      if (m == null) return '';
      if (typeof m == 'number') return num(m);
      if (typeof m == 'string') return str(m);
      return m.length ? arr(m) : obj(m);
    }
    function num(m) { return m; }
    function str(m) {
      return m.substr(0,6) == '/Date(' ? dfmt(date(m)) : m;
    }
    function date(s) { return new Date(parseFloat(/Date\(([^)]+)\)/.exec(s)[1])); }
    function pad(d) { return d < 10 ? '0'+d : d; }
    function dfmt(d) { return d.getFullYear() + '/' + pad(d.getMonth() + 1) + '/' + pad(d.getDate()); }
    function obj(m) {
      var sb = '
';
      for (var k in m) sb += '
' + splitCase(k) + '

' + val(m[k]) + '
';
      sb += '
';
      return sb;
    }
    function arr(m) {
      if (typeof m[0] == 'string' || typeof m[0] == 'number') return m.join(', ');
      var id=tbls.length, h=uniqueKeys(m);
      var sb = '

';
      tbls.push(m);
      var i=0;
      for (var k in h) sb += '' + splitCase(k) + '	';
      sb += '

' + makeRows(h,m) + '

';
      return sb;
    }

    function makeRows(h,m) {
      var sb = '';
      for (var r=0,len=m.length; r<len; r++) {
        sb += '
';
        var row = m[r];
        for (var k in h) sb += '' + val(row[k]) + '	';
        sb += '
';
      }
      return sb;
    }

    function setTableBody(tbody, html) {
      if (!isIE) { tbody.innerHTML = html; return; }
      var temp = tbody.ownerDocument.createElement('div');
      temp.innerHTML = '
' + html + '
';
      tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);
    }

    function clearSel() {
      if (doc.selection && doc.selection.empty) doc.selection.empty();
      else if(root.getSelection) {
        var sel=root.getSelection();
        if (sel && sel.removeAllRanges) sel.removeAllRanges();
      }
    }

    function cmp(v1, v2){
      var f1, f2, f1=parseFloat(v1), f2=parseFloat(v2);
      if (!isNaN(f1) && !isNaN(f2)) v1=f1, v2=f2;
      if (typeof v1 == 'string' && v1.substr(0,6) == '/Date(') v1=date(v1), v2=date(v2);
      if (v1 == v2) return 0;
      return v1 > v2 ? 1 : -1;
    }

    function enc(html) {
      if (typeof html != 'string') return html;
      return html.replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
    }

    function addEvent(obj, type, fn) {
      if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( root.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
    }

    addEvent(doc, 'click', function (e) {
        e = e || root.event, el = e.target || e.srcElement, cls = el.className;
        if (el.tagName == 'B') el = el.parentNode;
        if (el.tagName != 'TH') return;
        el.className = cls == 'asc' ? 'desc' : (cls == 'desc' ? null : 'asc');
        $.each($$('TH'), function(i,th){ if (th == el) return; th.className = null; });
        clearSel();
        var ids=el.id.split('-'), tId=ids[1], cId=ids[2];
        var tbl=tbls[tId].slice(0), h=uniqueKeys(tbl), col=keys(h)[cId], tbody=el.parentNode.parentNode.nextSibling;
        if (!el.className){ setTableBody(tbody, makeRows(h,tbls[tId])); return; }
        var d=el.className=='asc'?1:-1;
        tbl.sort(function(a,b){ return cmp(a[col],b[col]) * d; });
        setTableBody(tbody, makeRows(h,tbl));
    });

    return function(json) {
        var model = JSON.parse(json);
        return val(model);
    };
})();
<commit_msg>remove unused jsonreport.js<commit_after><|endoftext|>


<commit_before>javascript:!function() {
  var loc = document.location.href,
  div = document.createElement('div'),
  ua = window.navigator.userAgent.toLowerCase(),
  day = 'v20150912',
  ver = '' + day + '';
  switch (true) {
//いつもの放送ページの処理
  case /live\.nicovideo\.jp\/watch/.test(loc): {
  //ここ仕様変更に弱そう
    var url = document.querySelector('meta[property="og:url"]'),
  //放送IDを取得
    liveId = url.replace(/.+?watch\/(lv\d+).*/, '$1'),
    Aries = '',
    delButton = 'var f = "flvplayer_container",flv = document.getElementById(f);flv.parentNode.removeChild(flv);';
//放送主かどうか
  //ログインしてるユーザーIDを取得
    var myUserIdSource = document.querySelectorAll('div[id="hide_tool_box"] > script'),
    myUserId = myUserIdSource[1].outerHTML.replace(/[\s\S]+id: (\d+),[\s\S]+/, '$1');
  //放送主のユーザーIDを取得(表示がない放送は0)
    var liveUserIdSource = document.querySelector('.nicopedia_nushi');
      if (!liveUserIdSource) {
        liveUserId = 0;
      } else {
        var liveUserId = liveUserIdSource.innerHTML.replace(/[\s\S]+nicovideo.jp\/user\/(\d+)[\s\S]+/, '$1');
      }
  //ログインしてるユーザーIDと放送主のユーザーIDを比較
      if (myUserId != liveUserId) {
        nushi = 'N';
      } else {
        nushi = 'Y';
      }
    break;
//新しい放送ページ(？)の処理
  } case /live2\.nicovideo\.jp\/watch/.test(loc): {
    var liveId = loc.replace(/.+?watch\/(lv\d+).*/, '$1');
    if (ua.indexOf('firefox') != -1) {
      s = document.getElementsByTagName('script')[17].outerHTML;
    } else {
      s = document.getElementsByTagName('script')[16].outerHTML;
    }
    var p = s.replace(/[\s\u2028\u2029]/g,''),
    //URL のパラメータ
      we = 'webSocketUrl=ws://a.live2.nicovideo.jp/wsapi/v1/watch/',
      au = p.replace(/.*?"(audienceToken)".+?"(\w+)".*/,'&$1=$2'),
      re = p.replace(/.*?"(relatedNicoliveProgramId)".+?"(\w+)".*/,'&$1=$2'),
      br = p.replace(/.*?"(broadcastId)".+?"(\d+)".*/,'&$1=$2'),
      be = p.replace(/.*?"(beginTime)".+?"(\d+)".*/,'&$1=$2');
      Aries = '<input type="button" value="Aries" onClick="window.open(\'http://nl.nimg.jp/public/relive/1.4.36/assets/web/r1/swfs/v1/AriesPlayer.swf?' + we + au + re + br + be + '\',\'_blank\',\'width=960,height=512\');var f = "playerswf",flv = document.getElementById(f);flv.parentNode.removeChild(flv);">
',
      delButton = 'var f = "playerswf",flv = document.getElementById(f);flv.parentNode.removeChild(flv);',
      nushi = 'N';
    break;
//それ以外のページの処理
  } default: {
    var liveId = prompt('放送IDかURL', '');
    if (liveId.match(/lv[0-9]+/)) {
      liveId = liveId.replace(/.+?(lv\d+).*/, '$1'),
      Aries = '',
      delButton = '',
      nushi = 'Y';
    } else {
      alert('放送IDが入ってないよ！\n「' + liveId + '」\n連絡先とか　http://nico.ms/ar303976');
      return false;
    }
    break;
  }}
//放送主だったら追加
  if (nushi == 'Y') {
    nama1 = '放送主用
<input type="button" value="配信ツール" onClick="window.open(\'http://live.nicovideo.jp/nicolivebroadcaster.swf?dicfilename=NicoliveBroadcasterDictionaryJAJP.swf&v=' + liveId + '\',\'_blank\',\'width=900,height=250\')"><input type="button" value="放送情報変更" onClick="window.open(\'http://live.nicovideo.jp/editstream/' + liveId + '\',\'_blank\',\'width=960,height=600,scrollbars=1\')">
<input type="button" value="配信ツール(原宿)" onClick="window.open(\'http://live.nicovideo.jp/utility_v1.swf?v=' + liveId + '\',\'_blank\',\'width=950,height=200\')"> ',
    nama2 = '
※配信ツールはセッションが使えません
※かんたん配信タブは1番最初に操作したウィンドウの
配信ツールでなるべくいじってください
※放送情報変更の反映は少し時間がかかります
';
  } else {
    nama1 = '',
    nama2 = '';
  }
//ページに追加
    div.innerHTML = '
×プレイヤー変更
' + Aries + '<input type="button" value="GINZA" onClick="window.open(\'http://live.nicovideo.jp/nicoliveplayer.swf?v=' + liveId + '&languagecode=ja-jp\',\'_blank\',\'width=960,height=490\');' + delButton + '"><input type="button" value="ニコファーレ" onClick="window.open(\'http://live.nicovideo.jp/liveplayer_farre.swf?v=' + liveId + '\',\'_blank\',\'width=960,height=520\');' + delButton + '">
<input type="button" value="原宿" onClick="window.open(\'http://live.nicovideo.jp/liveplayer.swf?v=' + liveId + '\',\'_blank\',\'width=950,height=520\');' + delButton + '"><input type="button" value="ページ更新" onClick="window.location.reload(true)">
' + nama1 + nama2 + ver;
    div.style.color = 'rgb(250,250,250)';
    div.style.textAlign = 'center';
    div.style.padding = '10px';
    div.style.position = 'fixed';
    div.style.zIndex = '9999';
    div.style.fontSize = '12px';
    div.style.border = '2px solid black';
    div.style.right = '20px';
    div.style.bottom = '20px';
    div.style.background = 'rgba(0,128,255,0.5)';
    div.setAttribute("id", "nicoLivew");
    document.body.appendChild(m);
}();
<commit_msg>burasshuappu<commit_after>javascript:!function() {
  var loc = document.location.href,
  div = document.createElement('div'),
  ua = window.navigator.userAgent.toLowerCase(),
  day = 'v20150912',
  ver = '' + day + '';
  switch (true) {
//いつもの放送ページの処理
  case /live\.nicovideo\.jp\/watch/.test(loc): {
  //ここ仕様変更に弱そう
    var url = document.querySelector('meta[property="og:url"]'),
  //放送IDを取得
    liveId = url.replace(/.+?watch\/(lv\d+).*/, '$1'),
    Aries = '',
    delButton = 'var f = "flvplayer_container",flv = document.getElementById(f);flv.parentNode.removeChild(flv);';
//放送主かどうか
  //ログインしてるユーザーIDを取得
    var myUserIdSource = document.querySelectorAll('div[id="hide_tool_box"] > script'),
    myUserId = myUserIdSource[1].outerHTML.replace(/[\s\S]+id: (\d+),[\s\S]+/, '$1');
  //放送主のユーザーIDを取得(表示がない放送は0)
    var liveUserIdSource = document.querySelector('.nicopedia_nushi');
      if (!liveUserIdSource) {
        liveUserId = 0;
      } else {
        var liveUserId = liveUserIdSource.innerHTML.replace(/[\s\S]+nicovideo.jp\/user\/(\d+)[\s\S]+/, '$1');
      }
  //ログインしてるユーザーIDと放送主のユーザーIDを比較
      if (myUserId != liveUserId) {
        nushi = 'N';
      } else {
        nushi = 'Y';
      }
    break;
//新しい放送ページ(？)の処理
  } case /live2\.nicovideo\.jp\/watch/.test(loc): {
    var liveId = loc.replace(/.+?watch\/(lv\d+).*/, '$1');
    if (ua.indexOf('firefox') != -1) {
      s = document.getElementsByTagName('script')[17].outerHTML;
    } else {
      s = document.getElementsByTagName('script')[16].outerHTML;
    }
    var p = s.replace(/[\s\u2028\u2029]/g,''),
    //URL のパラメータ
      we = 'webSocketUrl=ws://a.live2.nicovideo.jp/wsapi/v1/watch/',
      au = p.replace(/.*?"(audienceToken)".+?"(\w+)".*/,'&$1=$2'),
      re = p.replace(/.*?"(relatedNicoliveProgramId)".+?"(\w+)".*/,'&$1=$2'),
      br = p.replace(/.*?"(broadcastId)".+?"(\d+)".*/,'&$1=$2'),
      be = p.replace(/.*?"(beginTime)".+?"(\d+)".*/,'&$1=$2');
      Aries = '<input type="button" value="Aries" onClick="window.open(\'http://nl.nimg.jp/public/relive/1.4.36/assets/web/r1/swfs/v1/AriesPlayer.swf?' + we + au + re + br + be + '\',\'_blank\',\'width=960,height=512\');var f = "playerswf",flv = document.getElementById(f);flv.parentNode.removeChild(flv);">
',
      delButton = 'var f = "playerswf",flv = document.getElementById(f);flv.parentNode.removeChild(flv);',
      nushi = 'N';
    break;
//それ以外のページの処理
  } default: {
    var liveId = prompt('放送IDかURL', '');
    if (liveId.match(/lv[0-9]+/)) {
      liveId = liveId.replace(/.+?(lv\d+).*/, '$1'),
      Aries = '',
      delButton = '',
      nushi = 'Y';
    } else {
      alert('放送IDが入ってないよ！\n「' + liveId + '」\n連絡先とか　http://nico.ms/ar303976');
      return false;
    }
    break;
  }}
//放送主だったら追加
  if (nushi == 'Y') {
    nama1 = '放送主用
<input type="button" value="配信ツール" onClick="window.open(\'http://live.nicovideo.jp/nicolivebroadcaster.swf?dicfilename=NicoliveBroadcasterDictionaryJAJP.swf&v=' + liveId + '\',\'_blank\',\'width=900,height=250\')"><input type="button" value="放送情報変更" onClick="window.open(\'http://live.nicovideo.jp/editstream/' + liveId + '\',\'_blank\',\'width=960,height=600,scrollbars=1\')">
<input type="button" value="配信ツール(原宿)" onClick="window.open(\'http://live.nicovideo.jp/utility_v1.swf?v=' + liveId + '\',\'_blank\',\'width=950,height=200\')"> ',
    nama2 = '
※配信ツールはセッションが使えません
※かんたん配信タブは1番最初に操作したウィンドウの
配信ツールでなるべくいじってください
※放送情報変更の反映は少し時間がかかります
';
  } else {
    nama1 = '',
    nama2 = '';
  }
//ページに追加
    div.innerHTML = '
×プレイヤー変更
' + Aries + '<input type="button" value="GINZA" onClick="window.open(\'http://live.nicovideo.jp/nicoliveplayer.swf?v=' + liveId + '&languagecode=ja-jp\',\'_blank\',\'width=960,height=490\');' + delButton + '"><input type="button" value="ニコファーレ" onClick="window.open(\'http://live.nicovideo.jp/liveplayer_farre.swf?v=' + liveId + '\',\'_blank\',\'width=960,height=520\');' + delButton + '">
<input type="button" value="原宿" onClick="window.open(\'http://live.nicovideo.jp/liveplayer.swf?v=' + liveId + '\',\'_blank\',\'width=950,height=520\');' + delButton + '"><input type="button" value="ページ更新" onClick="window.location.reload(true)">
' + nama1 + nama2 + ver;
    div.style.color = 'rgb(250,250,250)';
    div.style.textAlign = 'center';
    div.style.padding = '10px';
    div.style.position = 'fixed';
    div.style.zIndex = '9999';
    div.style.fontSize = '12px';
    div.style.border = '2px solid black';
    div.style.right = '20px';
    div.style.bottom = '20px';
    div.style.background = 'rgba(0,128,255,0.5)';
    div.setAttribute("id", "nicoLivew");
    document.body.appendChild(div);
}();
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var express = require('express');
var fs = require('fs');
var socket = require('./socket').socket;
var sg = require('./shadergen');

var serve = function () {
  exec('mkdir -p test-project/gen/ && find dasBoot/ -type f -name "*.js" | sort |xargs cat > test-project/gen/dasBoot.js',

       function(error, stdout, stderr){

    var frontend = express();
    frontend.use(express.static(__dirname + '/frontend'));
    frontend.listen(8000);

    var sockets = express();
    var sockets_server = require('http').createServer(sockets);
    socket.installHandlers(sockets_server, {prefix: '/socket'});
    sockets_server.listen(1337, '0.0.0.0');

    var files = express();
    files.use(function(req, res, next) {
      res.setHeader("Access-Control-Allow-Origin", "*");
      return next();
    });
    files.use(express.static(__dirname + '/test-project'));
    files.listen(9999);

    console.log('serving nin on http://localhost:8000');

    sg.shaderGen(function() { console.log("Shaders compiled"); });
  });
}

module.exports = {serve: serve};
<commit_msg>Add Origin * header to file server<commit_after>var exec = require('child_process').exec;
var express = require('express');
var fs = require('fs');
var socket = require('./socket').socket;
var sg = require('./shadergen');

var serve = function () {
  exec('mkdir -p test-project/gen/ && find dasBoot/ -type f -name "*.js" | sort |xargs cat > test-project/gen/dasBoot.js',

       function(error, stdout, stderr){

    var frontend = express();
    frontend.use(express.static(__dirname + '/frontend'));
    frontend.listen(8000);

    var sockets = express();
    var sockets_server = require('http').createServer(sockets);
    socket.installHandlers(sockets_server, {prefix: '/socket'});
    sockets_server.listen(1337, '0.0.0.0');

    var files = express();
    files.use(function(req, res, next) {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader("Origin", "*");
      return next();
    });
    files.use(express.static(__dirname + '/test-project'));
    files.listen(9999);

    console.log('serving nin on http://localhost:8000');

    sg.shaderGen(function() { console.log("Shaders compiled"); });
  });
}

module.exports = {serve: serve};
<|endoftext|>


<commit_before>// MP CLAIM ================================================================================
// open claim editor
function claimEditorLoad() {
    currFormType = "claim";
    $("#mp-claim-form").show();
    $('#quote').show();
    $("#claim-label-data-editor").hide();
    $(".annotator-save").hide();
    $("#mp-data-nav").hide();
    $("#mp-data-form-evRelationship").hide();
    $("#mp-data-form-participants").hide();
    $("#mp-data-form-dose1").hide();
    $("#mp-data-form-dose2").hide();
    $("#mp-data-form-auc").hide();
    $("#mp-data-form-cmax").hide();
    $("#mp-data-form-clearance").hide();
    $("#mp-data-form-halflife").hide();
    $("#mp-data-form-studytype").hide();
}

// scroll to the claim text span
function viewClaim() {
    annotationId = $('#mp-editor-claim-list option:selected').val();
    scrollToAnnotation(annotationId, "claim", 0);
}

// edit claim
function editClaim() {
    annotationId = $('#mp-editor-claim-list option:selected').val();

    scrollToAnnotation(annotationId, "claim", 0);
    showEditor();
    claimEditorLoad();

    $.ajax({url: "http://" + config.annotator.host + "/annotatorstore/annotations/" + annotationId,
            data: {},
            method: 'GET',
            error : function(jqXHR, exception){
                console.log(exception);
            },
            success : function(annotation){
                // enable delete button
                $("#annotator-delete").show();

                // call AnnotatorJs editor for update
                app.annotations.update(annotation);
            }
           });
}

$("#Drug1").change(function (){selectDrug();});
$("#Drug2").change(function (){selectDrug();});

function selectDrug() {
    var drug1 = $("#Drug1").val();
    var drug2 = $("#Drug2").val();
    var quotestring = $("#quote").html();
    quotestring = quotestring.replace(drug2, ""+drug2+"");
    quotestring = quotestring.replace(drug1, ""+drug1+"");
    $("#quote").html(quotestring);
}

$("#Drug1").mousedown(function (){deselectDrug();});
$("#Drug2").mousedown(function (){deselectDrug();});

function deselectDrug() {
    var drug1 = $("#Drug1").val();
    var drug2 = $("#Drug2").val();
    var quotestring = $("#quote").html();
    quotestring = quotestring.replace(""+drug2+"", drug2);
    quotestring = quotestring.replace(""+drug1+"", drug1);
    $("#quote").html(quotestring);
}

// when relationship is inhibits or substrate of, show field enzyme
function showEnzyme() {

    if($("#relationship option:selected").text()=="inhibits"||$("#relationship option:selected").text()=="substrate of") {
        $("#enzyme")[0].selectedIndex = 0;
        $("#enzymesection1").show();
        $("#enzyme").show();

        $('input[name=precipitant]').prop('checked', false);
        $('input[type=radio][name=precipitant]').hide();
        $('.precipitantLabel').hide();
    }
    if($("#relationship option:selected").text()=="interact with") {
        $("#enzymesection1").hide();
        $("#enzyme").hide();
        $('input[type=radio][name=precipitant]').show();
        $('.precipitantLabel').show();
    }
}

// modify annotaiton id when user pick claim on mpadder's menu
// update annotation table if necessary
function claimSelectedInMenu(annotationId) {
    currAnnotationId = annotationId;
    annTableId = $('#mp-editor-claim-list option:selected').val();

    if (annotationId != annTableId){
        $("#mp-editor-claim-list option[value='" + annotationId + "']").attr("selected", "true");
        changeClaimInAnnoTable();
    }
}

// MP DATA & MATERIAL ========================================================================
// called when click annotation table cell when value of cell is empty
// (1) if no text selection avaliable, then pop up warning message then return
// to mp annotation table
// (2) otherwise, load annotation to editor, then shown specific data form
function addDataCellByEditor(field, dataNum, isNewData) {

    $("#button#drug1-dose-switch-btn").focus();

    var annotationId = $('#mp-editor-claim-list option:selected').val();
    console.log("addDataCellByEditor - id: " + annotationId + " | data: " + dataNum + " | field: " + field);

    $("#claim-label-data-editor").show();

    // return if no text selection
    if (!isTextSelected && field != "evRelationship" && field != "studytype") {
        warnSelectTextSpan(field);
    } else {
        // hide data fields navigation if editing evidence relationship
        if (field == "evRelationship" || field == "studytype") {
            $("#mp-data-nav").hide();
            $(".annotator-save").hide();
        } else {
            $(".annotator-save").show();
        }

        // cached editing data cell
        currAnnotationId = annotationId;
        currDataNum = dataNum;
        currFormType = field;

        showEditor();
        if (cachedOATarget.hasSelector != null)
            $("#" + field + "quote").html(cachedOATarget.hasSelector.exact);
        $("#annotator-delete").hide();

        // updating current MP annotation
        if (annotationId != null)
            currAnnotationId = annotationId;

        preDataForm(field);

        $.ajax({url: "http://" + config.annotator.host + "/annotatorstore/annotations/" + annotationId,
                data: {},
                method: 'GET',
                error : function(jqXHR, exception){
                    console.log(exception);
                },
                success : function(annotation){
                    // add data if not avaliable
                    if (annotation.argues.supportsBy.length == 0 || isNewData){

                        var data = {type : "mp:data", evRelationship: "", auc : {}, cmax : {}, clearance : {}, halflife : {}, supportsBy : {type : "mp:method", supportsBy : {type : "mp:material", participants : {}, drug1Dose : {}, drug2Dose : {}}}, grouprandom: "", parallelgroup: ""};
                        annotation.argues.supportsBy.push(data);
                    }

                    // call AnnotatorJs editor for update
                    app.annotations.update(annotation);

                }
               });
        }
}

// called when click annotation table cell when value of cell is not null
// (1) scroll to the annotation upon document
// (2) load annotation to editor, then shown specific data form
function editDataCellByEditor(field, dataNum) {

    showEditor();
    $("#claim-label-data-editor").show();
    $('#quote').hide();

    // hide data fields navigation if editing evidence relationship
    if (field == "evRelationship" || field == "studytype") {
        $("#mp-data-nav").hide();
        $(".annotator-save").hide();
    } else {
        $(".annotator-save").show();
    }

    var annotationId = $('#mp-editor-claim-list option:selected').val();
    console.log("editDataCellByEditor - id: " + annotationId + " | data: " + dataNum + " | field: " + field);

    // cached editing data cell
    currAnnotationId = annotationId;
    currDataNum = dataNum;
    currFormType = field;

    // scroll to the position of annotation
    scrollToAnnotation(annotationId, field, dataNum);

    $.ajax({url: "http://" + config.annotator.host + "/annotatorstore/annotations/" + annotationId,
            data: {},
            method: 'GET',
            error : function(jqXHR, exception){
                console.log(exception);
            },
            success : function(annotation){

                // updating current MP annotation
                if (annotationId != null)
                    currAnnotationId = annotationId;

                //switchDataForm(field, true);
                preDataForm(field, true);

                // show delete button
                data = annotation.argues.supportsBy[dataNum];
                material = data.supportsBy.supportsBy;
                if ((field == "participants" && material.participants.value != null) || (field == "dose1" && material.drug1Dose.value != null) || (field == "dose2" && material.drug2Dose.value != null) || ((field == "auc" || field == "cmax" || field == "clearance" || field == "halflife") && (data[field].value != null)))
                    $("#annotator-delete").show();

                // call AnnotatorJs editor for update
                app.annotations.update(annotation);
            }
           });
}

// warning dialog for opening data editor
function preDataForm(targetField, isNotNeedValid) {
    $("#mp-claim-form").hide();
    quoteF = $('#'+targetField+'quote').html();
    // unsaved warning box
    if (!warnUnsavedDialog())
        return;

    if (!isTextSelected && (targetField != "evRelationship" || targetField != "studytype") && quoteF == "" && !isNotNeedValid) {
        warnSelectTextSpan(targetField);
        return;
    }

    if (targetField == null)
        targetField = "participants";

    currFormType = targetField;

    focusOnDataField(targetField);
}

// switch data from from nav button
function switchDataForm(targetField, isNotNeedValid) {

    $("#mp-claim-form").hide();
    quoteF = $('#'+targetField+'quote').html();
    // unsaved warning box
    if (!warnUnsavedDialog())
        return;

    // pop up warn for selecting span when switch to new targetField dring editing mode
    if (!isTextSelected && (targetField != "evRelationship" || targetField != "studytype") && quoteF == "" && !isNotNeedValid) {
        warnSelectTextSpan(targetField);
        return;
    }

    if (targetField == null)
        targetField = "participants";

    currFormType = targetField;

    //redraw data currhighlight
    app.annotations.update(currAnnotation);
    // scroll to the position of annotation
    scrollToAnnotation(currAnnotation.id, currFormType, currDataNum);

    switchDataFormHelper(targetField);
}

// when switch data field, show or hide delete button, nav buttons and data forms
function switchDataFormHelper(targetField) {

    // field actual div id mapping
    fieldM = {"evRelationship":"evRelationship", "participants":"participants", "dose1":"drug1Dose", "dose2":"drug2Dose", "auc":"auc", "cmax":"cmax", "clearance":"clearance", "halflife":"halflife", "studytype":"studytype"};

    var showDeleteBtn = false;

    for (var field in fieldM) {
        var dataid = "mp-data-form-"+field;
        if (field === targetField) {
            $("#"+dataid).show();  // show specific data form
            // inspect that is target form has value filled

            if (field == "evRelationship" || field =="studytype") { // when field is radio button
                fieldVal = $("input[name="+field+"]:checked").val();
            } else if (field == "auc" || field == "cmax" || field == "clearance" || field == "halflife") { // when field is checkbox
                $("#mp-data-nav").show();
                if ($('#' + field + '-unchanged-checkbox').is(':checked'))
                    showDeleteBtn = true;
                fieldVal = $("#" + fieldM[field]).val();
            } else { // when field is text input
                $("#mp-data-nav").show();
                fieldVal = $("#" + fieldM[field]).val();
            }

            if (fieldVal !=null && fieldVal != "")
                $("#annotator-delete").show();
            else if (showDeleteBtn)
                $("#annotator-delete").show();
            else
                $("#annotator-delete").hide();
            focusOnDataField(targetField);
        }
        else {
            cleanFocusOnDataField(field);
            $("#"+dataid).hide();
        }
    }
}

// scroll current focus on window to specific highlight piece
function scrollToAnnotation(annotationId, fieldName, dataNum) {
    var divId = annotationId + "-" + fieldName + "-" + dataNum;
    if (document.getElementById(divId))
        document.getElementById(divId).scrollIntoView(true);
}

// unselect study type questions
function clearStudyTypeQuestions() {
    $('input[name=grouprandom]').prop('checked', false);
    $('input[name=parallelgroup]').prop('checked', false);
}

function focusOnDataField (fieldName) {
    $("button#nav-"+fieldName+"-btn").css("border","3px solid #336699");
}

function cleanFocusOnDataField(fieldName) {
    $("button#nav-"+fieldName+"-btn").css("border","");
}
<commit_msg>bug fixed - switching form and add data<commit_after>// MP CLAIM ================================================================================
// open claim editor
function claimEditorLoad() {
    currFormType = "claim";
    $("#mp-claim-form").show();
    $('#quote').show();
    $("#claim-label-data-editor").hide();
    $(".annotator-save").hide();
    $("#mp-data-nav").hide();
    $("#mp-data-form-evRelationship").hide();
    $("#mp-data-form-participants").hide();
    $("#mp-data-form-dose1").hide();
    $("#mp-data-form-dose2").hide();
    $("#mp-data-form-auc").hide();
    $("#mp-data-form-cmax").hide();
    $("#mp-data-form-clearance").hide();
    $("#mp-data-form-halflife").hide();
    $("#mp-data-form-studytype").hide();
}

// scroll to the claim text span
function viewClaim() {
    annotationId = $('#mp-editor-claim-list option:selected').val();
    scrollToAnnotation(annotationId, "claim", 0);
}

// edit claim
function editClaim() {
    annotationId = $('#mp-editor-claim-list option:selected').val();

    scrollToAnnotation(annotationId, "claim", 0);
    showEditor();
    claimEditorLoad();

    $.ajax({url: "http://" + config.annotator.host + "/annotatorstore/annotations/" + annotationId,
            data: {},
            method: 'GET',
            error : function(jqXHR, exception){
                console.log(exception);
            },
            success : function(annotation){
                // enable delete button
                $("#annotator-delete").show();

                // call AnnotatorJs editor for update
                app.annotations.update(annotation);
            }
           });
}

$("#Drug1").change(function (){selectDrug();});
$("#Drug2").change(function (){selectDrug();});

function selectDrug() {
    var drug1 = $("#Drug1").val();
    var drug2 = $("#Drug2").val();
    var quotestring = $("#quote").html();
    quotestring = quotestring.replace(drug2, ""+drug2+"");
    quotestring = quotestring.replace(drug1, ""+drug1+"");
    $("#quote").html(quotestring);
}

$("#Drug1").mousedown(function (){deselectDrug();});
$("#Drug2").mousedown(function (){deselectDrug();});

function deselectDrug() {
    var drug1 = $("#Drug1").val();
    var drug2 = $("#Drug2").val();
    var quotestring = $("#quote").html();
    quotestring = quotestring.replace(""+drug2+"", drug2);
    quotestring = quotestring.replace(""+drug1+"", drug1);
    $("#quote").html(quotestring);
}

// when relationship is inhibits or substrate of, show field enzyme
function showEnzyme() {

    if($("#relationship option:selected").text()=="inhibits"||$("#relationship option:selected").text()=="substrate of") {
        $("#enzyme")[0].selectedIndex = 0;
        $("#enzymesection1").show();
        $("#enzyme").show();

        $('input[name=precipitant]').prop('checked', false);
        $('input[type=radio][name=precipitant]').hide();
        $('.precipitantLabel').hide();
    }
    if($("#relationship option:selected").text()=="interact with") {
        $("#enzymesection1").hide();
        $("#enzyme").hide();
        $('input[type=radio][name=precipitant]').show();
        $('.precipitantLabel').show();
    }
}

// modify annotaiton id when user pick claim on mpadder's menu
// update annotation table if necessary
function claimSelectedInMenu(annotationId) {
    currAnnotationId = annotationId;
    annTableId = $('#mp-editor-claim-list option:selected').val();

    if (annotationId != annTableId){
        $("#mp-editor-claim-list option[value='" + annotationId + "']").attr("selected", "true");
        changeClaimInAnnoTable();
    }
}

// MP DATA & MATERIAL ========================================================================
// called when click annotation table cell when value of cell is empty
// (1) if no text selection avaliable, then pop up warning message then return
// to mp annotation table
// (2) otherwise, load annotation to editor, then shown specific data form
function addDataCellByEditor(field, dataNum, isNewData) {

    $("#button#drug1-dose-switch-btn").focus();

    var annotationId = $('#mp-editor-claim-list option:selected').val();
    console.log("addDataCellByEditor - id: " + annotationId + " | data: " + dataNum + " | field: " + field);

    $("#claim-label-data-editor").show();

    // return if no text selection
    if (!isTextSelected && field != "evRelationship" && field != "studytype") {
        warnSelectTextSpan(field);
    } else {
        // hide data fields navigation if editing evidence relationship
        if (field == "evRelationship" || field == "studytype") {
            $("#mp-data-nav").hide();
            $(".annotator-save").hide();
        } else {
            $(".annotator-save").show();
        }

        // cached editing data cell
        currAnnotationId = annotationId;
        currDataNum = dataNum;
        currFormType = field;

        showEditor();
        if (cachedOATarget.hasSelector != null)
            $("#" + field + "quote").html(cachedOATarget.hasSelector.exact);
        $("#annotator-delete").hide();

        // updating current MP annotation
        if (annotationId != null)
            currAnnotationId = annotationId;

        preDataForm(field);

        $.ajax({url: "http://" + config.annotator.host + "/annotatorstore/annotations/" + annotationId,
                data: {},
                method: 'GET',
                error : function(jqXHR, exception){
                    console.log(exception);
                },
                success : function(annotation){
                    // add data if not avaliable
                    if (annotation.argues.supportsBy.length == 0 || isNewData){

                        var data = {type : "mp:data", evRelationship: "", auc : {}, cmax : {}, clearance : {}, halflife : {}, supportsBy : {type : "mp:method", supportsBy : {type : "mp:material", participants : {}, drug1Dose : {}, drug2Dose : {}}}, grouprandom: "", parallelgroup: ""};
                        annotation.argues.supportsBy.push(data);
                    }

                    // call AnnotatorJs editor for update
                    app.annotations.update(annotation);

                }
               });
        }
}

// called when click annotation table cell when value of cell is not null
// (1) scroll to the annotation upon document
// (2) load annotation to editor, then shown specific data form
function editDataCellByEditor(field, dataNum) {

    showEditor();
    $("#claim-label-data-editor").show();
    $('#quote').hide();

    // hide data fields navigation if editing evidence relationship
    if (field == "evRelationship" || field == "studytype") {
        $("#mp-data-nav").hide();
        $(".annotator-save").hide();
    } else {
        $(".annotator-save").show();
    }

    var annotationId = $('#mp-editor-claim-list option:selected').val();
    console.log("editDataCellByEditor - id: " + annotationId + " | data: " + dataNum + " | field: " + field);

    // cached editing data cell
    currAnnotationId = annotationId;
    currDataNum = dataNum;
    currFormType = field;

    // scroll to the position of annotation
    scrollToAnnotation(annotationId, field, dataNum);

    $.ajax({url: "http://" + config.annotator.host + "/annotatorstore/annotations/" + annotationId,
            data: {},
            method: 'GET',
            error : function(jqXHR, exception){
                console.log(exception);
            },
            success : function(annotation){

                // updating current MP annotation
                if (annotationId != null)
                    currAnnotationId = annotationId;

                //switchDataForm(field, true);
                preDataForm(field, true);

                // show delete button
                data = annotation.argues.supportsBy[dataNum];
                material = data.supportsBy.supportsBy;
                if ((field == "participants" && material.participants.value != null) || (field == "dose1" && material.drug1Dose.value != null) || (field == "dose2" && material.drug2Dose.value != null) || ((field == "auc" || field == "cmax" || field == "clearance" || field == "halflife") && (data[field].value != null)))
                    $("#annotator-delete").show();

                // call AnnotatorJs editor for update
                app.annotations.update(annotation);
            }
           });
}

// warning dialog for opening data editor
function preDataForm(targetField, isNotNeedValid) {
    $("#mp-claim-form").hide();
    quoteF = $('#'+targetField+'quote').html();
    // unsaved warning box
    if (!warnUnsavedDialog())
        return;

    if (!isTextSelected && (targetField != "evRelationship" || targetField != "studytype") && quoteF == "" && !isNotNeedValid) {
        warnSelectTextSpan(targetField);
        return;
    }

    if (targetField == null)
        targetField = "participants";

    currFormType = targetField;

    focusOnDataField(targetField);
}

// switch data from from nav button
function switchDataForm(targetField, isNotNeedValid) {

    $("#mp-claim-form").hide();
    quoteF = $('#'+targetField+'quote').html();
    // unsaved warning box
    if (!warnUnsavedDialog())
        return;

    // pop up warn for selecting span when switch to new targetField dring editing mode
    if (!isTextSelected && (targetField != "evRelationship" || targetField != "studytype") && quoteF == "" && !isNotNeedValid) {
        warnSelectTextSpan(targetField);
        return;
    }

    if (targetField == null)
        targetField = "participants";

    currFormType = targetField;

    //redraw data currhighlight
    try {
        app.annotations.update(currAnnotation);
        // scroll to the position of annotation
        scrollToAnnotation(currAnnotation.id, currFormType, currDataNum);

        switchDataFormHelper(targetField);
        addDataCellByEditor(currFormType, 0); // call add data function when switched form
    } catch (err) {
        console.log(err);
    }
}

// when switch data field, show or hide delete button, nav buttons and data forms
function switchDataFormHelper(targetField) {

    // field actual div id mapping
    fieldM = {"evRelationship":"evRelationship", "participants":"participants", "dose1":"drug1Dose", "dose2":"drug2Dose", "auc":"auc", "cmax":"cmax", "clearance":"clearance", "halflife":"halflife", "studytype":"studytype"};

    var showDeleteBtn = false;

    for (var field in fieldM) {
        var dataid = "mp-data-form-"+field;
        if (field === targetField) {
            $("#"+dataid).show();  // show specific data form
            // inspect that is target form has value filled

            if (field == "evRelationship" || field =="studytype") { // when field is radio button
                fieldVal = $("input[name="+field+"]:checked").val();
            } else if (field == "auc" || field == "cmax" || field == "clearance" || field == "halflife") { // when field is checkbox
                $("#mp-data-nav").show();
                if ($('#' + field + '-unchanged-checkbox').is(':checked'))
                    showDeleteBtn = true;
                fieldVal = $("#" + fieldM[field]).val();
            } else { // when field is text input
                $("#mp-data-nav").show();
                fieldVal = $("#" + fieldM[field]).val();
            }

            if (fieldVal !=null && fieldVal != "")
                $("#annotator-delete").show();
            else if (showDeleteBtn)
                $("#annotator-delete").show();
            else
                $("#annotator-delete").hide();
            focusOnDataField(targetField);
        }
        else {
            cleanFocusOnDataField(field);
            $("#"+dataid).hide();
        }
    }
}

// scroll current focus on window to specific highlight piece
function scrollToAnnotation(annotationId, fieldName, dataNum) {
    var divId = annotationId + "-" + fieldName + "-" + dataNum;
    if (document.getElementById(divId))
        document.getElementById(divId).scrollIntoView(true);
}

// unselect study type questions
function clearStudyTypeQuestions() {
    $('input[name=grouprandom]').prop('checked', false);
    $('input[name=parallelgroup]').prop('checked', false);
}

function focusOnDataField (fieldName) {
    $("button#nav-"+fieldName+"-btn").css("border","3px solid #336699");
}

function cleanFocusOnDataField(fieldName) {
    $("button#nav-"+fieldName+"-btn").css("border","");
}
<|endoftext|>


<commit_before>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define([
    '../../scripts/grid',
    '../../scripts/misc',
    '../../scripts/mobilehacks',
    '../../scripts/strings',
  ], function(
    Grid,
    Misc,
    MobileHacks,
    Strings) {

  var $ = function(id) {
    return document.getElementById(id);
  };

  var GameManager = function(services) {
    this.services = services;
    this.services.entitySystem.addEntity(this);
    this.timeContainer = $("timeContainer");
    this.timeStyle = $("time").style;
    this.timeNode = Misc.createTextNode($("time"));
    this.overlay = $("overlay-inner");
    this.overlayLine1 = Misc.createTextNode($("overlay-line1"));
    this.overlayLine2 = Misc.createTextNode($("overlay-line2"));
    this.setState('waitForPlayers');
  };

  GameManager.prototype.showOverlay = function(show) {
    this.overlay.style.display = show ? "block" : "none";
  };

  GameManager.prototype.showTime = function(show) {
    this.timeContainer.style.display = show ? "block" : "none";
  };

  GameManager.prototype.updateTime = function() {
    var time = this.roundTimer | 0;
    if (time != this.oldRoundTimer) {
      this.oldRoundTimer = time;
      var mins = time / 60 | 0;
      var seconds = time % 60;
      this.timeNode.nodeValue = Strings.padLeft(mins, 2, '0') + ":" + Strings.padLeft(seconds, 2, '0');
    }
    var globals = this.services.globals;
    var color = time > 15 ? 'white' : ((globals.frameCount & 8) ? 'white' : 'red');
    if (this.oldTimeColor != color) {
      this.oldTimeColor = color;
      this.timeStyle.color = color;
    }
  };

  GameManager.prototype.reset = function() {
    MobileHacks.fixHeightHack();
    var services = this.services;
    var levelManager = services.levelManager;
    var playerManager = services.playerManager;
    var globals = services.globals;
    var canvas = services.canvas;

    var numPlayers = playerManager.getNumPlayersConnected();

    if (!globals.forceScale) {
      // Compute a good scale for the number of players.
      globals.scale = 1;
      for (var ii = 8; ii > 0; --ii) {
        var mapSize = levelManager.computeMapSize(canvas.width, canvas.height, ii);
        var numPlayersThatFitOnMapBy3 = ((mapSize.numColumns + 2) / 3 | 0) * ((mapSize.numRows + 2) / 3 | 0);
        var numPlayersThatFitOnMapBy2 = ((mapSize.numColumns + 1) / 2 | 0) * ((mapSize.numRows + 1) / 2 | 0);
        if (numPlayersThatFitOnMapBy2 >= numPlayers) {
          globals.scale = ii;
          break;
        }
      }
    }

    levelManager.makeLevel(canvas.width, canvas.height);
    var off = {};
    levelManager.getDrawOffset(off);
    if (globals.grid) {
      if (!services.grid) {
        services.grid = new Grid({
          container: $("grid"),
          columns: 1,
          rows: 1,
        });
      }
      services.grid.setDimensions(levelManager.tilesAcross, levelManager.tilesDown);
      var s = $("grid").style;
      s.display = "block";
      s.left = off.x + "px";
      s.top = off.y + "px";
      services.gridTable = [];
      services.grid.forEach(function(element, x, y) {
        if (services.gridTable.length < y + 1) {
          services.gridTable.push([]);
        }
        var pre = element.firstChild;
        var txt;
        if (pre) {
          txt = pre.firstChild;
        } else {
          pre = document.createElement("pre");
          txt = document.createTextNode("");
          pre.appendChild(txt);
          element.appendChild(pre);
        }
        txt.nodeValue = "" + x + "," + y;
        services.gridTable[y].push(txt);
      });
    }

    // Adjust clock size.
    var tileHeight = 16;
    var topMax = 80;
    var topMin = 16;
    var topMaxOffset = 10;
    var topSpace = Math.min(topMax, Math.max(topMin, off.y + tileHeight * globals.scale));

    var topOffset = Math.floor((topSpace - topMin) * topMaxOffset / (topMax - topMin));
    var topSize = Math.max(topSpace - topOffset - 8, tileHeight - 8);
    this.timeContainer.style.top  = topOffset + "px";
    this.timeStyle.fontSize = topSize + "px";

    this.setAllPlayersToState('waiting');
    this.setState('waitForPlayers');
  };

  GameManager.prototype.setAllPlayersToState = function(state) {
    this.services.playerManager.forEachPlayerPlaying(function(player) {
      player.setState(state);
    });
  };

  GameManager.prototype.setState = function(state) {
    this.state = state;
    var init = this["init_" + state];
    if (init) {
      init.call(this);
    }
    this.process = this["state_" + state];
  };

  GameManager.prototype.waitForStartUpdate = function() {
    var globals = this.services.globals;
    var numPlayers = this.services.playerManager.getNumPlayersConnected();

    var timeStr = Strings.padLeft((this.timer | 0), 2, '0');

    this.overlayLine1.nodeValue = "Start In: " + ((numPlayers < 2 || (globals.frameCount & 16)) ? timeStr : '');
    this.overlayLine2.nodeValue = "Players: " + numPlayers + ((globals.frameCount & 16) && numPlayers < 2 ? ' Need 2+' : '');
  }

  GameManager.prototype.init_waitForPlayers = function() {
    this.showOverlay(true);
    this.showTime(false);
    this.overlay.style.textAlign = "";

    var globals = this.services.globals;
    this.timer = globals.waitForPlayersDuration;
    this.waitForStartUpdate();
    if (this.services.playerManager.getNumPlayersConnected() < 2) {
      this.services.server.broadcastCmd('waitForMorePlayers');
    }
  };

  GameManager.prototype.state_waitForPlayers = function() {
    this.waitForStartUpdate();
    if (this.services.playerManager.getNumPlayersConnected() > 1) {
      this.setState('waitForStart');
    }
  };

  GameManager.prototype.init_waitForStart = function() {
  };

  GameManager.prototype.state_waitForStart = function() {
    this.waitForStartUpdate();
    var globals = this.services.globals;
    var oldTimer = this.timer | 0;
    this.timer -= globals.elapsedTime;

    if (this.timer <= 0) {
      this.setState('start');
      return;
    }

    // Wait for at least 2 players.
    if (this.services.playerManager.getNumPlayersConnected() < 2) {
      this.setState('waitForPlayers');
      return;
    }

    var secondsLeft = this.timer | 0;
    if (oldTimer != secondsLeft) {
      this.services.server.broadcastCmd('waitForStart', {
        waitTime: secondsLeft,
      });
    }
  };

  GameManager.prototype.init_start = function() {
    var globals = this.services.globals;
    this.roundTimer = globals.roundDuration;
    this.showTime(true);
    this.updateTime();
    this.services.playerManager.reset();
    this.overlay.style.textAlign = "center";
    this.overlayLine1.nodeValue = "Ready?";
    this.overlayLine2.nodeValue = "";
    this.timer = globals.waitForStartDuration;
  };

  GameManager.prototype.state_start = function() {
    var globals = this.services.globals;
    var old = this.timer | 0;
    this.timer -= globals.elapsedTime;
    if (old != (this.timer | 0) && old == globals.waitForGo) {
      this.overlayLine1.nodeValue = "GO!";
    }
    if (this.timer <= 0) {
      this.setState('play');
    }
  };

  GameManager.prototype.init_play = function() {
    this.showOverlay(false);
    this.setAllPlayersToState('idle');
  };

  GameManager.prototype.state_play = function() {
    var globals = this.services.globals;
    this.roundTimer -= globals.elapsedTime;
    var numPlayersAlive = this.services.playerManager.getNumPlayersAlive();
    if (this.roundTimer <= 0 || numPlayersAlive < 2) {
      this.setState('end');
      return;
    }
    this.updateTime();
  };

  GameManager.prototype.init_end = function() {
    var globals = this.services.globals;
    this.services.playerManager.forEachPlayerPlaying(function(player) {
      ++player.roundsPlayed;
      if (player.alive) {
        player.setState('end');
        this.winner = player;
      }
    }.bind(this));
    this.timer = globals.waitForEnd;
  };

  GameManager.prototype.state_end = function() {
    var globals = this.services.globals;
    this.timer -= globals.elapsedTime;
    if (this.timer <= 0) {
      this.setState('showWinners');
    }
  };

  GameManager.prototype.init_showWinners = function() {
    var globals = this.services.globals;
    this.showOverlay(true);
    this.overlay.style.textAlign = "center";
    var numPlayersAlive = this.services.playerManager.getNumPlayersAlive();
    this.overlayLine2.nodeValue = "";
    if (numPlayersAlive <= 0) {
      this.overlayLine1.nodeValue = "No Winners";
    } else if (numPlayersAlive > 1) {
      this.overlayLine1.nodeValue = "Draw";
      this.services.playerManager.forEachPlayerPlaying(function(player) {
        if (player.alive) {
          player.sendTied();
        }
      });
    } else {
      ++this.winner.wins;
      this.overlayLine1.nodeValue = "Winner";
      this.overlayLine2.nodeValue = this.winner.playerName + " " + this.winner.wins + "/" + this.winner.roundsPlayed;
      this.winner.sendWinner();
    }
    this.timer = globals.waitForWinnerDuration;
  };

  GameManager.prototype.state_showWinners = function() {
    var globals = this.services.globals;
    this.timer -= globals.elapsedTime;
    if (this.timer <= 0) {
      this.setState('waitForPlayers');
    }
  };

  return GameManager;
});

<commit_msg>make grid match tile size<commit_after>/*
 * Copyright 2014, Gregg Tavares.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Gregg Tavares. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
"use strict";

define([
    '../../scripts/grid',
    '../../scripts/misc',
    '../../scripts/mobilehacks',
    '../../scripts/strings',
  ], function(
    Grid,
    Misc,
    MobileHacks,
    Strings) {

  var $ = function(id) {
    return document.getElementById(id);
  };

  var GameManager = function(services) {
    this.services = services;
    this.services.entitySystem.addEntity(this);
    this.timeContainer = $("timeContainer");
    this.timeStyle = $("time").style;
    this.timeNode = Misc.createTextNode($("time"));
    this.overlay = $("overlay-inner");
    this.overlayLine1 = Misc.createTextNode($("overlay-line1"));
    this.overlayLine2 = Misc.createTextNode($("overlay-line2"));
    this.setState('waitForPlayers');
  };

  GameManager.prototype.showOverlay = function(show) {
    this.overlay.style.display = show ? "block" : "none";
  };

  GameManager.prototype.showTime = function(show) {
    this.timeContainer.style.display = show ? "block" : "none";
  };

  GameManager.prototype.updateTime = function() {
    var time = this.roundTimer | 0;
    if (time != this.oldRoundTimer) {
      this.oldRoundTimer = time;
      var mins = time / 60 | 0;
      var seconds = time % 60;
      this.timeNode.nodeValue = Strings.padLeft(mins, 2, '0') + ":" + Strings.padLeft(seconds, 2, '0');
    }
    var globals = this.services.globals;
    var color = time > 15 ? 'white' : ((globals.frameCount & 8) ? 'white' : 'red');
    if (this.oldTimeColor != color) {
      this.oldTimeColor = color;
      this.timeStyle.color = color;
    }
  };

  GameManager.prototype.reset = function() {
    MobileHacks.fixHeightHack();
    var services = this.services;
    var levelManager = services.levelManager;
    var playerManager = services.playerManager;
    var globals = services.globals;
    var canvas = services.canvas;

    var tileWidth  = 16;
    var tileHeight = 16;

    var numPlayers = playerManager.getNumPlayersConnected();

    if (!globals.forceScale) {
      // Compute a good scale for the number of players.
      globals.scale = 1;
      for (var ii = 8; ii > 0; --ii) {
        var mapSize = levelManager.computeMapSize(canvas.width, canvas.height, ii);
        var numPlayersThatFitOnMapBy3 = ((mapSize.numColumns + 2) / 3 | 0) * ((mapSize.numRows + 2) / 3 | 0);
        var numPlayersThatFitOnMapBy2 = ((mapSize.numColumns + 1) / 2 | 0) * ((mapSize.numRows + 1) / 2 | 0);
        if (numPlayersThatFitOnMapBy2 >= numPlayers) {
          globals.scale = ii;
          break;
        }
      }
    }

    levelManager.makeLevel(canvas.width, canvas.height);
    var off = {};
    levelManager.getDrawOffset(off);
    if (globals.grid) {
      if (!services.grid) {
        services.grid = new Grid({
          container: $("grid"),
          columns: 1,
          rows: 1,
        });
      }
      services.grid.setDimensions(levelManager.tilesAcross, levelManager.tilesDown);
      var s = $("grid").style;
      s.display = "block";
      s.left = off.x + "px";
      s.top = off.y + "px";
      services.gridTable = [];
      services.grid.forEach(function(element, x, y) {
        if (services.gridTable.length < y + 1) {
          services.gridTable.push([]);
        }
        var pre = element.firstChild;
        var txt;
        if (pre) {
          txt = pre.firstChild;
        } else {
          pre = document.createElement("pre");
          txt = document.createTextNode("");
          pre.appendChild(txt);
          element.appendChild(pre);
        }
        txt.nodeValue = "" + x + "," + y;
        services.gridTable[y].push(txt);
      });
      var rule = Misc.findCSSStyleRule("#grid td");
      if (rule) {
        rule.style.width  = tileWidth * globals.scale + "px";
        rule.style.height = tileHeight * globals.scale + "px";
      }
    }

    // Adjust clock size.
    var topMax = 80;
    var topMin = 16;
    var topMaxOffset = 10;
    var topSpace = Math.min(topMax, Math.max(topMin, off.y + tileHeight * globals.scale));

    var topOffset = Math.floor((topSpace - topMin) * topMaxOffset / (topMax - topMin));
    var topSize = Math.max(topSpace - topOffset - 8, tileHeight - 8);
    this.timeContainer.style.top  = topOffset + "px";
    this.timeStyle.fontSize = topSize + "px";

    this.setAllPlayersToState('waiting');
    this.setState('waitForPlayers');
  };

  GameManager.prototype.setAllPlayersToState = function(state) {
    this.services.playerManager.forEachPlayerPlaying(function(player) {
      player.setState(state);
    });
  };

  GameManager.prototype.setState = function(state) {
    this.state = state;
    var init = this["init_" + state];
    if (init) {
      init.call(this);
    }
    this.process = this["state_" + state];
  };

  GameManager.prototype.waitForStartUpdate = function() {
    var globals = this.services.globals;
    var numPlayers = this.services.playerManager.getNumPlayersConnected();

    var timeStr = Strings.padLeft((this.timer | 0), 2, '0');

    this.overlayLine1.nodeValue = "Start In: " + ((numPlayers < 2 || (globals.frameCount & 16)) ? timeStr : '');
    this.overlayLine2.nodeValue = "Players: " + numPlayers + ((globals.frameCount & 16) && numPlayers < 2 ? ' Need 2+' : '');
  }

  GameManager.prototype.init_waitForPlayers = function() {
    this.showOverlay(true);
    this.showTime(false);
    this.overlay.style.textAlign = "";

    var globals = this.services.globals;
    this.timer = globals.waitForPlayersDuration;
    this.waitForStartUpdate();
    if (this.services.playerManager.getNumPlayersConnected() < 2) {
      this.services.server.broadcastCmd('waitForMorePlayers');
    }
  };

  GameManager.prototype.state_waitForPlayers = function() {
    this.waitForStartUpdate();
    if (this.services.playerManager.getNumPlayersConnected() > 1) {
      this.setState('waitForStart');
    }
  };

  GameManager.prototype.init_waitForStart = function() {
  };

  GameManager.prototype.state_waitForStart = function() {
    this.waitForStartUpdate();
    var globals = this.services.globals;
    var oldTimer = this.timer | 0;
    this.timer -= globals.elapsedTime;

    if (this.timer <= 0) {
      this.setState('start');
      return;
    }

    // Wait for at least 2 players.
    if (this.services.playerManager.getNumPlayersConnected() < 2) {
      this.setState('waitForPlayers');
      return;
    }

    var secondsLeft = this.timer | 0;
    if (oldTimer != secondsLeft) {
      this.services.server.broadcastCmd('waitForStart', {
        waitTime: secondsLeft,
      });
    }
  };

  GameManager.prototype.init_start = function() {
    var globals = this.services.globals;
    this.roundTimer = globals.roundDuration;
    this.showTime(true);
    this.updateTime();
    this.services.playerManager.reset();
    this.overlay.style.textAlign = "center";
    this.overlayLine1.nodeValue = "Ready?";
    this.overlayLine2.nodeValue = "";
    this.timer = globals.waitForStartDuration;
  };

  GameManager.prototype.state_start = function() {
    var globals = this.services.globals;
    var old = this.timer | 0;
    this.timer -= globals.elapsedTime;
    if (old != (this.timer | 0) && old == globals.waitForGo) {
      this.overlayLine1.nodeValue = "GO!";
    }
    if (this.timer <= 0) {
      this.setState('play');
    }
  };

  GameManager.prototype.init_play = function() {
    this.showOverlay(false);
    this.setAllPlayersToState('idle');
  };

  GameManager.prototype.state_play = function() {
    var globals = this.services.globals;
    this.roundTimer -= globals.elapsedTime;
    var numPlayersAlive = this.services.playerManager.getNumPlayersAlive();
    if (this.roundTimer <= 0 || numPlayersAlive < 2) {
      this.setState('end');
      return;
    }
    this.updateTime();
  };

  GameManager.prototype.init_end = function() {
    var globals = this.services.globals;
    this.services.playerManager.forEachPlayerPlaying(function(player) {
      ++player.roundsPlayed;
      if (player.alive) {
        player.setState('end');
        this.winner = player;
      }
    }.bind(this));
    this.timer = globals.waitForEnd;
  };

  GameManager.prototype.state_end = function() {
    var globals = this.services.globals;
    this.timer -= globals.elapsedTime;
    if (this.timer <= 0) {
      this.setState('showWinners');
    }
  };

  GameManager.prototype.init_showWinners = function() {
    var globals = this.services.globals;
    this.showOverlay(true);
    this.overlay.style.textAlign = "center";
    var numPlayersAlive = this.services.playerManager.getNumPlayersAlive();
    this.overlayLine2.nodeValue = "";
    if (numPlayersAlive <= 0) {
      this.overlayLine1.nodeValue = "No Winners";
    } else if (numPlayersAlive > 1) {
      this.overlayLine1.nodeValue = "Draw";
      this.services.playerManager.forEachPlayerPlaying(function(player) {
        if (player.alive) {
          player.sendTied();
        }
      });
    } else {
      ++this.winner.wins;
      this.overlayLine1.nodeValue = "Winner";
      this.overlayLine2.nodeValue = this.winner.playerName + " " + this.winner.wins + "/" + this.winner.roundsPlayed;
      this.winner.sendWinner();
    }
    this.timer = globals.waitForWinnerDuration;
  };

  GameManager.prototype.state_showWinners = function() {
    var globals = this.services.globals;
    this.timer -= globals.elapsedTime;
    if (this.timer <= 0) {
      this.setState('waitForPlayers');
    }
  };

  return GameManager;
});

<|endoftext|>


<commit_before>/**
 * Created by andreafspeziale on 16/04/16.
 */
lisk.factory('LiskServices', ['$http', '$q', function($http, $q) {
    // your ip
    var ip = 'http://194.116.72.47:8000';
    // will all return promise objects
    return {
        getBalance: function(address) {
            return $http.get(ip+'/api/accounts/getBalance?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getBalance lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getBalance lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getDelegateStats: function() {
            return $http.get(ip+'/api/delegates?getActive')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getDelegateStats lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getDelegateStats lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getVotesOfAccount: function(address) {
            return $http.get(ip+'/api/accounts/delegates/?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getVotesOfAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getVotesOfAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getVoters: function(public_key) {
            return $http.get(ip+'/api/delegates/voters?publicKey='+public_key)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getVoters lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getVoters lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getPublicKey: function(address) {
            return $http.get(ip+'/api/accounts/getPublicKey?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getPublicKey lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getPublicKey lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getAccount: function(address) {
            return $http.get(ip+'/api/accounts?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getBlockChainHeight: function() {
            return $http.get(ip+'/api/blocks/getHeight')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getSynchronisationStatus: function() {
            return $http.get(ip+'/api/loader/status/sync')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getDelegates: function(offset) {
            return $http.get(ip+'/api/delegates?offset='+offset)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getDelegates lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getDelegates lisk service promise rejected');
                    return $q.reject(response.data);
                });
        }
    }
}]);
<commit_msg>updating nodes<commit_after>/**
 * Created by andreafspeziale on 16/04/16.
 */
lisk.factory('LiskServices', ['$http', '$q', function($http, $q) {
    // your ip
    var ip = 'http://194.116.72.38:8000';
    // will all return promise objects
    return {
        getBalance: function(address) {
            return $http.get(ip+'/api/accounts/getBalance?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getBalance lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getBalance lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getDelegateStats: function() {
            return $http.get(ip+'/api/delegates?getActive')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getDelegateStats lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getDelegateStats lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getVotesOfAccount: function(address) {
            return $http.get(ip+'/api/accounts/delegates/?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getVotesOfAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getVotesOfAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getVoters: function(public_key) {
            return $http.get(ip+'/api/delegates/voters?publicKey='+public_key)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getVoters lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getVoters lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getPublicKey: function(address) {
            return $http.get(ip+'/api/accounts/getPublicKey?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getPublicKey lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getPublicKey lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getAccount: function(address) {
            return $http.get(ip+'/api/accounts?address='+address)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getBlockChainHeight: function() {
            return $http.get(ip+'/api/blocks/getHeight')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getSynchronisationStatus: function() {
            return $http.get(ip+'/api/loader/status/sync')
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getAccount lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getAccount lisk service promise rejected');
                    return $q.reject(response.data);
                });
        },
        getDelegates: function(offset) {
            return $http.get(ip+'/api/delegates?offset='+offset)
                .then(function(response) {
                    if (typeof response.data === 'object') {
                        return response.data;
                    } else {
                        console.log('getDelegates lisk service invalid response from API');
                        return $q.reject(response.data);
                    }

                }, function(response) {
                    console.log('getDelegates lisk service promise rejected');
                    return $q.reject(response.data);
                });
        }
    }
}]);
<|endoftext|>


<commit_before>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Data Window control")
description("This will return the data window control")
base_component_id("data_window_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    350,
            type:       "Number"
        }
        ,
        {
            id:     "limit",
            name:   "Limit",
            type:   "Number",
            default_expression: "(typeof $RETURNED_ROWS_LIMIT !== 'undefined')?eval('$RETURNED_ROWS_LIMIT'):100",
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    false,
            hidden:     true
        }
        ,
        {
            id:         "setData",
            snippet:    `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`,
            name:       "setData",
            type:       "Action"
        }
        ,
        {
            id:         "resetColumns",
            snippet:    `resetColumns()`,
            name:       "resetColumns",
            type:       "Action"
        }
        ,
        {
            id:     "addColumn",
            name:   "addColumn",
            type:   "Action"
        }
        ,
        {
            id:     "sql",
            name:   "SQL",
            type:   "String",
            default: "SELECT * FROM pg_catalog.pg_tables;"
        }
        ,
        {
            id:      "user",
            name:    "USER",
            type:    "String",
            default_expression: "(typeof $POSTGRES_USER !== 'undefined')?eval('$POSTGRES_USER'):'postgres'"
        }
        ,
        {
            id:     "password",
            name:   "Password",
            type:   "String",
            default_expression: "(typeof $POSTGRES_PASSWORD !== 'undefined')?eval('$POSTGRES_PASSWORD'):'password'",
        }
        ,
        {
            id:     "database",
            name:   "Database",
            type:   "String",
            default_expression: "(typeof $POSTGRES_DATABASE !== 'undefined')?eval('$POSTGRES_DATABASE'):'postgres'",
        }
        ,
        {
            id:     "port",
            name:   "Port",
            type:   "Number",
            default_expression: "(typeof $POSTGRES_PORT !== 'undefined')?eval('$POSTGRES_PORT'):5432",
        }
        ,
        {
            id:     "host",
            name:   "Host",
            type:   "String",
            default_expression: "(typeof $POSTGRES_HOST !== 'undefined')?$POSTGRES_HOST:'localhost'",
        }

        ,
        {
            id:     "result",
            name:   "result",
            type:   "Array",
            default:    []
        }
        ,
        {
            id:         "executeSql",
            pre_snippet: `await `,
            snippet:    `executeSql()`,
            name:       "executeSql",
            type:       "Action",
            help:       `
Help text for
                            executeSql function

The SQL is store in the "sql" property

`
        }
        ]
)//properties
logo_url("/driver_icons/data_window.png")
*/

    Vue.component("data_window_control",{
      props: ["meta","name","args","refresh","design_mode"]
      ,
      template:
`

            SQL Builder

                     SQL:
                        {{args.sql}}

`
      ,

      data: function() {
       return {
         selected_index:     null
         ,
         columnDefinitions: [ ]
         ,
         data:              [ ]
         ,
         table:              null
       }
     }
     ,

     watch: {
       // This would be called anytime the value of the input changes
       refresh: function(newValue, oldValue) {
           //console.log("refresh: " + this.args.text)
           if (isValidObject(this.args)) {
           }
       }
     }
     ,

     mounted: async function() {
         registerComponent(this)

         if (isValidObject(this.args)) {
         }

         if (this.design_mode == false) {
             this.table = new Tabulator(this.$refs.exampletable, {
                    width:                    this.args.width
                    ,
                    height:                    this.args.height
                    ,
                    data:                      this.data
                    ,
                	layout:                    "fitColumns"
                    ,
                	responsiveLayout:          "hide"
                    ,
                	tooltips:                   true
                    ,
                	addRowPos:                 "top"
                    ,
                	history:                    true
                    ,
                	pagination:                "local"
                    ,
                	paginationSize:             7
                    ,
                	movableColumns:             true
                    ,
                	resizableRows:              true
                    ,

                	initialSort:                [
                                            	]
                    ,

                	columns:                    this.columnDefinitions
                });
         }

         if (!this.design_mode) {

             var results = await this.executeSql()
             //alert(JSON.stringify(results,null,2))
             await this.setData(results.value)
         }

      }
      ,

      methods: {

            changedFn: function() {
                if (isValidObject(this.args)) {
                }
            }

            ,
            resetColumns: async function(data) {
                this.table.setColumns([])
            }
            ,
            addColumn: async function(colData) {
                this.table.addColumn(colData, true, "name");
            }
            ,

            runEventHandler: function() {
                this.$emit('send', {
                                                type:               "subcomponent_event",
                                                control_name:        this.args.name,
                                                sub_type:           "changed",
                                                code:                this.args.changed_event
                                            })
            }
            ,
            setData: async function(data) {
                this.data = data
                this.table.setData(data)

                var keysOfData = new Object()
                if ((this.columnDefinitions == null)  || (this.columnDefinitions.length == 0)) {
                    for (var rr = 0 ; rr < data.length; rr ++) {
                        var dfg = Object.keys(data[rr])
                        for (var qq = 0 ; qq < dfg.length; qq ++) {
                            keysOfData[dfg[qq]] = true
                        }
                    }
                }

                var dfg2 = Object.keys(keysOfData)
                for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) {
                    this.addColumn({title:dfg2[qq2], field:dfg2[qq2]})
                }

            }
            ,

            executeSql: async function() {
                if (!this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "postgres_server",
                                            method_name: "postgres_sql"  }
                                            ,{
                                                sql:             this.args.sql,
                                                user:            this.args.user,
                                                password:        this.args.password,
                                                database:        this.args.database,
                                                host:            this.args.host,
                                                port:            this.args.port,
                                                limit:           this.args.limit
                                             })

                   //alert("executeSql: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   if (result.value) {
                        this.args.result = result.value.result

                        return result.value
                   }

               }
                this.args.result = []
                this.changedFn()
                return {}
            }

        }

    })
}
<commit_msg>Added list of tables to the table builder<commit_after>function(args) {
/*
is_app(true)
control_type("VB")
display_name("Data Window control")
description("This will return the data window control")
base_component_id("data_window_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "text",
            name:   "Text",
            type:   "String"
        }
        ,
        {
            id:         "width",
            name:       "Width",
            default:    350,
            type:       "Number"
        }
        ,
        {
            id:     "limit",
            name:   "Limit",
            type:   "Number",
            default_expression: "(typeof $RETURNED_ROWS_LIMIT !== 'undefined')?eval('$RETURNED_ROWS_LIMIT'):100",
        }
        ,
        {
            id:         "height",
            name:       "Height",
            default:    300,
            type:       "Number"
        }
        ,
        {
            id:     "background_color",
            name:   "Background color",
            type:   "String"
        }
        ,

        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:     "changed_event",
            name:   "Changed event",
            type:   "Event"
        }
        ,
        {
            id:         "is_container",
            name:       "Is Container?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,
        {
            id:         "hide_children",
            name:       "Hide Children?",
            type:       "Boolean",
            default:    false,
            hidden:     true
        }
        ,
        {
            id:         "setData",
            snippet:    `setData([{a: 1, b: "c"},{a: 2, b: "d"}])`,
            name:       "setData",
            type:       "Action"
        }
        ,
        {
            id:         "resetColumns",
            snippet:    `resetColumns()`,
            name:       "resetColumns",
            type:       "Action"
        }
        ,
        {
            id:     "addColumn",
            name:   "addColumn",
            type:   "Action"
        }
        ,
        {
            id:     "sql",
            name:   "SQL",
            type:   "String",
            default: "SELECT * FROM pg_catalog.pg_tables;"
        }
        ,
        {
            id:      "user",
            name:    "USER",
            type:    "String",
            default_expression: "(typeof $POSTGRES_USER !== 'undefined')?eval('$POSTGRES_USER'):'postgres'"
        }
        ,
        {
            id:     "password",
            name:   "Password",
            type:   "String",
            default_expression: "(typeof $POSTGRES_PASSWORD !== 'undefined')?eval('$POSTGRES_PASSWORD'):'password'",
        }
        ,
        {
            id:     "database",
            name:   "Database",
            type:   "String",
            default_expression: "(typeof $POSTGRES_DATABASE !== 'undefined')?eval('$POSTGRES_DATABASE'):'postgres'",
        }
        ,
        {
            id:     "port",
            name:   "Port",
            type:   "Number",
            default_expression: "(typeof $POSTGRES_PORT !== 'undefined')?eval('$POSTGRES_PORT'):5432",
        }
        ,
        {
            id:     "host",
            name:   "Host",
            type:   "String",
            default_expression: "(typeof $POSTGRES_HOST !== 'undefined')?$POSTGRES_HOST:'localhost'",
        }

        ,
        {
            id:     "result",
            name:   "result",
            type:   "Array",
            default:    []
        }
        ,
        {
            id:         "executeSql",
            pre_snippet: `await `,
            snippet:    `executeSql()`,
            name:       "executeSql",
            type:       "Action",
            help:       `
Help text for
                            executeSql function

The SQL is store in the "sql" property

`
        }
        ]
)//properties
logo_url("/driver_icons/data_window.png")
*/

    Vue.component("data_window_control",{
      props: ["meta","name","args","refresh","design_mode"]
      ,
      template:
`

            SQL Builder

                     SQL:
                        {{args.sql}}

`
      ,

      data: function() {
       return {
         selected_index:     null
         ,
         columnDefinitions: [ ]
         ,
         data:              [ ]
         ,
         table:              null
       }
     }
     ,

     watch: {
       // This would be called anytime the value of the input changes
       refresh: function(newValue, oldValue) {
           //console.log("refresh: " + this.args.text)
           if (isValidObject(this.args)) {
           }
       }
     }
     ,

     mounted: async function() {
         registerComponent(this)

         if (isValidObject(this.args)) {
         }

         if (this.design_mode == false) {
             this.table = new Tabulator(this.$refs.exampletable, {
                    width:                    this.args.width
                    ,
                    height:                    this.args.height
                    ,
                    tables:                    []
                    ,
                    data:                      this.data
                    ,
                	layout:                    "fitColumns"
                    ,
                	responsiveLayout:          "hide"
                    ,
                	tooltips:                   true
                    ,
                	addRowPos:                 "top"
                    ,
                	history:                    true
                    ,
                	pagination:                "local"
                    ,
                	paginationSize:             7
                    ,
                	movableColumns:             true
                    ,
                	resizableRows:              true
                    ,

                	initialSort:                [
                                            	]
                    ,

                	columns:                    this.columnDefinitions
                });
         }

         if (!this.design_mode) {

             var results = await this.executeSql()
             //alert(JSON.stringify(results,null,2))
             await this.setData(results.value)
         }

      }
      ,

      methods: {

            changedFn: function() {
                if (isValidObject(this.args)) {
                }
            }

            ,
            resetColumns: async function(data) {
                this.table.setColumns([])
            }
            ,
            addColumn: async function(colData) {
                this.table.addColumn(colData, true, "name");
            }
            ,

            runEventHandler: function() {
                this.$emit('send', {
                                                type:               "subcomponent_event",
                                                control_name:        this.args.name,
                                                sub_type:           "changed",
                                                code:                this.args.changed_event
                                            })
            }
            ,
            setData: async function(data) {
                this.data = data
                this.table.setData(data)

                var keysOfData = new Object()
                if ((this.columnDefinitions == null)  || (this.columnDefinitions.length == 0)) {
                    for (var rr = 0 ; rr < data.length; rr ++) {
                        var dfg = Object.keys(data[rr])
                        for (var qq = 0 ; qq < dfg.length; qq ++) {
                            keysOfData[dfg[qq]] = true
                        }
                    }
                }

                var dfg2 = Object.keys(keysOfData)
                for (var qq2 = 0 ; qq2 < dfg2.length; qq2 ++) {
                    this.addColumn({title:dfg2[qq2], field:dfg2[qq2]})
                }

            }
            ,

            executeSql: async function() {
                if (!this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "postgres_server",
                                            method_name: "postgres_sql"  }
                                            ,{
                                                sql:             this.args.sql,
                                                user:            this.args.user,
                                                password:        this.args.password,
                                                database:        this.args.database,
                                                host:            this.args.host,
                                                port:            this.args.port,
                                                limit:           this.args.limit
                                             })

                   //alert("executeSql: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   if (result.value) {
                        this.args.result = result.value.result

                        return result.value
                   }

               }
                this.args.result = []
                this.changedFn()
                return {}
            }

        }

    })
}
<|endoftext|>