<commit_before>"use strict";
/*global describe, it, assert, beforeEach*/

describe("fs_ms", function () {

    if ("wscript" !== gpf.host()) {
        return; // Skip
    }

    var
        gpfI = gpf.interfaces,
        iWScriptFs;

    beforeEach(function () {
        iWScriptFs = new gpf.fs.WScriptFileStorage();
    });

    describe("gpf.fs.WScriptFileStorage", function () {

        it("implements IFileStorage", function () {
            assert(gpfI.isImplementedBy(iWScriptFs, gpfI.IFileStorage));
        });

        it("saves binary files", function (done) {
            iWScriptFs.writeAsBinaryStream("tmp\\test\\fs_ms.bin",
                function (event) {
                    assert(gpf.events.EVENT_READY === event.type);
                    var wStream = event.get("stream");
                    wStream.write([0, 34, 75, 0, 128, 255], function (event) {
                        assert(gpf.events.EVENT_READY === event.type);
                        iWScriptFs.close(wStream, function () {}); // ignore
                        done();
                    });
                });
        });

        it("reads binary files", function (done) {
            iWScriptFs.readAsBinaryStream("test\\data\\file.bin",
                function (event) {
                    assert(gpf.events.EVENT_READY === event.type);
                    var rStream = event.get("stream");
                    rStream.read(1, function (event) {
                        assert(gpf.events.EVENT_DATA === event.type);
                        var buffer = event.get("buffer");
                        assert(1 === buffer.length);
                        assert(0 === buffer[0]);
                        iWScriptFs.close(rStream);
                        done();
                    });
                });
        });
    });

});<commit_msg>forgot write<commit_after>"use strict";
/*global describe, it, assert, beforeEach*/

describe("fs_ms", function () {

    if ("wscript" !== gpf.host()) {
        return; // Skip
    }

    var
        gpfI = gpf.interfaces,
        iWScriptFs;

    beforeEach(function () {
        iWScriptFs = new gpf.fs.WScriptFileStorage();
    });

    describe("gpf.fs.WScriptFileStorage", function () {

        it("implements IFileStorage", function () {
            assert(gpfI.isImplementedBy(iWScriptFs, gpfI.IFileStorage));
        });

        it("saves binary files", function (done) {
            iWScriptFs.writeAsBinaryStream("tmp\\test\\fs_ms.bin",
                function (event) {
                    assert(gpf.events.EVENT_READY === event.type);
                    var wStream = event.get("stream");
                    wStream.write([0, 34, 75, 0, 128, 255], function (event) {
                        assert(gpf.events.EVENT_READY === event.type);
                        iWScriptFs.close(wStream, function () {}); // ignore
                        done();
                    });
                });
        });

        it("reads binary files", function (done) {
            iWScriptFs.readAsBinaryStream("test\\data\\file.bin",
                function (event) {
                    assert(gpf.events.EVENT_READY === event.type);
                    var rStream = event.get("stream");
                    rStream.read(1, function (event) {
                        assert(gpf.events.EVENT_DATA === event.type);
                        var buffer = event.get("buffer");
                        assert(1 === buffer.length);
                        assert(0 === buffer[0]);
                        iWScriptFs.close(rStream, function () {}); // ignore
                        done();
                    });
                });
        });
    });

});<|endoftext|>


<commit_before>var cadence = require('cadence')
var Cliffhanger = require('cliffhanger')

var instance = 0

function Communicator (conduit, colleagueId, cancelable) {
    this._instance = instance++
    this._cliffhanger = new Cliffhanger
    this._cancelable = cancelable
    this._conduit = conduit
}

module.exports = Cliffhanger
<commit_msg>Remove `communicator.js`.<commit_after><|endoftext|>


<commit_before>WHOLE_UNIT = new Big(0.00000001); //Backend data returns satoshi, use this conversion ratio
SATOSHI_UNIT = new Big(100000000); //Backend data needs satoshi, use this conversion ratio
MIN_MINER_FEE = new Big(0.00010000);
function WalletTradeFormController($scope, userService, walletTradeService) {
  // [ Form Validation]
  $scope.showErrors = false;

  // [ Template Initialization ]

  $scope.currencyList = userService.getCurrencies(); // [{symbol: 'BTC', addresses:[], name: 'BTC'}, {symbol: 'MSC', addresses:[], name: 'MSC'}, {symbol: 'TMSC', addresses:[], name: 'TMSC'}]

  $scope.selectedCoin = $scope.currencyList[0];
  $scope.currencyList.forEach(function(e, i) {
    if (e.symbol == "MSC")
      $scope.selectedCoin = e;
  });

  $scope.addressList = userService.getAddressesWithPrivkey($scope.selectedCoin.tradableAddresses);
  $scope.selectedAddress = $scope.addressList[0];
  $scope.$watch('selectedCoin', function() {
    $scope.addressList = userService.getAddressesWithPrivkey($scope.selectedCoin.tradableAddresses);
    $scope.selectedAddress = $scope.addressList[0];
    $scope.setBalance();
    $scope.minerFees = +MIN_MINER_FEE.valueOf() // reset miner fees
    $scope.calculateTotal($scope.minerFees);
  });

  $scope.calculateTotal = calculateTotal;

  $scope.minerFees = +MIN_MINER_FEE.valueOf(); //set default miner fees
  $scope.calculateTotal($scope.minerFees);

  // [ Retrieve Balances ]
  $scope.currencyUnit = 'stom'; // satoshi to millibitt
  $scope.amountUnit = 'mtow';
  $scope.balanceData = [0];
  var addrListBal = [];
  $scope.addressList.forEach(function(e, i) {
    var balances = [
      {
        symbol: 'MSC',
        value: '0'
      },
      {
        symbol: 'TMSC',
        value: '0'
      },
      {
        symbol: 'BTC',
        value: '0'
      }];
    addrListBal[i] = {
      address: e,
      balance: balances
    };
    var promise = walletTradeService.getAddressData(e);
    promise.then(function(successData) {
      var successData = successData.data;
      addrListBal[i].balance =  successData.balance;
      $scope.setBalance();
    }, function(errorData) {
      alert("We have encountered a problem accessing the server ... Please try again in a few minutes");
      //console.log('Error, no balance data found for ' + e + ' setting defaults...');
    });
  });

  $scope.setBalance = function() {
    var coin = $scope.selectedCoin.symbol;
    var address = $scope.selectedAddress;
    $scope.balanceData = [0,0];
    if (address || coin) {
      for (var i = 0; i < addrListBal.length; i++) {
        if (addrListBal[i].address == address) {
          for (var k = 0; k < addrListBal[i].balance.length; k++) {
            if (addrListBal[i].balance[k].symbol == coin) {
              var divisible = addrListBal[i].balance[k].divisible;
              $scope.balanceData[0] = divisible ? new Big(addrListBal[i].balance[k].value).times(WHOLE_UNIT).valueOf() : addrListBal[i].balance[k].value;
            }
            if (addrListBal[i].balance[k].symbol == 'BTC') {
              $scope.balanceData[1] = new Big(addrListBal[i].balance[k].value).times(WHOLE_UNIT).valueOf();
            }
          }
        }
      }
    }
  };

  $scope.convertSatoshiToDisplayedValue = function(satoshi, forceConvertToWhole ) {
      if($scope.selectedCoin.divisible || forceConvertToWhole )
        return new Big(satoshi).times(WHOLE_UNIT).toFixed(8);
      else
        return satoshi;
  }

  $scope.getDisplayedAbbreviation = function () {
    if($scope.selectedCoin.divisible) {
      $scope.sendPlaceholderValue = '1.00000000'
      $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '0.00000001'
    } else {
      $scope.sendPlaceholderValue = $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '1'
    }
    if ($scope.selectedCoin.symbol.indexOf('SP') == 0) {
      for (var i in $scope.currencyList) {
        if ($scope.currencyList[i].symbol == $scope.selectedCoin.symbol)
          return $scope.currencyList[i].name + ' #' + $scope.selectedCoin.symbol.match(/SP([0-9]+)/)[1];
      }
      return 'Smart Property #' + $scope.selectedCoin.symbol.match(/SP([0-9]+)/)[1];
    }
    else
      return $scope.selectedCoin.symbol;
  }

  $scope.convertDisplayedValue = function (value) {
      if (value instanceof Array) {
        value.forEach(function(e, i, a) {
            a[i] = new Big(e).times(SATOSHI_UNIT).valueOf();
        });
        return value;
      }
      else
          return new Big(value).times(SATOSHI_UNIT).valueOf();
  }

  function calculateTotal(minerFees) {
    $scope.mProtocolCost = 0.00025
    if ($scope.selectedCoin.symbol == 'BTC')
      $scope.mProtocolCost = 0.0;
    $scope.totalCost = (+new Big(minerFees).plus($scope.mProtocolCost).valueOf()).toFixed(8);
  }
};
<commit_msg>Allow only to choose tradable currencies<commit_after>WHOLE_UNIT = new Big(0.00000001); //Backend data returns satoshi, use this conversion ratio
SATOSHI_UNIT = new Big(100000000); //Backend data needs satoshi, use this conversion ratio
MIN_MINER_FEE = new Big(0.00010000);
function WalletTradeFormController($scope, userService, walletTradeService) {
  // [ Form Validation]
  $scope.showErrors = false;

  // [ Template Initialization ]

  $scope.currencyList = userService.getCurrencies().filter(function(currency){
    return currency.tradable;
  }); // [{symbol: 'BTC', addresses:[], name: 'BTC'}, {symbol: 'MSC', addresses:[], name: 'MSC'}, {symbol: 'TMSC', addresses:[], name: 'TMSC'}]

  $scope.selectedCoin = $scope.currencyList[0];
  $scope.currencyList.forEach(function(e, i) {
    if (e.symbol == "MSC")
      $scope.selectedCoin = e;
  });

  $scope.addressList = userService.getAddressesWithPrivkey($scope.selectedCoin.tradableAddresses);
  $scope.selectedAddress = $scope.addressList[0];
  $scope.$watch('selectedCoin', function() {
    $scope.addressList = userService.getAddressesWithPrivkey($scope.selectedCoin.tradableAddresses);
    $scope.selectedAddress = $scope.addressList[0];
    $scope.setBalance();
    $scope.minerFees = +MIN_MINER_FEE.valueOf() // reset miner fees
    $scope.calculateTotal($scope.minerFees);
  });

  $scope.calculateTotal = calculateTotal;

  $scope.minerFees = +MIN_MINER_FEE.valueOf(); //set default miner fees
  $scope.calculateTotal($scope.minerFees);

  // [ Retrieve Balances ]
  $scope.currencyUnit = 'stom'; // satoshi to millibitt
  $scope.amountUnit = 'mtow';
  $scope.balanceData = [0];
  var addrListBal = [];
  $scope.addressList.forEach(function(e, i) {
    var balances = [
      {
        symbol: 'MSC',
        value: '0'
      },
      {
        symbol: 'TMSC',
        value: '0'
      },
      {
        symbol: 'BTC',
        value: '0'
      }];
    addrListBal[i] = {
      address: e,
      balance: balances
    };
    var promise = walletTradeService.getAddressData(e);
    promise.then(function(successData) {
      var successData = successData.data;
      addrListBal[i].balance =  successData.balance;
      $scope.setBalance();
    }, function(errorData) {
      alert("We have encountered a problem accessing the server ... Please try again in a few minutes");
      //console.log('Error, no balance data found for ' + e + ' setting defaults...');
    });
  });

  $scope.setBalance = function() {
    var coin = $scope.selectedCoin.symbol;
    var address = $scope.selectedAddress;
    $scope.balanceData = [0,0];
    if (address || coin) {
      for (var i = 0; i < addrListBal.length; i++) {
        if (addrListBal[i].address == address) {
          for (var k = 0; k < addrListBal[i].balance.length; k++) {
            if (addrListBal[i].balance[k].symbol == coin) {
              var divisible = addrListBal[i].balance[k].divisible;
              $scope.balanceData[0] = divisible ? new Big(addrListBal[i].balance[k].value).times(WHOLE_UNIT).valueOf() : addrListBal[i].balance[k].value;
            }
            if (addrListBal[i].balance[k].symbol == 'BTC') {
              $scope.balanceData[1] = new Big(addrListBal[i].balance[k].value).times(WHOLE_UNIT).valueOf();
            }
          }
        }
      }
    }
  };

  $scope.convertSatoshiToDisplayedValue = function(satoshi, forceConvertToWhole ) {
      if($scope.selectedCoin.divisible || forceConvertToWhole )
        return new Big(satoshi).times(WHOLE_UNIT).toFixed(8);
      else
        return satoshi;
  }

  $scope.getDisplayedAbbreviation = function () {
    if($scope.selectedCoin.divisible) {
      $scope.sendPlaceholderValue = '1.00000000'
      $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '0.00000001'
    } else {
      $scope.sendPlaceholderValue = $scope.sendPlaceholderStep = $scope.sendPlaceholderMin = '1'
    }
    if ($scope.selectedCoin.symbol.indexOf('SP') == 0) {
      for (var i in $scope.currencyList) {
        if ($scope.currencyList[i].symbol == $scope.selectedCoin.symbol)
          return $scope.currencyList[i].name + ' #' + $scope.selectedCoin.symbol.match(/SP([0-9]+)/)[1];
      }
      return 'Smart Property #' + $scope.selectedCoin.symbol.match(/SP([0-9]+)/)[1];
    }
    else
      return $scope.selectedCoin.symbol;
  }

  $scope.convertDisplayedValue = function (value) {
      if (value instanceof Array) {
        value.forEach(function(e, i, a) {
            a[i] = new Big(e).times(SATOSHI_UNIT).valueOf();
        });
        return value;
      }
      else
          return new Big(value).times(SATOSHI_UNIT).valueOf();
  }

  function calculateTotal(minerFees) {
    $scope.mProtocolCost = 0.00025
    if ($scope.selectedCoin.symbol == 'BTC')
      $scope.mProtocolCost = 0.0;
    $scope.totalCost = (+new Big(minerFees).plus($scope.mProtocolCost).valueOf()).toFixed(8);
  }
};
<|endoftext|>


<commit_before>var should      = require('should');
var fs          = require('fs');
var SimpleScApi = require('../index.js');

describe('s-simple-api functional', function() {
  var ssa = new SimpleScApi()

  if ('elevate' in process.env) ssa.enableElevation(true)

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });

  it('should install a fake service', function(done) {
    ssa.nssmInstall('fake', 'C:\\nodejsx64\\node.exe', 'C:\\vagrant\\utils\\fake-service.js', function (err) {
      (err===null).should.eql(true);
      err && console.error(err);
      done();
    })
  });

  it.skip('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      console.log(list['fake']);
      ('fake' in list).should.eql(true);
      done();
    })
  });

  it('should start the fake service', function(done) {
    ssa.start('fake', [], function (err) {
      setTimeout(function(){
        done(err);
      }, 500); // this is needed for the system to load and start the program.
    })
  });

  it('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(true);
      list['fake'].name.should.eql('fake');
      done();
    })
  });

  it('should be able to consume the service', function(done) {
    var net = require('net');
    var client = net.connect({port: 8080});
    var d;
    client.on('data', (data) => {
      d = data.toString()
    });
    client.on('end', () => {
      d.should.match(/goodbye/)
      done();
    });
    client.on('error', done);
  });

  it('should stop the fake service', function(done) {
    ssa.stop('fake', done)
  });

  it('should remove the fake service', function(done) {
    var service = {
      id: 'fake',
    }
    ssa.uninstall(service, done)
  });

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });
});
<commit_msg>improve tests<commit_after>var should      = require('should');
var fs          = require('fs');
var SimpleScApi = require('../index.js');

describe('s-simple-api functional', function() {
  var ssa = new SimpleScApi()

  if ('elevate' in process.env) ssa.enableElevation(true)

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });

  it('should install a fake service', function(done) {
    ssa.nssmInstall('fake', 'C:\\nodejsx64\\node.exe', 'C:\\vagrant\\utils\\fake-service.js', function (err) {
      (!err).should.eql(true);
      err && console.error(err);
      done();
    })
  });

  it.skip('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      console.log(list['fake']);
      ('fake' in list).should.eql(true);
      done();
    })
  });

  it('should start the fake service', function(done) {
    ssa.start('fake', [], function (err) {
      setTimeout(function(){
        done(err);
      }, 500); // this is needed for the system to load and start the program.
    })
  });

  it('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(true);
      list['fake'].name.should.eql('fake');
      done();
    })
  });

  it('should be able to consume the service', function(done) {
    var net = require('net');
    var client = net.connect({port: 8080});
    var d;
    client.on('data', (data) => {
      d = data.toString()
    });
    client.on('end', () => {
      d.should.match(/goodbye/)
      done();
    });
    client.on('error', done);
  });

  it('should stop the fake service', function(done) {
    ssa.stop('fake', done)
  });

  it('should remove the fake service', function(done) {
    var service = {
      id: 'fake',
    }
    ssa.uninstall(service, done)
  });

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });
});
<|endoftext|>


<commit_before>$("#openbem").on("click",'.add-element', function() {

    var lib = $(this).attr("lib");
    var type = $(this).attr("type").toLowerCase();

    // Create default element
    var element = {type:type,name:type,lib:lib,l:0,h:0,area:0,uvalue:0,kvalue:0,wk:0};

    // If library is defined replace defaults with parameters from library
    if (lib!=undefined) {
        for (z in element_library[lib]) element[z] = element_library[lib][z];
    }

    if (type=="window") {
        element.orientation = 3;
        element.overshading = 2;
    }

    data.fabric.elements.push(element);

    var newelementid = data.fabric.elements.length - 1;
    if (type=="wall") add_element("#elements",newelementid);
    if (type=="roof") add_element("#roofs",newelementid);
    if (type=="floor") add_element("#floors",newelementid);
    if (type=="window") add_window(newelementid);

    update();

    if (type!="window" && type!="floor") {
        for (z in data.fabric.elements) {
            if (data.fabric.elements[z].type=="window") {
                $("#windows [key='data.fabric.elements."+z+".subtractfrom']").append("<option value='"+newelementid+"'>"+data.fabric.elements[newelementid].name+"</option>");
            }
        }
    }

    $('#myModal').modal('hide');
});

$("#openbem").on("click",'.delete-element', function(){
    var row = $(this).attr('row');
    $(this).closest('tr').remove();
    data.fabric.elements.splice(row,1);
    elements_initUI();
    update();
});

$("#create-element").click(function() {
    //
    $("#myModalcreateelement").modal('show');
    $('#myModal').modal('hide');
});

$("#create-element-type").change(function(){
   var type = $(this).val();
   if (type == "Window") {
       $(".create-element-window-options").show();
   } else {
       $(".create-element-window-options").hide();
   }
});

$("#create-element-save").click(function() {

    var type = $("#create-element-type").val();
    var tag = $("#create-element-tag").val();

    //if (element_library[tag]==undefined) {
        element_library[tag] = {};

        element_library[tag].name = $("#create-element-name").val();
        element_library[tag].source = $("#create-element-source").val();
        element_library[tag].uvalue = $("#create-element-uvalue").val();
        element_library[tag].kvalue = $("#create-element-kvalue").val();

        if (type=="Window") element_library[tag].g = $("#create-element-g").val();
        if (type=="Window") element_library[tag].gL = $("#create-element-gL").val();
        if (type=="Window") element_library[tag].ff = $("#create-element-ff").val();

        element_library[tag].tags = [type],
        element_library[tag].criteria = $("#create-element-criteria").val().split(",");

        $.ajax({type: "POST", url: path+"assessment/savelibrary.json", data:"id="+selected_library+"&data="+JSON.stringify(element_library), success: function(result){
            console.log("save library result: "+result);
        }});

        $("#myModalcreateelement").modal('hide');
    //} else {
    //    alert("Element or measure already exists");
    //}
});

function add_element(id,z)
{
    $(id).append($("#element-template").html());
    $(id+" [key='data.fabric.elements.template.type']").attr('key','data.fabric.elements.'+z+'.type');
    $(id+" [key='data.fabric.elements.template.name']").attr('key','data.fabric.elements.'+z+'.name');
    $(id+" [key='data.fabric.elements.template.lib']").attr('key','data.fabric.elements.'+z+'.lib');
    $(id+" [key='data.fabric.elements.template.l']").attr('key','data.fabric.elements.'+z+'.l');
    $(id+" [key='data.fabric.elements.template.h']").attr('key','data.fabric.elements.'+z+'.h');
    $(id+" [key='data.fabric.elements.template.area']").attr('key','data.fabric.elements.'+z+'.area');
    $(id+" [key='data.fabric.elements.template.windowarea']").attr('key','data.fabric.elements.'+z+'.windowarea');
    $(id+" [key='data.fabric.elements.template.netarea']").attr('key','data.fabric.elements.'+z+'.netarea');
    $(id+" [key='data.fabric.elements.template.uvalue']").attr('key','data.fabric.elements.'+z+'.uvalue');
    $(id+" [key='data.fabric.elements.template.kvalue']").attr('key','data.fabric.elements.'+z+'.kvalue');
    $(id+" [key='data.fabric.elements.template.wk']").attr('key','data.fabric.elements.'+z+'.wk');

    $(id+" [row='template']").attr('row',z);
}

function add_window(z)
{
    $("#windows").append($("#window-template").html());
    $("#windows [key='data.fabric.elements.template.name']").attr('key','data.fabric.elements.'+z+'.name');
    $("#windows [key='data.fabric.elements.template.description']").attr('key','data.fabric.elements.'+z+'.description');
    $("#windows [key='data.fabric.elements.template.subtractfrom']").attr('key','data.fabric.elements.'+z+'.subtractfrom');
    $("#windows [key='data.fabric.elements.template.l']").attr('key','data.fabric.elements.'+z+'.l');
    $("#windows [key='data.fabric.elements.template.h']").attr('key','data.fabric.elements.'+z+'.h');
    $("#windows [key='data.fabric.elements.template.area']").attr('key','data.fabric.elements.'+z+'.area');
    $("#windows [key='data.fabric.elements.template.uvalue']").attr('key','data.fabric.elements.'+z+'.uvalue');

    $("#windows [key='data.fabric.elements.template.orientation']").attr('key','data.fabric.elements.'+z+'.orientation');
    $("#windows [key='data.fabric.elements.template.overshading']").attr('key','data.fabric.elements.'+z+'.overshading');

    $("#windows [key='data.fabric.elements.template.g']").attr('key','data.fabric.elements.'+z+'.g');
    $("#windows [key='data.fabric.elements.template.gL']").attr('key','data.fabric.elements.'+z+'.gL');
    $("#windows [key='data.fabric.elements.template.ff']").attr('key','data.fabric.elements.'+z+'.ff');
    $("#windows [key='data.fabric.elements.template.wk']").attr('key','data.fabric.elements.'+z+'.wk');
    $("#windows [key='data.fabric.elements.template.gain']").attr('key','data.fabric.elements.'+z+'.gain');

    $("#windows [row='template']").attr('row',z);

    var subtractfromhtml = "<option value='no' ></option>";
    for (i in data.fabric.elements) {
        if (data.fabric.elements[i].type!='window' && data.fabric.elements[i].type!='floor') subtractfromhtml += "<option value='"+i+"'>"+data.fabric.elements[i].name+"</option>";
    }
    $("#windows [key='data.fabric.elements."+z+".subtractfrom']").html(subtractfromhtml);
}

function elements_initUI()
{
    $("#elements").html("");
    $("#roofs").html("");
    $("#floors").html("");
    $("#windows").html("");

    // Initial addition of floors
    for (z in data.fabric.elements) {
        if (data.fabric.elements[z].type=='wall') {
            add_element("#elements",z);
        } else if (data.fabric.elements[z].type=='floor') {
            add_element("#floors",z);
        } else if (data.fabric.elements[z].type=='roof') {
            add_element("#roofs",z);
        } else if (data.fabric.elements[z].type=='window') {
            add_window(z);
        }
    }

    loadlibrarylist(function(){
        loadlibrary(selected_library,function(){});
    });
}

//-----------------------------------------------------------------------------------------------
// Element library
//-----------------------------------------------------------------------------------------------

function loadlibrarylist(callback) {
    var mylibraries = [];

    $.ajax({ url: path+"assessment/listlibrary.json", datatype:"json", success: function(result){
        mylibraries = result;

        if (selected_library==-1 && mylibraries.length>0) {
            selected_library = mylibraries[0].id;
        } else {
            $.ajax({ url: path+"assessment/newlibrary.json", data: "name=StandardLibrary", datatype:"json", async:false, success: function(result){
                console.log(result);
                selected_library = result;
                element_library = standard_element_library;
                mylibraries[0] = {id:selected_library, name:"StandardLibrary"};
                $.ajax({type: "POST", url: path+"assessment/savelibrary.json", data:"id="+selected_library+"&data="+JSON.stringify(element_library), success: function(result){
                    console.log("save library result: "+result);
                }});
            }});
        }

        var out = "";
        for (z in mylibraries) {
            out += "<option value="+mylibraries[z].id+">"+mylibraries[z].name+"</option>";
        }

        out += "<option value=-1 class='newlibraryoption' style='background-color:#eee'>Create new</option>";
        $("#library-select").html(out);
        $("#library-select").val(selected_library);

        callback();
    }});
}

function loadlibrary(id,callback) {
    element_library = {};
    // selected_library = id
    // try loading the library from the database
    $.ajax({ url: path+"assessment/loadlibrary.json", data: "id="+id, datatype:"json", success: function(result){
        element_library = result;
        // check if library is empty
        var num = 0; for (z in element_library) num++;
        // if empty load standard library
        // if (num==0) element_library = standard_element_library;
        callback();
    }});
}

$("#openbem").on("click",'.add-element-from-lib', function() {
    var tag = $(this).attr("tags");
    draw_library(tag);
});

function draw_library(tag)
{
    var out = "";
    for (z in element_library){
        if (element_library[z].tags.indexOf(tag)!=-1) {
            out += "
";
            out += ""+z+"	";

            out += ""+element_library[z].name;
            out += "
Source: "+element_library[z].source+"";
            if (element_library[z].criteria.length)
                out += "
Measure criteria: "+element_library[z].criteria.join(", ")+"";
            out += "	";

            out += "";
                out += "U-value: "+element_library[z].uvalue+" W/K.m2";
                out += "
k-value: "+element_library[z].kvalue+" kJ/K.m2";
                if (element_library[z].tags[0]=="Window") {
                    out += "
g: "+element_library[z].g+", ";
                    out += "gL: "+element_library[z].gL+", ";
                    out += "ff: "+element_library[z].ff;
                }
            out += "	";

            out += "";
                out += "";
                // out += "";
                out += "<button class='add-element btn' style='margin-left:20px' lib='"+z+"' type='"+tag+"'>use</button";
            out += "	";
            out += "
";
        }
    }
    $("#element_library").html(out);
    $('#myModal').modal('show');

}

$("#openbem").on("click",'.apply-measure-list', function() {
    var row = $(this).attr('row');
    var element = data.fabric.elements[row];

    var out = "";
    for (z in element_library){
        if (element_library[z].criteria.indexOf(element.lib)!=-1) {
            out += "
";
            out += ""+z+"	";
            out += ""+element_library[z].name+"	";
            out += ""+element_library[z].source+"	";
            out += ""+element_library[z].uvalue+" W/K.m2	";
            out += ""+element_library[z].kvalue+" kJ/K.m2	";
            // out += ""+element_library[z].criteria.join(",")+"	";
            out += "
";
        }
    }
    $("#element_library").html(out);
    $('#myModal').modal('show');
});

$("#openbem").on("click",'.apply-measure', function() {
    var lib = $(this).attr('lib');
    var row = $(this).attr('row');

    if (lib!=undefined) {
        for (z in element_library[lib]) data.fabric.elements[row][z] = element_library[lib][z];
        data.fabric.elements[row].lib = lib;
    }

    update();
    $('#myModal').modal('hide');
});

$("#openbem").on("click",".edit-element",function() {
    var lib = $(this).attr('lib');
    var type = element_library[lib].tags[0];

    $("#create-element-tag").val(lib);
    $("#create-element-name").val(element_library[lib].name);
    $("#create-element-source").val(element_library[lib].source);
    $("#create-element-uvalue").val(element_library[lib].uvalue);
    $("#create-element-kvalue").val(element_library[lib].kvalue);
    $("#create-element-criteria").val(element_library[lib].criteria.join(","));

    $("#create-element-type").val(type);
    if (type=="Window") {
        $("#create-element-g").val(element_library[lib].g);
        $("#create-element-gL").val(element_library[lib].gL);
        $("#create-element-ff").val(element_library[lib].ff);
        $(".create-element-window-options").show();
    }

    $("#myModalcreateelement").modal('show');
    $('#myModal').modal('hide');
});

$("#openbem").on("click",".newlibraryoption",function() {
    $(".library-select-view").hide();
    $(".new-library-view").show();
});

$("#openbem").on("click","#newlibrary",function() {
    var name = $("#newlibrary-name").val();
    console.log("newlibrary:"+name);
    $.ajax({ url: path+"assessment/newlibrary.json", data: "name="+name, datatype:"json", success: function(result){
        console.log("result: "+result);
        loadlibrarylist();
        $(".library-select-view").show();
        $(".new-library-view").hide();
    }});
});

$("#library-select").change(function(){
    var id = $(this).val() * 1.0;
    if (id!=-1) {
        console.log(id);
        selected_library = id;
        loadlibrary(id,function(){
            draw_library("Wall");
        });
    }
});
$("#openbem").on("click","#cancelnewlibrary",function() {
    $(".library-select-view").show();
    $(".new-library-view").hide();
});

<commit_msg>fix for element library creation<commit_after>$("#openbem").on("click",'.add-element', function() {

    var lib = $(this).attr("lib");
    var type = $(this).attr("type").toLowerCase();

    // Create default element
    var element = {type:type,name:type,lib:lib,l:0,h:0,area:0,uvalue:0,kvalue:0,wk:0};

    // If library is defined replace defaults with parameters from library
    if (lib!=undefined) {
        for (z in element_library[lib]) element[z] = element_library[lib][z];
    }

    if (type=="window") {
        element.orientation = 3;
        element.overshading = 2;
    }

    data.fabric.elements.push(element);

    var newelementid = data.fabric.elements.length - 1;
    if (type=="wall") add_element("#elements",newelementid);
    if (type=="roof") add_element("#roofs",newelementid);
    if (type=="floor") add_element("#floors",newelementid);
    if (type=="window") add_window(newelementid);

    update();

    if (type!="window" && type!="floor") {
        for (z in data.fabric.elements) {
            if (data.fabric.elements[z].type=="window") {
                $("#windows [key='data.fabric.elements."+z+".subtractfrom']").append("<option value='"+newelementid+"'>"+data.fabric.elements[newelementid].name+"</option>");
            }
        }
    }

    $('#myModal').modal('hide');
});

$("#openbem").on("click",'.delete-element', function(){
    var row = $(this).attr('row');
    $(this).closest('tr').remove();
    data.fabric.elements.splice(row,1);
    elements_initUI();
    update();
});

$("#create-element").click(function() {
    //
    $("#myModalcreateelement").modal('show');
    $('#myModal').modal('hide');
});

$("#create-element-type").change(function(){
   var type = $(this).val();
   if (type == "Window") {
       $(".create-element-window-options").show();
   } else {
       $(".create-element-window-options").hide();
   }
});

$("#create-element-save").click(function() {

    var type = $("#create-element-type").val();
    var tag = $("#create-element-tag").val();

    //if (element_library[tag]==undefined) {
        element_library[tag] = {};

        element_library[tag].name = $("#create-element-name").val();
        element_library[tag].source = $("#create-element-source").val();
        element_library[tag].uvalue = $("#create-element-uvalue").val();
        element_library[tag].kvalue = $("#create-element-kvalue").val();

        if (type=="Window") element_library[tag].g = $("#create-element-g").val();
        if (type=="Window") element_library[tag].gL = $("#create-element-gL").val();
        if (type=="Window") element_library[tag].ff = $("#create-element-ff").val();

        element_library[tag].tags = [type],
        element_library[tag].criteria = $("#create-element-criteria").val().split(",");

        $.ajax({type: "POST", url: path+"assessment/savelibrary.json", data:"id="+selected_library+"&data="+JSON.stringify(element_library), success: function(result){
            console.log("save library result: "+result);
        }});

        $("#myModalcreateelement").modal('hide');
    //} else {
    //    alert("Element or measure already exists");
    //}
});

function add_element(id,z)
{
    $(id).append($("#element-template").html());
    $(id+" [key='data.fabric.elements.template.type']").attr('key','data.fabric.elements.'+z+'.type');
    $(id+" [key='data.fabric.elements.template.name']").attr('key','data.fabric.elements.'+z+'.name');
    $(id+" [key='data.fabric.elements.template.lib']").attr('key','data.fabric.elements.'+z+'.lib');
    $(id+" [key='data.fabric.elements.template.l']").attr('key','data.fabric.elements.'+z+'.l');
    $(id+" [key='data.fabric.elements.template.h']").attr('key','data.fabric.elements.'+z+'.h');
    $(id+" [key='data.fabric.elements.template.area']").attr('key','data.fabric.elements.'+z+'.area');
    $(id+" [key='data.fabric.elements.template.windowarea']").attr('key','data.fabric.elements.'+z+'.windowarea');
    $(id+" [key='data.fabric.elements.template.netarea']").attr('key','data.fabric.elements.'+z+'.netarea');
    $(id+" [key='data.fabric.elements.template.uvalue']").attr('key','data.fabric.elements.'+z+'.uvalue');
    $(id+" [key='data.fabric.elements.template.kvalue']").attr('key','data.fabric.elements.'+z+'.kvalue');
    $(id+" [key='data.fabric.elements.template.wk']").attr('key','data.fabric.elements.'+z+'.wk');

    $(id+" [row='template']").attr('row',z);
}

function add_window(z)
{
    $("#windows").append($("#window-template").html());
    $("#windows [key='data.fabric.elements.template.name']").attr('key','data.fabric.elements.'+z+'.name');
    $("#windows [key='data.fabric.elements.template.description']").attr('key','data.fabric.elements.'+z+'.description');
    $("#windows [key='data.fabric.elements.template.subtractfrom']").attr('key','data.fabric.elements.'+z+'.subtractfrom');
    $("#windows [key='data.fabric.elements.template.l']").attr('key','data.fabric.elements.'+z+'.l');
    $("#windows [key='data.fabric.elements.template.h']").attr('key','data.fabric.elements.'+z+'.h');
    $("#windows [key='data.fabric.elements.template.area']").attr('key','data.fabric.elements.'+z+'.area');
    $("#windows [key='data.fabric.elements.template.uvalue']").attr('key','data.fabric.elements.'+z+'.uvalue');

    $("#windows [key='data.fabric.elements.template.orientation']").attr('key','data.fabric.elements.'+z+'.orientation');
    $("#windows [key='data.fabric.elements.template.overshading']").attr('key','data.fabric.elements.'+z+'.overshading');

    $("#windows [key='data.fabric.elements.template.g']").attr('key','data.fabric.elements.'+z+'.g');
    $("#windows [key='data.fabric.elements.template.gL']").attr('key','data.fabric.elements.'+z+'.gL');
    $("#windows [key='data.fabric.elements.template.ff']").attr('key','data.fabric.elements.'+z+'.ff');
    $("#windows [key='data.fabric.elements.template.wk']").attr('key','data.fabric.elements.'+z+'.wk');
    $("#windows [key='data.fabric.elements.template.gain']").attr('key','data.fabric.elements.'+z+'.gain');

    $("#windows [row='template']").attr('row',z);

    var subtractfromhtml = "<option value='no' ></option>";
    for (i in data.fabric.elements) {
        if (data.fabric.elements[i].type!='window' && data.fabric.elements[i].type!='floor') subtractfromhtml += "<option value='"+i+"'>"+data.fabric.elements[i].name+"</option>";
    }
    $("#windows [key='data.fabric.elements."+z+".subtractfrom']").html(subtractfromhtml);
}

function elements_initUI()
{
    $("#elements").html("");
    $("#roofs").html("");
    $("#floors").html("");
    $("#windows").html("");

    // Initial addition of floors
    for (z in data.fabric.elements) {
        if (data.fabric.elements[z].type=='wall') {
            add_element("#elements",z);
        } else if (data.fabric.elements[z].type=='floor') {
            add_element("#floors",z);
        } else if (data.fabric.elements[z].type=='roof') {
            add_element("#roofs",z);
        } else if (data.fabric.elements[z].type=='window') {
            add_window(z);
        }
    }

    loadlibrarylist(function(){
        loadlibrary(selected_library,function(){});
    });
}

//-----------------------------------------------------------------------------------------------
// Element library
//-----------------------------------------------------------------------------------------------

function loadlibrarylist(callback) {
    var mylibraries = [];

    $.ajax({ url: path+"assessment/listlibrary.json", datatype:"json", success: function(result){
        mylibraries = result;

        if (selected_library!=-1 && mylibraries.length>0) {
            selected_library = mylibraries[0].id;
        } else {
            $.ajax({ url: path+"assessment/newlibrary.json", data: "name=StandardLibrary", datatype:"json", async:false, success: function(result){
                selected_library = result;
                element_library = standard_element_library;
                mylibraries[0] = {id:selected_library, name:"StandardLibrary"};
                $.ajax({type: "POST", url: path+"assessment/savelibrary.json", data:"id="+selected_library+"&data="+JSON.stringify(element_library), success: function(result){
                    console.log("save library result: "+result);
                }});
            }});
        }

        var out = "";
        for (z in mylibraries) {
            out += "<option value="+mylibraries[z].id+">"+mylibraries[z].name+"</option>";
        }

        out += "<option value=-1 class='newlibraryoption' style='background-color:#eee'>Create new</option>";
        $("#library-select").html(out);
        $("#library-select").val(selected_library);

        callback();
    }});
}

function loadlibrary(id,callback) {
    element_library = {};
    // selected_library = id
    // try loading the library from the database
    $.ajax({ url: path+"assessment/loadlibrary.json", data: "id="+id, datatype:"json", success: function(result){
        element_library = result;
        // check if library is empty
        var num = 0; for (z in element_library) num++;
        // if empty load standard library
        // if (num==0) element_library = standard_element_library;
        callback();
    }});
}

$("#openbem").on("click",'.add-element-from-lib', function() {
    var tag = $(this).attr("tags");
    draw_library(tag);
});

function draw_library(tag)
{
    var out = "";
    for (z in element_library){
        if (element_library[z].tags.indexOf(tag)!=-1) {
            out += "
";
            out += ""+z+"	";

            out += ""+element_library[z].name;
            out += "
Source: "+element_library[z].source+"";
            if (element_library[z].criteria.length)
                out += "
Measure criteria: "+element_library[z].criteria.join(", ")+"";
            out += "	";

            out += "";
                out += "U-value: "+element_library[z].uvalue+" W/K.m2";
                out += "
k-value: "+element_library[z].kvalue+" kJ/K.m2";
                if (element_library[z].tags[0]=="Window") {
                    out += "
g: "+element_library[z].g+", ";
                    out += "gL: "+element_library[z].gL+", ";
                    out += "ff: "+element_library[z].ff;
                }
            out += "	";

            out += "";
                out += "";
                // out += "";
                out += "<button class='add-element btn' style='margin-left:20px' lib='"+z+"' type='"+tag+"'>use</button";
            out += "	";
            out += "
";
        }
    }
    $("#element_library").html(out);
    $('#myModal').modal('show');

}

$("#openbem").on("click",'.apply-measure-list', function() {
    var row = $(this).attr('row');
    var element = data.fabric.elements[row];

    var out = "";
    for (z in element_library){
        if (element_library[z].criteria.indexOf(element.lib)!=-1) {
            out += "
";
            out += ""+z+"	";
            out += ""+element_library[z].name+"	";
            out += ""+element_library[z].source+"	";
            out += ""+element_library[z].uvalue+" W/K.m2	";
            out += ""+element_library[z].kvalue+" kJ/K.m2	";
            // out += ""+element_library[z].criteria.join(",")+"	";
            out += "
";
        }
    }
    $("#element_library").html(out);
    $('#myModal').modal('show');
});

$("#openbem").on("click",'.apply-measure', function() {
    var lib = $(this).attr('lib');
    var row = $(this).attr('row');

    if (lib!=undefined) {
        for (z in element_library[lib]) data.fabric.elements[row][z] = element_library[lib][z];
        data.fabric.elements[row].lib = lib;
    }

    update();
    $('#myModal').modal('hide');
});

$("#openbem").on("click",".edit-element",function() {
    var lib = $(this).attr('lib');
    var type = element_library[lib].tags[0];

    $("#create-element-tag").val(lib);
    $("#create-element-name").val(element_library[lib].name);
    $("#create-element-source").val(element_library[lib].source);
    $("#create-element-uvalue").val(element_library[lib].uvalue);
    $("#create-element-kvalue").val(element_library[lib].kvalue);
    $("#create-element-criteria").val(element_library[lib].criteria.join(","));

    $("#create-element-type").val(type);
    if (type=="Window") {
        $("#create-element-g").val(element_library[lib].g);
        $("#create-element-gL").val(element_library[lib].gL);
        $("#create-element-ff").val(element_library[lib].ff);
        $(".create-element-window-options").show();
    }

    $("#myModalcreateelement").modal('show');
    $('#myModal').modal('hide');
});

$("#openbem").on("click",".newlibraryoption",function() {
    $(".library-select-view").hide();
    $(".new-library-view").show();
});

$("#openbem").on("click","#newlibrary",function() {
    var name = $("#newlibrary-name").val();
    console.log("newlibrary:"+name);
    $.ajax({ url: path+"assessment/newlibrary.json", data: "name="+name, datatype:"json", success: function(result){
        console.log("result: "+result);
        loadlibrarylist();
        $(".library-select-view").show();
        $(".new-library-view").hide();
    }});
});

$("#library-select").change(function(){
    var id = $(this).val() * 1.0;
    if (id!=-1) {
        console.log(id);
        selected_library = id;
        loadlibrary(id,function(){
            draw_library("Wall");
        });
    }
});
$("#openbem").on("click","#cancelnewlibrary",function() {
    $(".library-select-view").show();
    $(".new-library-view").hide();
});

<|endoftext|>


<commit_before>
/**
 * Test dependencies.
 */

var assert = require('assert');
var x = require('..');
var Store = require('datastore');

describe('basic', function() {

  it('should return a function', function() {
    var dom = x('button');
    assert.equal(typeof dom, 'function');
  });

  it('should create dom element with a specified tag', function() {
    var el = x('button')();
    assert.equal(el.nodeName, 'BUTTON');
  });

  it('should set the inner value of the returned element', function() {
    var el = x('button', 'hello')();
    assert.equal(el.innerHTML, 'hello');
  });

  describe("inception", function() {

    it('should append one dom node', function() {
      var dom = x('ul', [
        x('li', 'hello')
      ])();

      var li = dom.firstChild;
      assert.equal(li.nodeName, 'LI');
      assert.equal(li.innerHTML, 'hello');

    });

    it('should append multiple dom nodes', function() {
      var dom = x('ul', [
        x('li', 'hello'),
        x('li', 'world')
      ])();
      assert.equal(dom.children.length, 2);
    });

    it('should append string as a dom node', function() {
      var dom = x('ul', [
        'hello'
      ])();
      assert.equal(dom.innerHTML, 'hello');
    });

    it('should mix text and dom nodes', function() {
      var dom = x('div', [
        'hello',
        x('ul', [
          x('li', 'hello'),
          x('li', 'world')
        ])
      ])();
      assert.equal(dom.innerHTML, 'hello

hello

world

');
    });

  });

  describe("attributes", function() {

    it('should set attributes', function() {
      var dom = x('button', {
        class: 'btn'
      })();
      assert.equal(dom.className, 'btn');
    });

    it('should still set dom nodes', function() {
      var dom = x('button', {
        class: 'btn'
      }, [
        x('img', {
          src: 'hello'
        })
      ])();

      var img = dom.firstChild;
      assert.equal(img.nodeName, 'IMG');
      assert.equal(img.getAttribute('src'), 'hello');
    });

    it('should still set text node', function() {
      var dom = x('button', {
        class: 'btn'
      }, 'hello')();
      assert.equal(dom.innerHTML, 'hello');
    });

    describe('attributes function', function() {

      it('should define functions as attributes', function() {
        var dom = x('button', {
          class: function() {
            return 'hello-world';
          }
        })();
        assert.equal(dom.className, 'hello-world');
      });

      it('should call function with data', function() {
        var dom = x('h1', {
          class: function() {
            return this.type;
          }
        })({
          type: 'title'
        });

        assert.equal(dom.className, 'title');
      });

    });

    describe('attributes listener', function() {
      var ev = document.createEvent('MouseEvents');
      ev.initEvent('click', true, true);
      //ev.synthetic = true;

      it('should listen dom events', function(done) {
        var dom = x('button', {
          onclick: function() {
            done();
          }
        })();

        dom.dispatchEvent(ev, true);

      });
    });

  });

  describe('styles', function() {

    it('should create styles from object', function() {
      var dom = x('button', {
        style: {
          background: 'red',
          width: '100px'
        }
      })();

      assert.equal(dom.getAttribute('style'), 'background:red;width:100px;');
    });

  });

});

describe('template', function() {

  it('should substitute inner text with data', function() {
    var dom = x('button', '${label}')({
      label: 'hello'
    });
    assert.equal(dom.innerHTML, 'hello');
  });

  it('should substitute attributes with data', function() {
    var dom = x('button', {
      class: 'btn ${label}'
    }, '${label}')({
      label: 'hello'
    });
    assert.equal(dom.className, 'btn hello');
  });

  describe('observable', function() {

    it('should update inner text when data changes', function() {
      var store = new Store({
        label: 'hello'
      });
      var dom = x('button', '${label}')(store);
      assert.equal(dom.innerHTML, 'hello');
      store.set('label', 'world');
      assert.equal(dom.innerHTML, 'world');
    });

    it('should update attribute when data changes', function() {
      var store = new Store({
        label: 'hello'
      });
      var dom = x('button', {
        class: 'btn ${label}'
      })(store);
      assert.equal(dom.className, 'btn hello');
      store.set('label', 'world');
      assert.equal(dom.className, 'btn world');
    });

  });

});
<commit_msg>interpolate style attribute<commit_after>
/**
 * Test dependencies.
 */

var assert = require('assert');
var x = require('..');
var Store = require('datastore');

describe('basic', function() {

  it('should return a function', function() {
    var dom = x('button');
    assert.equal(typeof dom, 'function');
  });

  it('should create dom element with a specified tag', function() {
    var el = x('button')();
    assert.equal(el.nodeName, 'BUTTON');
  });

  it('should set the inner value of the returned element', function() {
    var el = x('button', 'hello')();
    assert.equal(el.innerHTML, 'hello');
  });

  describe("inception", function() {

    it('should append one dom node', function() {
      var dom = x('ul', [
        x('li', 'hello')
      ])();

      var li = dom.firstChild;
      assert.equal(li.nodeName, 'LI');
      assert.equal(li.innerHTML, 'hello');

    });

    it('should append multiple dom nodes', function() {
      var dom = x('ul', [
        x('li', 'hello'),
        x('li', 'world')
      ])();
      assert.equal(dom.children.length, 2);
    });

    it('should append string as a dom node', function() {
      var dom = x('ul', [
        'hello'
      ])();
      assert.equal(dom.innerHTML, 'hello');
    });

    it('should mix text and dom nodes', function() {
      var dom = x('div', [
        'hello',
        x('ul', [
          x('li', 'hello'),
          x('li', 'world')
        ])
      ])();
      assert.equal(dom.innerHTML, 'hello

hello

world

');
    });

  });

  describe("attributes", function() {

    it('should set attributes', function() {
      var dom = x('button', {
        class: 'btn'
      })();
      assert.equal(dom.className, 'btn');
    });

    it('should still set dom nodes', function() {
      var dom = x('button', {
        class: 'btn'
      }, [
        x('img', {
          src: 'hello'
        })
      ])();

      var img = dom.firstChild;
      assert.equal(img.nodeName, 'IMG');
      assert.equal(img.getAttribute('src'), 'hello');
    });

    it('should still set text node', function() {
      var dom = x('button', {
        class: 'btn'
      }, 'hello')();
      assert.equal(dom.innerHTML, 'hello');
    });

    describe('attributes function', function() {

      it('should define functions as attributes', function() {
        var dom = x('button', {
          class: function() {
            return 'hello-world';
          }
        })();
        assert.equal(dom.className, 'hello-world');
      });

      it('should call function with data', function() {
        var dom = x('h1', {
          class: function() {
            return this.type;
          }
        })({
          type: 'title'
        });

        assert.equal(dom.className, 'title');
      });

    });

    describe('attributes listener', function() {
      var ev = document.createEvent('MouseEvents');
      ev.initEvent('click', true, true);
      //ev.synthetic = true;

      it('should listen dom events', function(done) {
        var dom = x('button', {
          onclick: function() {
            done();
          }
        })();

        dom.dispatchEvent(ev, true);

      });
    });

  });

  describe('styles', function() {

    it('should create styles from object', function() {
      var dom = x('button', {
        style: {
          background: 'red',
          width: '100px'
        }
      })();

      assert.equal(dom.getAttribute('style'), 'background:red;width:100px;');
    });

  });

});

describe('template', function() {

  it('should substitute inner text with data', function() {
    var dom = x('button', '${label}')({
      label: 'hello'
    });
    assert.equal(dom.innerHTML, 'hello');
  });

  it('should substitute attributes with data', function() {
    var dom = x('button', {
      class: 'btn ${label}'
    }, '${label}')({
      label: 'hello'
    });
    assert.equal(dom.className, 'btn hello');
  });

  it('should substitute styles with data', function() {
      var dom = x('button', {
        style: {
          background: '${color}',
          width: '${size}px'
        }
      })({
        color: 'red',
        size: 100
      });
      assert.equal(dom.getAttribute('style'), 'background:red;width:100px;');
  });

  describe('observable', function() {

    it('should update inner text when data changes', function() {
      var store = new Store({
        label: 'hello'
      });
      var dom = x('button', '${label}')(store);
      assert.equal(dom.innerHTML, 'hello');
      store.set('label', 'world');
      assert.equal(dom.innerHTML, 'world');
    });

    it('should update attribute when data changes', function() {
      var store = new Store({
        label: 'hello'
      });
      var dom = x('button', {
        class: 'btn ${label}'
      })(store);
      assert.equal(dom.className, 'btn hello');
      store.set('label', 'world');
      assert.equal(dom.className, 'btn world');
    });

  });

});
<|endoftext|>


<commit_before>var should = require('chai').should(),
  assert = require('chai').assert,
  CommentDocs = require('../commentdocs'),
  commentDocs = new CommentDocs();

describe('#parseSourceFile', function() {
  it('converts a file into an array of objects', function() {
    assert.deepEqual(
      commentDocs.parseSourceFile( 'test/getfilecontents.css' ),
      [{
        docs: { prop1: 'Comment one' },
        code: ''
      }]
    );
  });
});

describe('#joinDocsAndCode', function() {
  it('takes an array of doc comments and an array of code snippets and merges them into one object', function() {
    var docs = [ { prop1: 'Comment one' } ];
    var code = [ '.test{\n    content:\"Hello\";\n}' ];
    assert.deepEqual(
      commentDocs.joinDocsAndCode( docs, code ),
      [{
        docs: docs[0],
        code: code[0]
      }]
    );
  });
});

describe('#parsingIsValid', function() {
  it('validates that their is one code snippet (even if it\'s an empty string) for each doc comment', function() {
    var fileContents = '/* topdoc\n    prop1: Comment one\n*/\n.test{\n    content:\"Hello\";\n}';
    var docs = commentDocs.parseOutDocs( fileContents, commentDocs.regex.css );
    var code = commentDocs.parseOutCode( fileContents, commentDocs.regex.css );
    assert.equal( commentDocs.parsingIsValid( docs, code ), true );
  });
});

describe('#parseOutCode', function() {
  it('build an array from the code after each doc comment', function() {
    assert.deepEqual(
      commentDocs.parseOutCode(
        '/* topdoc\n    prop1: Comment one\n*/\n.test{\n    content:\"Hello\";\n}',
        commentDocs.regex.css
      ),
      [ '.test{\n    content:\"Hello\";\n}' ]
    );
  });
});

describe('#getTextFromDocComment', function() {
  it('removes the opening and closing comments from a doc comment', function() {
    assert.equal(
      commentDocs.getTextFromDocComment(
        '/* topdoc\n    prop1: Comment one\n*/\n',
        commentDocs.regex.css
      ),
      '    prop1: Comment one\n\n'
    );
  });
});

describe('#parseOutDocs', function() {
  it('build an array from the text of each doc comment', function() {
    assert.deepEqual(
      commentDocs.parseOutDocs(
        '/* topdoc\n    prop1: Comment one\n*/\n',
        commentDocs.regex.css
      ),
      [ { prop1: 'Comment one' } ]
    );
  });
});

describe('#convertYaml', function() {
  it('converts a yaml string into an object and identifies the comment number if the conversion fails', function() {
    var yamlString = 'prop1: Comment one';
    assert.deepEqual( commentDocs.convertYaml( yamlString ), { prop1: 'Comment one' } );
    assert.throws(
      function() { commentDocs.convertYaml( 'prop1: prop1:' ); },
      Error,
      'Error converting comment to YAML. Please check for formatting errors.'
    );
    assert.throws(
      function() { commentDocs.convertYaml( 'prop1: prop1:', 0 ); },
      Error,
      'Error converting comment #1 to YAML. Please check for formatting errors.'
    );
  });
});

describe('#getFileContents', function() {
  it('returns the contents of a file, trimming everything before the first doc comment', function() {
    assert.equal(
      commentDocs.getFileContents( 'test/getfilecontents.css', commentDocs.regex.css ),
      '/* topdoc\n    prop1: Comment one\n*/\n'
    );
  });
});

describe('#getCommentType', function() {
  it('returns the correct comment type based on the file extension', function() {
    assert.equal( commentDocs.getCommentType('test.css'), 'css' );
    assert.equal( commentDocs.getCommentType('test.less'), 'css' );
    assert.equal( commentDocs.getCommentType('test.less'), 'css' );
    assert.equal( commentDocs.getCommentType('test.html'), 'html' );
  });
});
<commit_msg>Reorders tests.<commit_after>var should = require('chai').should(),
  assert = require('chai').assert,
  CommentDocs = require('../commentdocs'),
  commentDocs = new CommentDocs();

describe('#getCommentType', function() {
  it('returns the correct comment type based on the file extension', function() {
    assert.equal( commentDocs.getCommentType('test.css'), 'css' );
    assert.equal( commentDocs.getCommentType('test.less'), 'css' );
    assert.equal( commentDocs.getCommentType('test.less'), 'css' );
    assert.equal( commentDocs.getCommentType('test.html'), 'html' );
  });
});

describe('#getFileContents', function() {
  it('returns the contents of a file, trimming everything before the first doc comment', function() {
    assert.equal(
      commentDocs.getFileContents( 'test/getfilecontents.css', commentDocs.regex.css ),
      '/* topdoc\n    prop1: Comment one\n*/\n'
    );
  });
});

describe('#convertYaml', function() {
  it('converts a yaml string into an object and identifies the comment number if the conversion fails', function() {
    var yamlString = 'prop1: Comment one';
    assert.deepEqual( commentDocs.convertYaml( yamlString ), { prop1: 'Comment one' } );
    assert.throws(
      function() { commentDocs.convertYaml( 'prop1: prop1:' ); },
      Error,
      'Error converting comment to YAML. Please check for formatting errors.'
    );
    assert.throws(
      function() { commentDocs.convertYaml( 'prop1: prop1:', 0 ); },
      Error,
      'Error converting comment #1 to YAML. Please check for formatting errors.'
    );
  });
});

describe('#parseOutDocs', function() {
  it('build an array from the text of each doc comment', function() {
    assert.deepEqual(
      commentDocs.parseOutDocs(
        '/* topdoc\n    prop1: Comment one\n*/\n',
        commentDocs.regex.css
      ),
      [ { prop1: 'Comment one' } ]
    );
  });
});

describe('#getTextFromDocComment', function() {
  it('removes the opening and closing comments from a doc comment', function() {
    assert.equal(
      commentDocs.getTextFromDocComment(
        '/* topdoc\n    prop1: Comment one\n*/\n',
        commentDocs.regex.css
      ),
      '    prop1: Comment one\n\n'
    );
  });
});

describe('#parseOutCode', function() {
  it('build an array from the code after each doc comment', function() {
    assert.deepEqual(
      commentDocs.parseOutCode(
        '/* topdoc\n    prop1: Comment one\n*/\n.test{\n    content:\"Hello\";\n}',
        commentDocs.regex.css
      ),
      [ '.test{\n    content:\"Hello\";\n}' ]
    );
  });
});

describe('#parsingIsValid', function() {
  it('validates that their is one code snippet (even if it\'s an empty string) for each doc comment', function() {
    var fileContents = '/* topdoc\n    prop1: Comment one\n*/\n.test{\n    content:\"Hello\";\n}';
    var docs = commentDocs.parseOutDocs( fileContents, commentDocs.regex.css );
    var code = commentDocs.parseOutCode( fileContents, commentDocs.regex.css );
    assert.equal( commentDocs.parsingIsValid( docs, code ), true );
  });
});

describe('#joinDocsAndCode', function() {
  it('takes an array of doc comments and an array of code snippets and merges them into one object', function() {
    var docs = [ { prop1: 'Comment one' } ];
    var code = [ '.test{\n    content:\"Hello\";\n}' ];
    assert.deepEqual(
      commentDocs.joinDocsAndCode( docs, code ),
      [{
        docs: docs[0],
        code: code[0]
      }]
    );
  });
});

describe('#parseSourceFile', function() {
  it('converts a file into an array of objects', function() {
    assert.deepEqual(
      commentDocs.parseSourceFile( 'test/getfilecontents.css' ),
      [{
        docs: { prop1: 'Comment one' },
        code: ''
      }]
    );
  });
});
<|endoftext|>


<commit_before>
define([
    './visualize/highlight',
    './visualize/options',
    './visualize/themes',
    './visualize/checkChartHeight',
    './visualize/loadVisDeferred',
    './visualize/initTabNav',
    './visualize/enableInlineEditing',
    './visualize/liveUpdate',
    './visualize/updateSize',
    './visualize/options',
    'js/misc/classify',
    'js/misc/jquery.easing'],

function(initHighlightSeries, visOptions, themes, checkChartHeight, loadVisDfd,
    initTabNav, enableInlineEditing, liveUpdate, updateSize, options, classify) {

    var _typeHasChanged = false,
        _themeHasChanged = false,
        _axesHaveChanged = false,
        _transposed = false,
        __thumbTimer,
        _optionsSynchronized = false,
        __updateSizeTimer,
        chart = dw.backend.currentChart,
        visMetas = {},
        iframe = $('#iframe-vis');

    function init(themesJSON, _visMetas, visJSON) {

        themes.init(themesJSON);

        visMetas = _visMetas;

        dw.backend.__currentVisLoaded = loadVisDfd.promise();

        chart.onSave(onChartSave);

        syncUI();

        chart.load(dw.backend.__currentData).done(onDatasetLoaded);
        iframe.load(iframeLoaded);

        // initialize some UI actions
        initTabNav();
        initTransposeLink();
        initVisSelector();
        initResizeChart();
        initChartSize();

        $(window).on('keyup', function(e) {
            if (e.ctrlKey && e.keyCode == 82) {
                // reload iframe on ctrl+r
                iframe.get(0).contentWindow.location.reload();
            }
        });
    }

    function onChartSave(chart) {
        if (_themeHasChanged) {
            // update the iframe background color after theme changed
            iframe.one('load', updateVisBackground);
            // update iframe size according to theme default
            _.some(themes.all(), function(theme) {
                if (theme.id == chart.get('theme')) {
                    var w = theme.default_width || chart.get('metadata.publish.embed-width'),
                        h = theme.default_height || chart.get('metadata.publish.embed-height');
                    updateSize(w, h);
                    return true;
                }
            });

            // load themes
            themes.load().done(function() {
                dw.backend.fire('theme-changed-and-loaded');
                loadOptions().done(function() {
                    loadVis();
                    themes.updateUI();
                });
            });
        }

        if (_typeHasChanged) {
            iframe.attr('src', '');
            dw.backend.fire('type-changed');
        }

        if (_axesHaveChanged) dw.backend.fire('axes-changed');
        if (_transposed) dw.backend.fire('dataset-transposed');

        if (_axesHaveChanged || _transposed || _typeHasChanged) {
            // reload options
            loadOptions().done(function() {
                dw.backend.fire('options-reloaded');
                loadVis();
            });
            // remove all notifications
            $("#notifications .notification").fadeOutAndRemove();
        }

        _themeHasChanged = false;
        _typeHasChanged = false;
        _axesHaveChanged = false;
        _transposed = false;

        var iframeWin = iframe.get(0).contentWindow;
        if (iframeWin.__dw && iframeWin.__dw.saved) {
            iframeWin.__dw.saved();
        }
        scheduleThumbnail();
        checkChartHeight();
    }

    function syncUI() {
        chart.sync('#select-theme', 'theme');
        chart.sync('#text-title', 'title');
        chart.sync('#text-intro', 'metadata.describe.intro');
        chart.sync('#text-notes', 'metadata.annotate.notes');
        chart.sync('#describe-source-name', 'metadata.describe.source-name');
        chart.sync('#describe-source-url', 'metadata.describe.source-url');

        chart.onChange(function(chart, key, value) {
            if (key == 'type') _typeHasChanged = true;
            if (key == 'theme') _themeHasChanged = true;
            if (key.substr(0, 13) == 'metadata.axes') _axesHaveChanged = true;
            if (key == 'metadata.data.transpose') _transposed = true;
            liveUpdate.update(iframe, chart.attributes());
        });
    }

    function iframeLoaded() {
        dw.backend.fire('vis-loaded');
        updateVisBackground();
        var win = iframe.get(0).contentWindow,
            chk;

        // periodically check if vis is initialized in iframe
        chk = setInterval(function() {
            if (win.__dw && win.__dw.vis) {
                clearInterval(chk);
                iframeReady();
            }
        }, 100);
    }

    /*
     * called as soon the __dw.vis object is available
     * inside the reloaded iframe
     */
    function iframeReady() {
        dw.backend.fire('vis-ready');
        var win = iframe.get(0).contentWindow;

        liveUpdate.init(iframe);

        dw.backend.on('vis-rendered', visualizationRendered);

        $(window).on('message', function(evt) {
            evt = evt.originalEvent;
            if (evt.source == win) {
                if (evt.data == 'datawrapper:vis:init') {
                    dw.backend.fire('vis-msg-init');
                    win.dw_alert = dw.backend.alert;
                    win.__dw.backend = dw.backend;
                }
                if (evt.data && evt.data.slice && evt.data.slice(0, 7) == 'notify:') {
                    dw.backend.notify(evt.data.slice(7));
                }
                if (evt.data == 'datawrapper:vis:rendered') {
                    dw.backend.fire('vis-rendered');
                }
            }
        });
    }

    /*
     * called as soon the vis is rendered (after iframe reload)
     */
    function visualizationRendered() {
        checkChartHeight();
        enableInlineEditing(iframe, chart);
        if (initHighlightSeries) initHighlightSeries();
    }

    /*
     * reload the chart specific options
     */
    function loadOptions() {
        var loaded = $.Deferred();
        _optionsSynchronized = false;
        $('#vis-options').load(
            '/xhr/'+chart.get('id')+'/vis-options?nocache='+Math.random(),
            function() {
                loaded.resolve();
                loadVis();
            }
        );
        return loaded.promise();
    }

    function initTransposeLink() {
        $('#btn-transpose').click(function(e) {
            e.preventDefault();
            chart.set('metadata.data.transpose', !chart.get('metadata.data.transpose'));
            chart.load().done(onDatasetLoaded);
            setTimeout(function() {
                loadOptions();
            }, 2000);
        });
    }

    function initVisSelector() {
        // graphical vis selector
        var unfolded = $('.vis-selector-unfolded'),
            folded = $('.vis-selector-folded'),
            thumbs = $('.vis-thumb'),
            selVis = $('.vis-selected');
        unfolded.show().data('h', unfolded.height()).hide();
        thumbs.click(function(e) {
            var thumb = $(e.target);
            if (!thumb.hasClass('vis-thumb')) thumb = thumb.parents('.vis-thumb');
            thumbs.removeClass('active');
            thumb.addClass('active');
            selVis.html('' + thumb.data('title'));
            setTimeout(function() {
                /*folded.show();
                unfolded.animate({ height: 0 }, 300, 'easeOutExpo', function() {
                    unfolded.hide();
                });*/
                chart.set('type', thumb.data('id'));
            }, 100);
        });

        folded.click(function() {
            folded.hide();
            unfolded.height(0).show().animate({ height: unfolded.data('h') }, 300);
        });

        unfolded.show();
        folded.hide();
    }

    function initResizeChart() {
        $('.resize-chart a').click(function(e) {
            e.preventDefault();
            var dim = $(e.target).html().split('×');
            $('#resize-w').val(dim[0]);
            $('#resize-h').val(dim[1]);
            updateSize(dim[0], dim[1]);
        });
    }

    function initChartSize() {
        var cw = chart.get('metadata.publish.embed-width', $('#iframe-wrapper').width()),
            ch = chart.get('metadata.publish.embed-height', $('#iframe-wrapper').height());
        $('#resize-w').val(cw);
        $('#resize-h').val(ch);
        $('.resize-chart input').change(_updateSize);
        $('#iframe-wrapper').width(cw);
        $('#iframe-wrapper').height(ch);
    }

    function scheduleThumbnail() {
        clearTimeout(__thumbTimer);
        __thumbTimer = setTimeout(function() {
            dw.backend.snapshot(iframe, dw.backend.currentChart.get('id'), 'm', 260, 160);
        }, 500);
    }

    function onDatasetLoaded() {
        dw.backend.fire('dataset-loaded');
        loadVis();
        if (initHighlightSeries) initHighlightSeries();
        _.each(themes.all(), function(theme) {
            if (theme.id == chart.get('theme')) {
                var w = chart.get('metadata.publish.embed-width', theme.default_width || 560),
                    h = chart.get('metadata.publish.embed-height', theme.default_height || 400);
                updateSize(w, h);
                return false;
            }
        });
        themes.load();
    }

    /** Set into `dw.backend.currentVis` the edited visualization (editor side) */
    function loadVis() {
        if (iframe.attr('src') === "") {
            // load vis in iframe if not done yet
            iframe.attr('src', '/chart/'+chart.get('id')+'/preview?innersvg=1&random='+Math.floor(Math.random()*100000));
        }
        dw.backend.currentVis = dw.visualization(chart.get('type'));
        dw.backend.currentVis.chart(chart);
        dw.backend.currentVis.dataset = chart.dataset().reset();
        dw.backend.currentVis.meta = visMetas[chart.get('type')];
        options.init(chart, visMetas[chart.get('type')]);
        if (!_optionsSynchronized) {
            _optionsSynchronized = true;
            options.sync();
        }
        loadVisDfd.resolve();
    }

    function updateVisBackground() {  // and show msg if chart needs more space
        var iframe = $('#iframe-vis').contents(),
            bgcol =  $('body', iframe).css('background-color'),
            white = bgcol == 'rgb(255, 255, 255)' || bgcol == '#ffffff' || bgcol == 'white' || bgcol == 'transparent',
            border = white ? '#ffffff' : '#bbb';

        bgcol = dw.backend.currentChart.get('metadata.publish.contextBg') || dw.backend.currentChart.get('metadata.publish.background');

        $('#iframe-wrapper').css({
            'background-color': white ? '#ffffff' : bgcol,
            'border-color': border
        });
    }

    // chart resizing
    function _updateSize() {
        clearTimeout(__updateSizeTimer);
        __updateSizeTimer = setTimeout(updateSize, 300);
    }

    return {
        init: init
    };

});<commit_msg>increasing snapshot timeout to 1.5s<commit_after>
define([
    './visualize/highlight',
    './visualize/options',
    './visualize/themes',
    './visualize/checkChartHeight',
    './visualize/loadVisDeferred',
    './visualize/initTabNav',
    './visualize/enableInlineEditing',
    './visualize/liveUpdate',
    './visualize/updateSize',
    './visualize/options',
    'js/misc/classify',
    'js/misc/jquery.easing'],

function(initHighlightSeries, visOptions, themes, checkChartHeight, loadVisDfd,
    initTabNav, enableInlineEditing, liveUpdate, updateSize, options, classify) {

    var _typeHasChanged = false,
        _themeHasChanged = false,
        _axesHaveChanged = false,
        _transposed = false,
        __thumbTimer,
        _optionsSynchronized = false,
        __updateSizeTimer,
        chart = dw.backend.currentChart,
        visMetas = {},
        iframe = $('#iframe-vis');

    function init(themesJSON, _visMetas, visJSON) {

        themes.init(themesJSON);

        visMetas = _visMetas;

        dw.backend.__currentVisLoaded = loadVisDfd.promise();

        chart.onSave(onChartSave);

        syncUI();

        chart.load(dw.backend.__currentData).done(onDatasetLoaded);
        iframe.load(iframeLoaded);

        // initialize some UI actions
        initTabNav();
        initTransposeLink();
        initVisSelector();
        initResizeChart();
        initChartSize();

        $(window).on('keyup', function(e) {
            if (e.ctrlKey && e.keyCode == 82) {
                // reload iframe on ctrl+r
                iframe.get(0).contentWindow.location.reload();
            }
        });
    }

    function onChartSave(chart) {
        if (_themeHasChanged) {
            // update the iframe background color after theme changed
            iframe.one('load', updateVisBackground);
            // update iframe size according to theme default
            _.some(themes.all(), function(theme) {
                if (theme.id == chart.get('theme')) {
                    var w = theme.default_width || chart.get('metadata.publish.embed-width'),
                        h = theme.default_height || chart.get('metadata.publish.embed-height');
                    updateSize(w, h);
                    return true;
                }
            });

            // load themes
            themes.load().done(function() {
                dw.backend.fire('theme-changed-and-loaded');
                loadOptions().done(function() {
                    loadVis();
                    themes.updateUI();
                });
            });
        }

        if (_typeHasChanged) {
            iframe.attr('src', '');
            dw.backend.fire('type-changed');
        }

        if (_axesHaveChanged) dw.backend.fire('axes-changed');
        if (_transposed) dw.backend.fire('dataset-transposed');

        if (_axesHaveChanged || _transposed || _typeHasChanged) {
            // reload options
            loadOptions().done(function() {
                dw.backend.fire('options-reloaded');
                loadVis();
            });
            // remove all notifications
            $("#notifications .notification").fadeOutAndRemove();
        }

        _themeHasChanged = false;
        _typeHasChanged = false;
        _axesHaveChanged = false;
        _transposed = false;

        var iframeWin = iframe.get(0).contentWindow;
        if (iframeWin.__dw && iframeWin.__dw.saved) {
            iframeWin.__dw.saved();
        }
        scheduleThumbnail();
        checkChartHeight();
    }

    function syncUI() {
        chart.sync('#select-theme', 'theme');
        chart.sync('#text-title', 'title');
        chart.sync('#text-intro', 'metadata.describe.intro');
        chart.sync('#text-notes', 'metadata.annotate.notes');
        chart.sync('#describe-source-name', 'metadata.describe.source-name');
        chart.sync('#describe-source-url', 'metadata.describe.source-url');

        chart.onChange(function(chart, key, value) {
            if (key == 'type') _typeHasChanged = true;
            if (key == 'theme') _themeHasChanged = true;
            if (key.substr(0, 13) == 'metadata.axes') _axesHaveChanged = true;
            if (key == 'metadata.data.transpose') _transposed = true;
            liveUpdate.update(iframe, chart.attributes());
        });
    }

    function iframeLoaded() {
        dw.backend.fire('vis-loaded');
        updateVisBackground();
        var win = iframe.get(0).contentWindow,
            chk;

        // periodically check if vis is initialized in iframe
        chk = setInterval(function() {
            if (win.__dw && win.__dw.vis) {
                clearInterval(chk);
                iframeReady();
            }
        }, 100);
    }

    /*
     * called as soon the __dw.vis object is available
     * inside the reloaded iframe
     */
    function iframeReady() {
        dw.backend.fire('vis-ready');
        var win = iframe.get(0).contentWindow;

        liveUpdate.init(iframe);

        dw.backend.on('vis-rendered', visualizationRendered);

        $(window).on('message', function(evt) {
            evt = evt.originalEvent;
            if (evt.source == win) {
                if (evt.data == 'datawrapper:vis:init') {
                    dw.backend.fire('vis-msg-init');
                    win.dw_alert = dw.backend.alert;
                    win.__dw.backend = dw.backend;
                }
                if (evt.data && evt.data.slice && evt.data.slice(0, 7) == 'notify:') {
                    dw.backend.notify(evt.data.slice(7));
                }
                if (evt.data == 'datawrapper:vis:rendered') {
                    dw.backend.fire('vis-rendered');
                }
            }
        });
    }

    /*
     * called as soon the vis is rendered (after iframe reload)
     */
    function visualizationRendered() {
        checkChartHeight();
        enableInlineEditing(iframe, chart);
        if (initHighlightSeries) initHighlightSeries();
    }

    /*
     * reload the chart specific options
     */
    function loadOptions() {
        var loaded = $.Deferred();
        _optionsSynchronized = false;
        $('#vis-options').load(
            '/xhr/'+chart.get('id')+'/vis-options?nocache='+Math.random(),
            function() {
                loaded.resolve();
                loadVis();
            }
        );
        return loaded.promise();
    }

    function initTransposeLink() {
        $('#btn-transpose').click(function(e) {
            e.preventDefault();
            chart.set('metadata.data.transpose', !chart.get('metadata.data.transpose'));
            chart.load().done(onDatasetLoaded);
            setTimeout(function() {
                loadOptions();
            }, 2000);
        });
    }

    function initVisSelector() {
        // graphical vis selector
        var unfolded = $('.vis-selector-unfolded'),
            folded = $('.vis-selector-folded'),
            thumbs = $('.vis-thumb'),
            selVis = $('.vis-selected');
        unfolded.show().data('h', unfolded.height()).hide();
        thumbs.click(function(e) {
            var thumb = $(e.target);
            if (!thumb.hasClass('vis-thumb')) thumb = thumb.parents('.vis-thumb');
            thumbs.removeClass('active');
            thumb.addClass('active');
            selVis.html('' + thumb.data('title'));
            setTimeout(function() {
                /*folded.show();
                unfolded.animate({ height: 0 }, 300, 'easeOutExpo', function() {
                    unfolded.hide();
                });*/
                chart.set('type', thumb.data('id'));
            }, 100);
        });

        folded.click(function() {
            folded.hide();
            unfolded.height(0).show().animate({ height: unfolded.data('h') }, 300);
        });

        unfolded.show();
        folded.hide();
    }

    function initResizeChart() {
        $('.resize-chart a').click(function(e) {
            e.preventDefault();
            var dim = $(e.target).html().split('×');
            $('#resize-w').val(dim[0]);
            $('#resize-h').val(dim[1]);
            updateSize(dim[0], dim[1]);
        });
    }

    function initChartSize() {
        var cw = chart.get('metadata.publish.embed-width', $('#iframe-wrapper').width()),
            ch = chart.get('metadata.publish.embed-height', $('#iframe-wrapper').height());
        $('#resize-w').val(cw);
        $('#resize-h').val(ch);
        $('.resize-chart input').change(_updateSize);
        $('#iframe-wrapper').width(cw);
        $('#iframe-wrapper').height(ch);
    }

    function scheduleThumbnail() {
        clearTimeout(__thumbTimer);
        __thumbTimer = setTimeout(function() {
            dw.backend.snapshot(iframe, dw.backend.currentChart.get('id'), 'm', 260, 160);
        }, 1500);
    }

    function onDatasetLoaded() {
        dw.backend.fire('dataset-loaded');
        loadVis();
        if (initHighlightSeries) initHighlightSeries();
        _.each(themes.all(), function(theme) {
            if (theme.id == chart.get('theme')) {
                var w = chart.get('metadata.publish.embed-width', theme.default_width || 560),
                    h = chart.get('metadata.publish.embed-height', theme.default_height || 400);
                updateSize(w, h);
                return false;
            }
        });
        themes.load();
    }

    /** Set into `dw.backend.currentVis` the edited visualization (editor side) */
    function loadVis() {
        if (iframe.attr('src') === "") {
            // load vis in iframe if not done yet
            iframe.attr('src', '/chart/'+chart.get('id')+'/preview?innersvg=1&random='+Math.floor(Math.random()*100000));
        }
        dw.backend.currentVis = dw.visualization(chart.get('type'));
        dw.backend.currentVis.chart(chart);
        dw.backend.currentVis.dataset = chart.dataset().reset();
        dw.backend.currentVis.meta = visMetas[chart.get('type')];
        options.init(chart, visMetas[chart.get('type')]);
        if (!_optionsSynchronized) {
            _optionsSynchronized = true;
            options.sync();
        }
        loadVisDfd.resolve();
    }

    function updateVisBackground() {  // and show msg if chart needs more space
        var iframe = $('#iframe-vis').contents(),
            bgcol =  $('body', iframe).css('background-color'),
            white = bgcol == 'rgb(255, 255, 255)' || bgcol == '#ffffff' || bgcol == 'white' || bgcol == 'transparent',
            border = white ? '#ffffff' : '#bbb';

        bgcol = dw.backend.currentChart.get('metadata.publish.contextBg') || dw.backend.currentChart.get('metadata.publish.background');

        $('#iframe-wrapper').css({
            'background-color': white ? '#ffffff' : bgcol,
            'border-color': border
        });
    }

    // chart resizing
    function _updateSize() {
        clearTimeout(__updateSizeTimer);
        __updateSizeTimer = setTimeout(updateSize, 300);
    }

    return {
        init: init
    };

});<|endoftext|>


<commit_before>import assert from 'assert';
import democase from '../lib';

describe('democase', function () {
  it('should have unit test!', function () {
    assert(false, 'we expected this package author to add actual unit tests.');
  });
});
<commit_msg>make the dummy test case pass<commit_after>import assert from 'assert';
import democase from '../lib';

describe('democase', function () {
  it('should be defined', function () {
    assert(democase);
  });
});
<|endoftext|>