<commit_before>var template = '<form id="form{ID}" action="./" class="ch-form">
Test {ID}<input id="autoComplete{ID}" type="text">

<input type="submit" class="ch-btn">
</form>',
    idGenerator = (function(){
        var count = 0;

        return function(){
            return count++;
        }
    }()),
    getSnippet = function(selector){
        var n = idGenerator();
        var f = $(template.replace(/{ID}/g, n));
        var snippet = f.find(selector + n);
        $('body').prepend(f);
        return snippet;
    },
    suggestions = ['Aruba', 'Armenia', 'Argentina'],
    suggestionsHTML = ['Argentina', 'Armenia', 'Aruba'],
    autoComplete = getSnippet('#autoComplete').autocomplete({'fx': 'none'}),
    autoCompleteHTML = getSnippet('#autoComplete').autocomplete({'html': true}),
    readyEvent = jasmine.createSpy('readyEvent'),
    hideEvent = jasmine.createSpy('hideEvent'),
    typingEvent = jasmine.createSpy('typingEvent');

    autoComplete
        .on('type', function () {
            typingEvent();
            autoComplete.suggest(suggestions);
        })
        .on('ready', function () { readyEvent(); })
        ._el.value = 'ar';

    autoCompleteHTML
        .on('type', function () {
            autoCompleteHTML.suggest(suggestionsHTML);
        })
        ._el.value = 'ar';

describe('ch.Autocomplete', function () {

    it('should be defined in ch object', function () {
        expect(ch.hasOwnProperty('Autocomplete')).toBeTruthy();
        expect(typeof ch.Autocomplete).toEqual('function');
    });

    it('should be defined in $ object', function () {
        expect($.fn.hasOwnProperty('autocomplete')).toBeTruthy();
        expect(typeof ch.Autocomplete).toEqual('function');
    });

    it('should be return a new instance', function () {
        expect(autoComplete instanceof ch.Autocomplete).toBeTruthy();
    });

    it('should emit the "ready" event when it\'s created', function () {
        waits(50);
        runs(function () {
            expect(readyEvent).toHaveBeenCalled();
        });
    });

    describe('should use the following abilities:', function () {
        it('EventEmitter', function () {
            expect(autoComplete.on).not.toEqual(undefined);
            expect(typeof autoComplete.on).toEqual('function');
        });

        it('Popover', function () {
            expect(autoComplete._popover).not.toEqual(undefined);
            expect(autoComplete._popover instanceof ch.Popover).toBeTruthy();
        });
    });

});

describe('It should have the following public properties:', function () {

    it('._el', function () {
        expect(autoComplete._el).not.toEqual(undefined);
        expect(autoComplete._el.nodeType).toEqual(1);
        expect(autoComplete._el instanceof HTMLInputElement).toBeTruthy();
    });

    it('.$trigger', function () {
        expect(autoComplete.$trigger).not.toEqual(undefined);
        expect(autoComplete.$trigger instanceof $).toBeTruthy();
    });

    it('.name', function () {
        expect(autoComplete.name).not.toEqual(undefined);
        expect(typeof autoComplete.name).toEqual('string');
        expect(autoComplete.name).toEqual('autocomplete');
    });

    it('.constructor', function () {
        expect(autoComplete.constructor).not.toEqual(undefined);
        expect(typeof autoComplete.constructor).toEqual('function');
    });

    it('.uid', function () {
        expect(autoComplete.uid).not.toEqual(undefined);
        expect(typeof autoComplete.uid).toEqual('number');
    });

});

describe('It should have the following public methods:', function () {
    var methods = ['destroy', 'suggest', 'hide', 'isShown', 'enable', 'disable'],
        i = 0,
        len = methods.length;

    for (i; i < len; i += 1) {
        (function (i){
            it('.' + methods[i] + '()', function () {
                expect(autoComplete[methods[i]]).not.toEqual(undefined);
                expect(typeof autoComplete[methods[i]]).toEqual('function');
            });
        }(i));
    }
});

describe('The input element should have the following WAI-ARIA attributes', function () {
    var $input = autoComplete.$trigger,
        inputID = autoComplete.$container[0].id;

    it('"aria-haspopup" in "true"', function () {
       expect($input.attr('aria-haspopup')).toEqual('true');
    });

    it('"aria-autocomplete" in "list"', function () {
       expect($input.attr('aria-autocomplete')).toEqual('list');
    });

    it('"aria-owns" in "' + inputID + '"', function () {
       expect($input.attr('aria-owns')).toEqual(inputID);
    });

});

describe('It should have a "$container" property and', function () {
    var $container = autoComplete.$container;

    it('should exist', function () {
        expect($container).not.toEqual(undefined);
        expect($container[0].nodeType).toEqual(1);
        expect($container instanceof $).toBeTruthy();
    });

    it('should have the ".ch-autocomplete" class name ', function () {
        expect($container.hasClass('ch-autocomplete')).toBeTruthy();
    });

    it('should be hidden', function () {
        expect($container.hasClass('ch-hide')).toBeTruthy();
        expect($container[0].getAttribute('aria-hidden')).toBeTruthy('true');
    });

    it('should have the WAI-ARIA attribute "role" in "dialog"', function () {
        expect($container.attr('role')).toEqual('dialog');
    });

});

describe('It should emits typing event and',function(){
    autoComplete._el.focus();

    autoComplete.emit('type', autoComplete._el.value);

    it('should trigger the callback function', function () {
        expect(typingEvent).toHaveBeenCalled();
    });

});

describe('Its suggest() method', function () {

    describe('shows the suggetion list', function () {
        var itemsHighilighted,
            $suggestionList;

        it('open when suggestions are given', function () {
            autoComplete._el.focus();
            autoComplete.emit('type', autoComplete._el.value);
            expect(autoComplete.isShown()).toBeTruthy();
        });

        it('should have hightlighted items', function () {
            autoComplete._el.focus();
            autoComplete.emit('type', autoComplete._el.value);
            itemsHighilighted = autoComplete.$container.find('strong').length;
            expect(itemsHighilighted).toEqual(3);
        });

        it('should show the same number of items as suggestions array have', function () {
            itemsHighilighted = autoComplete.$container.find('.ch-autocomplete-item').length;
            expect(suggestions.length).toEqual(3);
        });

        it('should close the suggestion list if there is no results', function () {
            autoComplete.suggest([]);
            expect(autoComplete.isShown()).toBeFalsy();
        });

    });

});

describe('Its hide() method', function () {
    var $container = autoComplete.$container,
        instance;

        autoComplete.on('hide', function () { hideEvent(); })

    it('should add "ch-hide" class name to container', function () {
        instance = autoComplete.hide();
        expect($container.hasClass('ch-hide')).toBeTruthy();
    });

    it('should update the WAI-ARIA attribute "aria-hidden" to "true" on container', function () {
        expect($container.attr('aria-hidden')).toEqual('true');
    });

    it('should emit the "hide" event', function () {
        expect(hideEvent).toHaveBeenCalled();
    });

    it('should return the same instance than initialized component', function () {
        expect(instance).toEqual(autoComplete);
    });

});

describe('Its isShown() method', function () {
    var isShown;

    it('should return "true" when the component is shown', function () {
        autoComplete._el.focus();
        autoComplete.emit('type', autoComplete._el.value);
        isShown = autoComplete.isShown();

        expect(typeof isShown).toEqual('boolean');
        expect(isShown).toBeTruthy();
    });

    it('should return "false" when the component is hidden', function () {
        autoComplete.hide();
        isShown = autoComplete.isShown();

        expect(typeof isShown).toEqual('boolean');
        expect(isShown).toBeFalsy();
    });

    autoComplete.hide();
});

describe('Its disable() method', function () {
    var instance,
        isShown;

    it('should prevent to suggest', function () {
        autoComplete._el.focus();
        autoComplete.emit('type', autoComplete._el.value);
        instance = autoComplete.disable();
        expect(autoComplete.isShown()).toBeFalsy();
    });

    it('should return the same instance than initialized component', function () {
        expect(instance).toEqual(autoComplete);
    });
});

describe('Its enable() method', function () {
    var instance,
        isShown;

    it('should suggest', function () {
        instance = autoComplete.enable();
        autoComplete._el.focus();
        autoComplete.emit('type', autoComplete._el.value);
        expect(autoComplete.isShown()).toBeTruthy();
    });

    it('should return the same instance than initialized component', function () {
        expect(instance).toEqual(autoComplete);
    });

});

describe('Instance an AutoComplete configured to show HTML', function () {

    it('should return the items with the HTML sent', function () {

        autoCompleteHTML._el.focus();
        autoCompleteHTML.emit('type', autoCompleteHTML._el.value);

        // this wait is for the focu
        waits(300);
        runs(function () {
            var itemAdded = autoCompleteHTML.$container[0].querySelector('.ch-autocomplete-item .HTMLAdded');
            expect(itemAdded.nodeType).toEqual(1);
        });

    });

});

describe('Its destroy() method', function () {

    it('should reset the $trigger', function () {
        autoComplete.destroy();
        expect(autoComplete.$trigger.attr('aria-haspopup')).toBeUndefined();
        expect(autoComplete.$trigger.attr('aria-owns')).toBeUndefined();
        expect(autoComplete.$trigger.attr('aria-autocomplete')).toBeUndefined();
    });

    it('should remove ".autocomplete" events', function () {
        expect($._data(autoComplete.$trigger[0], 'events')).toBeUndefined();
    });

    it('should remove the instance from the element', function () {
        expect(autoComplete._$el.data('autoComplete')).toBeUndefined();
    });

});
<commit_msg>#987 Autocomplete test fixed<commit_after>var template = '<form id="form{ID}" action="./" class="ch-form">
Test {ID}<input id="autoComplete{ID}" type="text">

<input type="submit" class="ch-btn">
</form>',
    idGenerator = (function(){
        var count = 0;

        return function(){
            return count++;
        }
    }()),
    getSnippet = function(selector){
        var n = idGenerator();
        var f = $(template.replace(/{ID}/g, n));
        var snippet = f.find(selector + n);
        $('body').prepend(f);
        return snippet;
    },
    suggestions = ['Aruba', 'Armenia', 'Argentina'],
    suggestionsHTML = ['Argentina', 'Armenia', 'Aruba'],
    autoComplete = getSnippet('#autoComplete').autocomplete({'fx': 'none'}),
    autoCompleteHTML = getSnippet('#autoComplete').autocomplete({'html': true}),
    readyEvent = jasmine.createSpy('readyEvent'),
    hideEvent = jasmine.createSpy('hideEvent'),
    typingEvent = jasmine.createSpy('typingEvent');

    autoComplete
        .on('type', function () {
            typingEvent();
            autoComplete.suggest(suggestions);
        })
        .on('ready', function () { readyEvent(); })
        ._el.value = 'ar';

    autoCompleteHTML
        .on('type', function () {
            autoCompleteHTML.suggest(suggestionsHTML);
        })
        ._el.value = 'ar';

describe('ch.Autocomplete', function () {

    it('should be defined in ch object', function () {
        expect(ch.hasOwnProperty('Autocomplete')).toBeTruthy();
        expect(typeof ch.Autocomplete).toEqual('function');
    });

    it('should be defined in $ object', function () {
        expect($.fn.hasOwnProperty('autocomplete')).toBeTruthy();
        expect(typeof ch.Autocomplete).toEqual('function');
    });

    it('should be return a new instance', function () {
        expect(autoComplete instanceof ch.Autocomplete).toBeTruthy();
    });

    it('should emit the "ready" event when it\'s created', function () {
        waits(50);
        runs(function () {
            expect(readyEvent).toHaveBeenCalled();
        });
    });

    describe('should use the following abilities:', function () {
        it('EventEmitter', function () {
            expect(autoComplete.on).not.toEqual(undefined);
            expect(typeof autoComplete.on).toEqual('function');
        });

        it('Popover', function () {
            expect(autoComplete._popover).not.toEqual(undefined);
            expect(autoComplete._popover instanceof ch.Popover).toBeTruthy();
        });
    });

});

describe('It should have the following public properties:', function () {

    it('._el', function () {
        expect(autoComplete._el).not.toEqual(undefined);
        expect(autoComplete._el.nodeType).toEqual(1);
        expect(autoComplete._el instanceof HTMLInputElement).toBeTruthy();
    });

    it('.$trigger', function () {
        expect(autoComplete.$trigger).not.toEqual(undefined);
        expect(autoComplete.$trigger instanceof $).toBeTruthy();
    });

    it('.name', function () {
        expect(autoComplete.name).not.toEqual(undefined);
        expect(typeof autoComplete.name).toEqual('string');
        expect(autoComplete.name).toEqual('autocomplete');
    });

    it('.constructor', function () {
        expect(autoComplete.constructor).not.toEqual(undefined);
        expect(typeof autoComplete.constructor).toEqual('function');
    });

    it('.uid', function () {
        expect(autoComplete.uid).not.toEqual(undefined);
        expect(typeof autoComplete.uid).toEqual('number');
    });

});

describe('It should have the following public methods:', function () {
    var methods = ['destroy', 'suggest', 'hide', 'isShown', 'enable', 'disable'],
        i = 0,
        len = methods.length;

    for (i; i < len; i += 1) {
        (function (i){
            it('.' + methods[i] + '()', function () {
                expect(autoComplete[methods[i]]).not.toEqual(undefined);
                expect(typeof autoComplete[methods[i]]).toEqual('function');
            });
        }(i));
    }
});

describe('The input element should have the following WAI-ARIA attributes', function () {
    var $input = autoComplete.$trigger,
        inputID = autoComplete.$container[0].id;

    it('"aria-haspopup" in "true"', function () {
       expect($input.attr('aria-haspopup')).toEqual('true');
    });

    it('"aria-autocomplete" in "list"', function () {
       expect($input.attr('aria-autocomplete')).toEqual('list');
    });

    it('"aria-owns" in "' + inputID + '"', function () {
       expect($input.attr('aria-owns')).toEqual(inputID);
    });

});

describe('It should have a "$container" property and', function () {
    var $container = autoComplete.$container;

    it('should exist', function () {
        expect($container).not.toEqual(undefined);
        expect($container[0].nodeType).toEqual(1);
        expect($container instanceof $).toBeTruthy();
    });

    it('should have the ".ch-autocomplete" class name ', function () {
        expect($container.hasClass('ch-autocomplete')).toBeTruthy();
    });

    it('should be hidden', function () {
        expect($container.hasClass('ch-hide')).toBeTruthy();
        expect($container[0].getAttribute('aria-hidden')).toBeTruthy('true');
    });

    it('should have the WAI-ARIA attribute "role" in "dialog"', function () {
        expect($container.attr('role')).toEqual('dialog');
    });

});

describe('It should emits typing event and',function(){
    autoComplete._el.focus();

    autoComplete.emit('type', autoComplete._el.value);

    it('should trigger the callback function', function () {
        expect(typingEvent).toHaveBeenCalled();
    });

});

describe('Its suggest() method', function () {

    describe('shows the suggetion list', function () {
        var itemsHighilighted,
            $suggestionList;

        it('open when suggestions are given', function () {
            autoComplete._el.focus();
            autoComplete.emit('type', autoComplete._el.value);
            expect(autoComplete.isShown()).toBeTruthy();
        });

        it('should have hightlighted keywords', function () {
            autoComplete._el.focus();
            autoComplete._currentQuery = 'ar';
            autoComplete.suggest(suggestions);
            itemsHighilighted = autoComplete.$container.find('strong').length;
            expect(itemsHighilighted).toEqual(3);
        });

        it('should show the same number of items as suggestions array have', function () {
            itemsHighilighted = autoComplete.$container.find('.ch-autocomplete-item').length;
            expect(suggestions.length).toEqual(3);
        });

        it('should close the suggestion list if there is no results', function () {
            autoComplete.suggest([]);
            expect(autoComplete.isShown()).toBeFalsy();
        });

    });

});

describe('Its hide() method', function () {
    var $container = autoComplete.$container,
        instance;

        autoComplete.on('hide', function () { hideEvent(); })

    it('should add "ch-hide" class name to container', function () {
        instance = autoComplete.hide();
        expect($container.hasClass('ch-hide')).toBeTruthy();
    });

    it('should update the WAI-ARIA attribute "aria-hidden" to "true" on container', function () {
        expect($container.attr('aria-hidden')).toEqual('true');
    });

    it('should emit the "hide" event', function () {
        expect(hideEvent).toHaveBeenCalled();
    });

    it('should return the same instance than initialized component', function () {
        expect(instance).toEqual(autoComplete);
    });

});

describe('Its isShown() method', function () {
    var isShown;

    it('should return "true" when the component is shown', function () {
        autoComplete._el.focus();
        autoComplete.emit('type', autoComplete._el.value);
        isShown = autoComplete.isShown();

        expect(typeof isShown).toEqual('boolean');
        expect(isShown).toBeTruthy();
    });

    it('should return "false" when the component is hidden', function () {
        autoComplete.hide();
        isShown = autoComplete.isShown();

        expect(typeof isShown).toEqual('boolean');
        expect(isShown).toBeFalsy();
    });

    autoComplete.hide();
});

describe('Its disable() method', function () {
    var instance,
        isShown;

    it('should prevent to suggest', function () {
        autoComplete._el.focus();
        autoComplete.emit('type', autoComplete._el.value);
        instance = autoComplete.disable();
        expect(autoComplete.isShown()).toBeFalsy();
    });

    it('should return the same instance than initialized component', function () {
        expect(instance).toEqual(autoComplete);
    });
});

describe('Its enable() method', function () {
    var instance,
        isShown;

    it('should suggest', function () {
        instance = autoComplete.enable();
        autoComplete._el.focus();
        autoComplete.emit('type', autoComplete._el.value);
        expect(autoComplete.isShown()).toBeTruthy();
    });

    it('should return the same instance than initialized component', function () {
        expect(instance).toEqual(autoComplete);
    });

});

describe('Instance an AutoComplete configured to show HTML', function () {

    it('should return the items with the HTML sent', function () {

        autoCompleteHTML._el.focus();
        autoCompleteHTML.emit('type', autoCompleteHTML._el.value);

        // this wait is for the focu
        waits(300);
        runs(function () {
            var itemAdded = autoCompleteHTML.$container[0].querySelector('.ch-autocomplete-item .HTMLAdded');
            expect(itemAdded.nodeType).toEqual(1);
        });

    });

});

describe('Its destroy() method', function () {

    it('should reset the $trigger', function () {
        autoComplete.destroy();
        expect(autoComplete.$trigger.attr('aria-haspopup')).toBeUndefined();
        expect(autoComplete.$trigger.attr('aria-owns')).toBeUndefined();
        expect(autoComplete.$trigger.attr('aria-autocomplete')).toBeUndefined();
    });

    it('should remove ".autocomplete" events', function () {
        expect($._data(autoComplete.$trigger[0], 'events')).toBeUndefined();
    });

    it('should remove the instance from the element', function () {
        expect(autoComplete._$el.data('autoComplete')).toBeUndefined();
    });

});
<|endoftext|>


<commit_before>/***
  ** Himle Client -- http://himle.org/
  **
  ** Copyright (C) 2008 Juha-Jarmo Heinonen
  **
  ** This file is part of Himle Client.
  **
  ** Himle Client is free software: you can redistribute it and/or modify
  ** it under the terms of the GNU General Public License as published by
  ** the Free Software Foundation, either version 3 of the License, or
  ** (at your option) any later version.
  **
  ** Himle Client is distributed in the hope that it will be useful,
  ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  ** GNU General Public License for more details.
  **
  ** You should have received a copy of the GNU General Public License
  ** along with this program.  If not, see <http://www.gnu.org/licenses/>.
  **
  ***/

/** class: HWindow
  *
  * Simple window component.
  *
  * Extends:
  *  <HDynControl>
  *
  * See Also:
  *  <HDynControl> <HControl> <HView>
  *
  **/
HWindow = HDynControl.extend({

  componentName:      'window',

  // HWindow has a few extra options, like the close/collapse/zoom buttons, see below
  constructor: function(_rect,_parentApp,_options){

    // the parent of HWindow has to be an HApplication instance
    if(_parentApp.componentBehaviour[0]!='app'){
      throw( "Himle.ComponentParentError: HWindow parent must be an HApplication instance!" );
    }

    if(!_options) {
      _options={};
    }

    var _defaults = HClass.extend({
      minSize:   [96,54],
      maxSize:   [16000,9000],
      resizeW:   4,
      resizeE:   4,
      resizeN:   4,
      resizeS:   4,
      resizeNW:  [ 6, 6 ],
      resizeNE:  [ 6, 6 ],
      resizeSW:  [ 6, 6 ],
      resizeSE:  [ 16, 16 ],
      noResize:  false,

      // set to true, if you want a close box for the window
      closeButton: false,

      // set to true, if you want a collapse (minimize) button for the window
      collapseButton: false,

      // set to true, if you want a zoom (maximize/restore) button for the window
      zoomButton: false
    });
    _options = new (_defaults.extend(_options))();
    if(_options.noResize){
      _options.minSize = [_rect.width,_rect.height];
      _options.maxSize = [_rect.width,_rect.height];
      _options.resizeW = 0;
      resizeE = 0;
      resizeN = 0;
      resizeS = 0;
      resizeNW = [0,0];
      resizeNE = [0,0];
      resizeSW = [0,0];
      resizeSE = [0,0];
    }
    this.base(_rect,_parentApp,_options);
    HSystem.windowFocus(this);
  },

  // Reports to HSystem that this window has the focus and the previously active window needs to blur
  gainedActiveStatus: function(){
    HSystem.windowFocus(this);
  },

  // HSystem calls this method, whenever this window is allowed to be focused
  windowFocus: function(){
    this.toggleCSSClass(this.elemId, 'inactive', false);
    this.setStyle('cursor','move');
  },

  // HSystem calls this method, whenever this window needs to lose its focus (another window focused)
  windowBlur: function(){
    this.toggleCSSClass(this.elemId, 'inactive', true);
    this.setStyle('cursor','default');
  },

  // This method gets called, whenever the close button has been clicked
  windowClose: function(){
    this.die(); // extend this to this.app.die(), if your app needs to die instead of just the window
  },

  // This method gets called, whenever the collapse (minimize) button has been clicked
  windowCollapse: function(){
    // extend with your app-specific behaviour
  },

  // This method gets called, whenever the zoom (maximize/restore) button has been clicked
  windowZoom: function(){
    // extend with your app-specific behaviour
  }
});

<commit_msg>improved window behaviour, bugfix<commit_after>/***
  ** Himle Client -- http://himle.org/
  **
  ** Copyright (C) 2008 Juha-Jarmo Heinonen
  **
  ** This file is part of Himle Client.
  **
  ** Himle Client is free software: you can redistribute it and/or modify
  ** it under the terms of the GNU General Public License as published by
  ** the Free Software Foundation, either version 3 of the License, or
  ** (at your option) any later version.
  **
  ** Himle Client is distributed in the hope that it will be useful,
  ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  ** GNU General Public License for more details.
  **
  ** You should have received a copy of the GNU General Public License
  ** along with this program.  If not, see <http://www.gnu.org/licenses/>.
  **
  ***/

/** class: HWindow
  *
  * Simple window component.
  *
  * Extends:
  *  <HDynControl>
  *
  * See Also:
  *  <HDynControl> <HControl> <HView>
  *
  **/
HWindow = HDynControl.extend({

  componentName:      'window',

  // HWindow has a few extra options, like the close/collapse/zoom buttons, see below
  constructor: function(_rect,_parentApp,_options){

    // the parent of HWindow has to be an HApplication instance
    if(_parentApp.componentBehaviour[0]!='app'){
      throw( "Himle.ComponentParentError: HWindow parent must be an HApplication instance!" );
    }

    if(!_options) {
      _options={};
    }

    var _defaults = HClass.extend({
      minSize:   [96,54],
      maxSize:   [16000,9000],
      resizeW:   4,
      resizeE:   4,
      resizeN:   4,
      resizeS:   4,
      resizeNW:  [ 6, 6 ],
      resizeNE:  [ 6, 6 ],
      resizeSW:  [ 6, 6 ],
      resizeSE:  [ 16, 16 ],
      noResize:  false,

      // set to true, if you want a close box for the window
      closeButton: false,

      // set to true, if you want a collapse (minimize) button for the window
      collapseButton: false,

      // set to true, if you want a zoom (maximize/restore) button for the window
      zoomButton: false
    });
    _options = new (_defaults.extend(_options))();
    if(_options.noResize){
      _options.minSize = [_rect.width,_rect.height];
      _options.maxSize = [_rect.width,_rect.height];
      _options.resizeW = 0;
      resizeE = 0;
      resizeN = 0;
      resizeS = 0;
      resizeNW = [0,0];
      resizeNE = [0,0];
      resizeSW = [0,0];
      resizeSE = [0,0];
    }
    this.base(_rect,_parentApp,_options);
    HSystem.windowFocus(this);
  },

  // Reports to HSystem that this window has the focus and the previously active window needs to blur
  gainedActiveStatus: function(){
    HSystem.windowFocus(this);
  },

  // HSystem calls this method, whenever this window is allowed to be focused
  windowFocus: function(){
    this.toggleCSSClass(this.elemId, 'inactive', false);
  },

  // HSystem calls this method, whenever this window needs to lose its focus (another window focused)
  windowBlur: function(){
    this.toggleCSSClass(this.elemId, 'inactive', true);
    this.setStyle('cursor','default');
  },

  // This method gets called, whenever the close button has been clicked
  windowClose: function(){
    this.die(); // extend this to this.app.die(), if your app needs to die instead of just the window
  },

  // This method gets called, whenever the collapse (minimize) button has been clicked
  windowCollapse: function(){
    // extend with your app-specific behaviour
  },

  // This method gets called, whenever the zoom (maximize/restore) button has been clicked
  windowZoom: function(){
    // extend with your app-specific behaviour
  }
});

<|endoftext|>


<commit_before>var should = require('should'),
    _ = require('lodash'),
    supertest = require('supertest'),
    os = require('os'),
    fs = require('fs-extra'),
    testUtils = require('../../../utils'),
    config = require('../../../../../core/server/config'),
    ghost = testUtils.startGhost,
    request;

describe('Settings API', function () {
    var accesstoken = '', ghostServer;

    before(function () {
        return ghost()
            .then(function (_ghostServer) {
                ghostServer = _ghostServer;
                request = supertest.agent(config.get('url'));
            })
            .then(function () {
                return testUtils.doAuth(request);
            })
            .then(function (token) {
                accesstoken = token;
            });
    });

    // TODO: currently includes values of type=core
    it('can retrieve all settings', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(200)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                should.not.exist(res.headers['x-cache-invalidate']);
                var jsonResponse = res.body;
                should.exist(jsonResponse);

                testUtils.API.checkResponse(jsonResponse, 'settings');

                JSON.parse(_.find(jsonResponse.settings, {key: 'unsplash'}).value).isActive.should.eql(true);
                JSON.parse(_.find(jsonResponse.settings, {key: 'amp'}).value).should.eql(true);

                done();
            });
    });

    it('can retrieve a setting', function (done) {
        request.get(testUtils.API.getApiQuery('settings/title/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(200)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                should.not.exist(res.headers['x-cache-invalidate']);
                var jsonResponse = res.body;

                should.exist(jsonResponse);
                should.exist(jsonResponse.settings);

                testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'key', 'value', 'type', 'created_at', 'created_by', 'updated_at', 'updated_by']);
                jsonResponse.settings[0].key.should.eql('title');
                testUtils.API.isISO8601(jsonResponse.settings[0].created_at).should.be.true();
                done();
            });
    });

    it('can\'t retrieve non existent setting', function (done) {
        request.get(testUtils.API.getApiQuery('settings/testsetting/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(404)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                should.not.exist(res.headers['x-cache-invalidate']);
                var jsonResponse = res.body;
                should.exist(jsonResponse);
                should.exist(jsonResponse.errors);
                testUtils.API.checkResponseValue(jsonResponse.errors[0], ['message', 'errorType']);
                done();
            });
    });

    it('can edit settings', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                var jsonResponse = res.body,
                    changedValue = 'Ghost changed',
                    settingToChange = {
                        settings: [
                            {key: 'title', value: changedValue}
                        ]
                    };

                should.exist(jsonResponse);
                should.exist(jsonResponse.settings);

                request.put(testUtils.API.getApiQuery('settings/'))
                    .set('Authorization', 'Bearer ' + accesstoken)
                    .send(settingToChange)
                    .expect('Content-Type', /json/)
                    .expect('Cache-Control', testUtils.cacheRules.private)
                    .expect(200)
                    .end(function (err, res) {
                        if (err) {
                            return done(err);
                        }

                        var putBody = res.body;
                        res.headers['x-cache-invalidate'].should.eql('/*');
                        should.exist(putBody);
                        putBody.settings[0].value.should.eql(changedValue);
                        testUtils.API.checkResponse(putBody, 'settings');
                        done();
                    });
            });
    });

    it('can\'t edit settings with invalid accesstoken', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                var jsonResponse = res.body,
                    changedValue = 'Ghost changed';
                should.exist(jsonResponse);
                jsonResponse.title = changedValue;

                request.put(testUtils.API.getApiQuery('settings/'))
                    .set('Authorization', 'Bearer ' + 'invalidtoken')
                    .send(jsonResponse)
                    .expect(401)
                    .end(function (err) {
                        if (err) {
                            return done(err);
                        }

                        done();
                    });
            });
    });

    it('can\'t edit non existent setting', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                var jsonResponse = res.body,
                    newValue = 'new value';
                should.exist(jsonResponse);
                should.exist(jsonResponse.settings);
                jsonResponse.settings = [{key: 'testvalue', value: newValue}];

                request.put(testUtils.API.getApiQuery('settings/'))
                    .set('Authorization', 'Bearer ' + accesstoken)
                    .send(jsonResponse)
                    .expect('Content-Type', /json/)
                    .expect('Cache-Control', testUtils.cacheRules.private)
                    .expect(404)
                    .end(function (err, res) {
                        if (err) {
                            return done(err);
                        }

                        jsonResponse = res.body;
                        should.not.exist(res.headers['x-cache-invalidate']);
                        should.exist(jsonResponse.errors);
                        testUtils.API.checkResponseValue(jsonResponse.errors[0], ['message', 'errorType']);
                        done();
                    });
            });
    });

    it('can download routes.yaml', ()=> {
        return request.get(testUtils.API.getApiQuery('settings/routes/yaml/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/yaml')
            .expect(200)
            .then((res)=> {
                res.headers['content-disposition'].should.eql('Attachment; filename="routes.yaml"');
                res.headers['content-type'].should.eql('application/yaml; charset=utf-8');
                res.headers['content-length'].should.eql('152');
            });
    });

    it('can upload routes.yaml', ()=> {
        const newRoutesYamlPath = `${os.tmpdir()}routes.yaml`;

        return fs.writeFile(newRoutesYamlPath, 'routes:\ncollections:\ntaxonomies:\n')
            .then(()=> {
                return request
                    .post(testUtils.API.getApiQuery('settings/routes/yaml/'))
                    .set('Authorization', 'Bearer ' + accesstoken)
                    .set('Origin', testUtils.API.getURL())
                    .attach('routes', newRoutesYamlPath)
                    .expect('Content-Type', /application\/json/)
                    .expect(200);
            })
            .then((res)=> {
                res.headers['x-cache-invalidate'].should.eql('/*');
            })
            .finally(()=> {
                return ghostServer.stop();
            });
    });
});
<commit_msg>Fixed travis builds<commit_after>var should = require('should'),
    _ = require('lodash'),
    supertest = require('supertest'),
    os = require('os'),
    fs = require('fs-extra'),
    testUtils = require('../../../utils'),
    config = require('../../../../../core/server/config'),
    ghost = testUtils.startGhost,
    request;

describe('Settings API', function () {
    var accesstoken = '', ghostServer;

    before(function () {
        return ghost()
            .then(function (_ghostServer) {
                ghostServer = _ghostServer;
                request = supertest.agent(config.get('url'));
            })
            .then(function () {
                return testUtils.doAuth(request);
            })
            .then(function (token) {
                accesstoken = token;
            });
    });

    // TODO: currently includes values of type=core
    it('can retrieve all settings', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(200)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                should.not.exist(res.headers['x-cache-invalidate']);
                var jsonResponse = res.body;
                should.exist(jsonResponse);

                testUtils.API.checkResponse(jsonResponse, 'settings');

                JSON.parse(_.find(jsonResponse.settings, {key: 'unsplash'}).value).isActive.should.eql(true);
                JSON.parse(_.find(jsonResponse.settings, {key: 'amp'}).value).should.eql(true);

                done();
            });
    });

    it('can retrieve a setting', function (done) {
        request.get(testUtils.API.getApiQuery('settings/title/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(200)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                should.not.exist(res.headers['x-cache-invalidate']);
                var jsonResponse = res.body;

                should.exist(jsonResponse);
                should.exist(jsonResponse.settings);

                testUtils.API.checkResponseValue(jsonResponse.settings[0], ['id', 'key', 'value', 'type', 'created_at', 'created_by', 'updated_at', 'updated_by']);
                jsonResponse.settings[0].key.should.eql('title');
                testUtils.API.isISO8601(jsonResponse.settings[0].created_at).should.be.true();
                done();
            });
    });

    it('can\'t retrieve non existent setting', function (done) {
        request.get(testUtils.API.getApiQuery('settings/testsetting/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(404)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                should.not.exist(res.headers['x-cache-invalidate']);
                var jsonResponse = res.body;
                should.exist(jsonResponse);
                should.exist(jsonResponse.errors);
                testUtils.API.checkResponseValue(jsonResponse.errors[0], ['message', 'errorType']);
                done();
            });
    });

    it('can edit settings', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                var jsonResponse = res.body,
                    changedValue = 'Ghost changed',
                    settingToChange = {
                        settings: [
                            {key: 'title', value: changedValue}
                        ]
                    };

                should.exist(jsonResponse);
                should.exist(jsonResponse.settings);

                request.put(testUtils.API.getApiQuery('settings/'))
                    .set('Authorization', 'Bearer ' + accesstoken)
                    .send(settingToChange)
                    .expect('Content-Type', /json/)
                    .expect('Cache-Control', testUtils.cacheRules.private)
                    .expect(200)
                    .end(function (err, res) {
                        if (err) {
                            return done(err);
                        }

                        var putBody = res.body;
                        res.headers['x-cache-invalidate'].should.eql('/*');
                        should.exist(putBody);
                        putBody.settings[0].value.should.eql(changedValue);
                        testUtils.API.checkResponse(putBody, 'settings');
                        done();
                    });
            });
    });

    it('can\'t edit settings with invalid accesstoken', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                var jsonResponse = res.body,
                    changedValue = 'Ghost changed';
                should.exist(jsonResponse);
                jsonResponse.title = changedValue;

                request.put(testUtils.API.getApiQuery('settings/'))
                    .set('Authorization', 'Bearer ' + 'invalidtoken')
                    .send(jsonResponse)
                    .expect(401)
                    .end(function (err) {
                        if (err) {
                            return done(err);
                        }

                        done();
                    });
            });
    });

    it('can\'t edit non existent setting', function (done) {
        request.get(testUtils.API.getApiQuery('settings/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .end(function (err, res) {
                if (err) {
                    return done(err);
                }

                var jsonResponse = res.body,
                    newValue = 'new value';
                should.exist(jsonResponse);
                should.exist(jsonResponse.settings);
                jsonResponse.settings = [{key: 'testvalue', value: newValue}];

                request.put(testUtils.API.getApiQuery('settings/'))
                    .set('Authorization', 'Bearer ' + accesstoken)
                    .send(jsonResponse)
                    .expect('Content-Type', /json/)
                    .expect('Cache-Control', testUtils.cacheRules.private)
                    .expect(404)
                    .end(function (err, res) {
                        if (err) {
                            return done(err);
                        }

                        jsonResponse = res.body;
                        should.not.exist(res.headers['x-cache-invalidate']);
                        should.exist(jsonResponse.errors);
                        testUtils.API.checkResponseValue(jsonResponse.errors[0], ['message', 'errorType']);
                        done();
                    });
            });
    });

    it('can download routes.yaml', ()=> {
        return request.get(testUtils.API.getApiQuery('settings/routes/yaml/'))
            .set('Authorization', 'Bearer ' + accesstoken)
            .set('Accept', 'application/yaml')
            .expect(200)
            .then((res)=> {
                res.headers['content-disposition'].should.eql('Attachment; filename="routes.yaml"');
                res.headers['content-type'].should.eql('application/yaml; charset=utf-8');
                res.headers['content-length'].should.eql('152');
            });
    });

    it('can upload routes.yaml', ()=> {
        const newRoutesYamlPath = `${os.tmpdir()}/routes.yaml`;

        return fs.writeFile(newRoutesYamlPath, 'routes:\ncollections:\ntaxonomies:\n')
            .then(()=> {
                return request
                    .post(testUtils.API.getApiQuery('settings/routes/yaml/'))
                    .set('Authorization', 'Bearer ' + accesstoken)
                    .set('Origin', testUtils.API.getURL())
                    .attach('routes', newRoutesYamlPath)
                    .expect('Content-Type', /application\/json/)
                    .expect(200);
            })
            .then((res)=> {
                res.headers['x-cache-invalidate'].should.eql('/*');
            })
            .finally(()=> {
                return ghostServer.stop();
            });
    });
});
<|endoftext|>


<commit_before>angular.module('materialscommons').factory('toUITask', toUITaskService);

/*@ngInject*/
function toUITaskService() {
    return function(task) {
        task.displayState = {
            details: {
                showNotes: true,
                showFiles: false,
                showSamples: false,
                currentFilesTab: 0,
                currentSamplesTab: 0,
                loadEditor: false
            },
            flags: {
                starredClass: task.flags.starred ? 'fa-star' : 'fa-star-o',
                flaggedClass: task.flags.flagged ? 'mc-flagged-color' : 'mc-flag-not-set'
            },
            selectedClass: '',
            editTitle: true,
            open: false,
            maximize: false
        };
        task.node = null;
    }
}<commit_msg>Set loaded flag on a task to false. Only load the task template if the task is clicked on (preloading the templates for all tasks is an expensive operation when there are a decent (20+) number of tasks).<commit_after>angular.module('materialscommons').factory('toUITask', toUITaskService);

/*@ngInject*/
function toUITaskService() {
    return function(task) {
        task.displayState = {
            details: {
                showNotes: true,
                showFiles: false,
                showSamples: false,
                currentFilesTab: 0,
                currentSamplesTab: 0,
                loadEditor: false
            },
            flags: {
                starredClass: task.flags.starred ? 'fa-star' : 'fa-star-o',
                flaggedClass: task.flags.flagged ? 'mc-flagged-color' : 'mc-flag-not-set'
            },
            selectedClass: '',
            editTitle: true,
            open: false,
            maximize: false
        };
        task.loaded = false;
        task.node = null;
    }
}<|endoftext|>


<commit_before>'use strict';

module.exports = function($scope, $http, $uibModalInstance, formBuilder, fusio) {

  $scope.action = {
    name: "",
    class: "",
    config: {}
  };
  $scope.elements = [];
  $scope.config = {};
  $scope.actions = [];

  $scope.create = function(action) {
    var data = angular.copy(action);

    if (angular.isObject($scope.config)) {
      data.config = formBuilder.postProcessModel($scope.config, $scope.elements);
    }

    $http.post(fusio.baseUrl + 'backend/action', data)
      .then(function(response) {
        var data = response.data;
        $scope.response = data;
        if (data.success === true) {
          $uibModalInstance.close(data);
        }
      })
      .catch(function(response) {
        $scope.response = response.data;
      });
  };

  $http.get(fusio.baseUrl + 'backend/action/list')
    .then(function(response) {
      var data = response.data;
      $scope.actions = data.actions;

      if (data.actions[0]) {
        $scope.action.class = data.actions[0].class;
        $scope.loadConfig();
      }
    });

  $scope.close = function() {
    $uibModalInstance.dismiss('cancel');
  };

  $scope.closeResponse = function() {
    $scope.response = null;
  };

  $scope.loadConfig = function() {
    if ($scope.action.class) {
      $http.get(fusio.baseUrl + 'backend/action/form?class=' + encodeURIComponent($scope.action.class))
        .then(function(response) {
          var data = response.data;
          var containerEl = angular.element(document.querySelector('#config-form'));
          containerEl.children().remove();

          $scope.elements = data.element;
          $scope.config = formBuilder.preProcessModel($scope.action.config, $scope.elements);
          var linkFn = formBuilder.buildHtml($scope.elements, 'config');
          if (angular.isFunction(linkFn)) {
            var el = linkFn($scope);
            containerEl.append(el);
          }
        });
    }
  };

};
<commit_msg>use php class engine<commit_after>'use strict';

module.exports = function($scope, $http, $uibModalInstance, formBuilder, fusio) {

  $scope.action = {
    name: "",
    class: "",
    engine: "Fusio\\Engine\\Factory\\Resolver\\PhpClass",
    config: {}
  };
  $scope.elements = [];
  $scope.config = {};
  $scope.actions = [];

  $scope.create = function(action) {
    var data = angular.copy(action);

    if (angular.isObject($scope.config)) {
      data.config = formBuilder.postProcessModel($scope.config, $scope.elements);
    }

    $http.post(fusio.baseUrl + 'backend/action', data)
      .then(function(response) {
        var data = response.data;
        $scope.response = data;
        if (data.success === true) {
          $uibModalInstance.close(data);
        }
      })
      .catch(function(response) {
        $scope.response = response.data;
      });
  };

  $http.get(fusio.baseUrl + 'backend/action/list')
    .then(function(response) {
      var data = response.data;
      $scope.actions = data.actions;

      if (data.actions[0]) {
        $scope.action.class = data.actions[0].class;
        $scope.loadConfig();
      }
    });

  $scope.close = function() {
    $uibModalInstance.dismiss('cancel');
  };

  $scope.closeResponse = function() {
    $scope.response = null;
  };

  $scope.loadConfig = function() {
    if ($scope.action.class) {
      $http.get(fusio.baseUrl + 'backend/action/form?class=' + encodeURIComponent($scope.action.class))
        .then(function(response) {
          var data = response.data;
          var containerEl = angular.element(document.querySelector('#config-form'));
          containerEl.children().remove();

          $scope.elements = data.element;
          $scope.config = formBuilder.preProcessModel($scope.action.config, $scope.elements);
          var linkFn = formBuilder.buildHtml($scope.elements, 'config');
          if (angular.isFunction(linkFn)) {
            var el = linkFn($scope);
            containerEl.append(el);
          }
        });
    }
  };

};
<|endoftext|>


<commit_before>// ***********************************************//
//                 models and stores
// ***********************************************//
require('akvo-flow/core');
DS.Model.reopen({
	namingConvention: {
		keyToJSONKey: function(key) {
			return key;
		},

		foreignKey: function(key) {
			return key;
		}
	}
});

FLOW.store = DS.Store.create({
	revision: 4,
	//adapter:DS.FLOWRESTAdapter.create({bulkCommit:false, namespace:"REST"})//change
	adapter: DS.fixtureAdapter
});

FLOW.SurveyGroup = DS.Model.extend({
	surveyList: DS.attr('string',{defaulValue: ""}),
	description: DS.attr('string',{defaulValue: ""}),
	name: DS.attr('string',{defaulValue: ""}),
	createdDateTime: DS.attr('string',{defaulValue: ""}),
	lastUpdateDateTime: DS.attr('string',{defaulValue: ""}),
	code: DS.attr('string',{defaulValue: ""}),
	displayName: DS.attr('string',{defaulValue: ""}),
	keyId: DS.attr('number'),
	primaryKey: 'keyId'

});

FLOW.SurveyGroup.FIXTURES = [{
	keyId: 1,
	displayName: 'Urban sanitation surveys'
}, {
	keyId: 2,
	displayName: 'Elise Surveys'
}, {
	keyId: 3,
	displayName: 'Test Survey group'
},{
	keyId: 4,
	displayName: 'Upande - SNVVERMIS'
},{
	keyId: 5,
	displayName: 'Akvo test surveys'
}

];

FLOW.Survey = DS.Model.extend({
	defaultLanguageCode: DS.attr('string'),
	status: DS.attr('string'),
	code: DS.attr('string'),
	requireApproval: DS.attr('string'),
	version: DS.attr('string'),
	description: DS.attr('string'),
	name: DS.attr('string'),
	path: DS.attr('string'),
	displayName: DS.attr('string'),
	questionGroupList: DS.attr('string'),
	keyId: DS.attr('number'),
	pointType: DS.attr('string'),
	surveyGroupId: DS.attr('number'),
	primaryKey: 'keyId'

});

FLOW.Survey.FIXTURES = [{
	keyId: 1,
	displayName: 'Water point survey',
	name:'Water point survey',
	surveyGroupId: 1
}, {
	keyId: 2,
	displayName: 'Sanitation survey',
	name:'Sanitation survey',
	surveyGroupId: 1
}, {
	keyId: 3,
	displayName: 'Baseline WASH',
	name:'Baseline WASH',
	surveyGroupId: 1
}, {
	keyId: 4,
	displayName: 'Akvo RSR update',
	name:'Akvo RSR update',
	surveyGroupId: 1
}];

FLOW.QuestionGroup = DS.Model.extend({
	order: DS.attr('number'),
	questionMap: DS.attr('string'),
	description: DS.attr('string'),
	name: DS.attr('string'),
	path: DS.attr('string'),
	class: DS.attr('string'),
	code: DS.attr('string'),
	surveyId: DS.attr('number'),
	displayName: DS.attr('string'),
	keyId: DS.attr('number'),
	isOpen: DS.attr('boolean', {
		defaulValue: 0
	}),
	primaryKey: 'keyId'
});

FLOW.QuestionGroup.FIXTURES = [{
	keyId: 1,
	surveyId:1,
	order:1,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu. ",
	name: 'Location',
	displayName: 'Location'

}, {
	keyId: 2,
	surveyId:1,
	order:2,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Occupation',
	displayName: 'Occupation'

}, {
	keyId: 3,
	surveyId:1,
	order:3,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Water system',
	displayName: 'Water system'

}, {
	keyId: 4,
	surveyId:1,
	order:4,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Sanitation system',
	displayName: 'Sanitation system'

},
{
	keyId: 5,
	surveyId:2,
	order:5,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Something else',
	displayName: 'Something else'

}

];

FLOW.Question = DS.Model.extend({
	translationMap: DS.attr('string'),
	// not sure
	allowDecimal: DS.attr('boolean', {defaulValue: 0}),
	optionContainerDto: DS.attr('string'),
	//not sure
	// type:     --- not now
	tip: DS.attr('string'),
	maxVal: DS.attr('number'),
	minVal: DS.attr('number'),
	order: DS.attr('number'),
	isName: DS.attr('boolean', {defaulValue: 0}),
	// questionHelpList:     --- now now
	collabseable: DS.attr('boolean', {defaulValue: 0}),
	path: DS.attr('string'),
	allowMultipleFlag: DS.attr('boolean', {defaulValue: 0}),
	immutable: DS.attr('boolean', {defaulValue: 0}),
	allowOtherFlag: DS.attr('boolean', {defaulValue: 0}),
	allowSign: DS.attr('boolean', {defaulValue: 0}),
	text: DS.attr('string'),
	class: DS.attr('string'),
	questionDependency: DS.attr('string'),
	mandatoryFlag: DS.attr('boolean', {defaulValue: 0}),
	questionGroupId: DS.attr('number'),
	questionTypeString: DS.attr('string',{defaultValue:"freeText"}),
	surveyId: DS.attr('number'),
	displayName: DS.attr('string'),
	keyId: DS.attr('number')
});

FLOW.Question.FIXTURES = [{
	keyId: 1,
	text: 'What is the name of the community?',
	displayName: 'What is the name of the community?',
	mandatory: false,
	questionTypeString:'freeText',
	questionSetId: 1
}, {
	keyId: 2,
	text: 'What is your occupation?',
	displayName: 'What is your occupation?',
	mandatory: false,
	questionTypeString:'option',
	questionSetId: 1
}, {
	keyId: 3,
	text: 'How much children do you have?',
	displayName: 'How much children do you have?',
	mandatory: false,
	questionTypeString:'number',
	questionSetId: 1
}, {
	keyId: 4,
	text: 'Please take a geolocation',
	displayName: 'Please take a geolocation',
	mandatory: false,
	questionTypeString:'geoLoc',
	questionSetId: 1
}, 	{
	keyId: 4,
	text: 'Please take a picture',
	displayName: 'Please take a picture',
	mandatory: false,
	questionTypeString:'photo',
	questionSetId: 1
},	{
	keyId: 4,
	text: 'Please make a video',
	displayName: 'Please make a video',
	questionTypeString:'video',
	mandatory: false,
	questionSetId: 1
},	{
	keyId: 4,
	text: 'What is the date today?',
	displayName: 'What is the date today?',
	questionTypeString:'date',
	mandatory: false,
	questionSetId: 1
}];

FLOW.QuestionOption = DS.Model.extend({
	questionId: DS.attr('number'),
	text: DS.attr('string'),
	keyId: DS.attr('number')
});

FLOW.QuestionOption.FIXTURES = [{
	keyId: 1,
	text: 'teacher',
	questionId: 1
}, {
	keyId: 2,
	text: 'cook',
	questionId: 1
},{
	keyId: 3,
	text: 'minister',
	questionId: 1
},{
	keyId: 4,
	text: 'programmer',
	questionId: 1
}];<commit_msg>added order to question models<commit_after>// ***********************************************//
//                 models and stores
// ***********************************************//
require('akvo-flow/core');
DS.Model.reopen({
	namingConvention: {
		keyToJSONKey: function(key) {
			return key;
		},

		foreignKey: function(key) {
			return key;
		}
	}
});

FLOW.store = DS.Store.create({
	revision: 4,
	//adapter:DS.FLOWRESTAdapter.create({bulkCommit:false, namespace:"REST"})//change
	adapter: DS.fixtureAdapter
});

FLOW.SurveyGroup = DS.Model.extend({
	surveyList: DS.attr('string',{defaulValue: ""}),
	description: DS.attr('string',{defaulValue: ""}),
	name: DS.attr('string',{defaulValue: ""}),
	createdDateTime: DS.attr('string',{defaulValue: ""}),
	lastUpdateDateTime: DS.attr('string',{defaulValue: ""}),
	code: DS.attr('string',{defaulValue: ""}),
	displayName: DS.attr('string',{defaulValue: ""}),
	keyId: DS.attr('number'),
	primaryKey: 'keyId'

});

FLOW.SurveyGroup.FIXTURES = [{
	keyId: 1,
	displayName: 'Urban sanitation surveys'
}, {
	keyId: 2,
	displayName: 'Elise Surveys'
}, {
	keyId: 3,
	displayName: 'Test Survey group'
},{
	keyId: 4,
	displayName: 'Upande - SNVVERMIS'
},{
	keyId: 5,
	displayName: 'Akvo test surveys'
}

];

FLOW.Survey = DS.Model.extend({
	defaultLanguageCode: DS.attr('string'),
	status: DS.attr('string'),
	code: DS.attr('string'),
	requireApproval: DS.attr('string'),
	version: DS.attr('string'),
	description: DS.attr('string'),
	name: DS.attr('string'),
	path: DS.attr('string'),
	displayName: DS.attr('string'),
	questionGroupList: DS.attr('string'),
	keyId: DS.attr('number'),
	pointType: DS.attr('string'),
	surveyGroupId: DS.attr('number'),
	primaryKey: 'keyId'

});

FLOW.Survey.FIXTURES = [{
	keyId: 1,
	displayName: 'Water point survey',
	name:'Water point survey',
	surveyGroupId: 1
}, {
	keyId: 2,
	displayName: 'Sanitation survey',
	name:'Sanitation survey',
	surveyGroupId: 1
}, {
	keyId: 3,
	displayName: 'Baseline WASH',
	name:'Baseline WASH',
	surveyGroupId: 1
}, {
	keyId: 4,
	displayName: 'Akvo RSR update',
	name:'Akvo RSR update',
	surveyGroupId: 1
}];

FLOW.QuestionGroup = DS.Model.extend({
	order: DS.attr('number'),
	questionMap: DS.attr('string'),
	description: DS.attr('string'),
	name: DS.attr('string'),
	path: DS.attr('string'),
	class: DS.attr('string'),
	code: DS.attr('string'),
	surveyId: DS.attr('number'),
	displayName: DS.attr('string'),
	keyId: DS.attr('number'),
	isOpen: DS.attr('boolean', {
		defaulValue: 0
	}),
	primaryKey: 'keyId'
});

FLOW.QuestionGroup.FIXTURES = [{
	keyId: 1,
	surveyId:1,
	order:1,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu. ",
	name: 'Location',
	displayName: 'Location'

}, {
	keyId: 2,
	surveyId:1,
	order:2,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Occupation',
	displayName: 'Occupation'

}, {
	keyId: 3,
	surveyId:1,
	order:3,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Water system',
	displayName: 'Water system'

}, {
	keyId: 4,
	surveyId:1,
	order:4,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Sanitation system',
	displayName: 'Sanitation system'

},
{
	keyId: 5,
	surveyId:2,
	order:5,
	description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin in ligula et ipsum feugiat egestas ac vel arcu.",
	name: 'Something else',
	displayName: 'Something else'

}

];

FLOW.Question = DS.Model.extend({
	translationMap: DS.attr('string'),
	// not sure
	allowDecimal: DS.attr('boolean', {defaulValue: 0}),
	optionContainerDto: DS.attr('string'),
	//not sure
	// type:     --- not now
	tip: DS.attr('string'),
	maxVal: DS.attr('number'),
	minVal: DS.attr('number'),
	order: DS.attr('number'),
	isName: DS.attr('boolean', {defaulValue: 0}),
	// questionHelpList:     --- now now
	collabseable: DS.attr('boolean', {defaulValue: 0}),
	path: DS.attr('string'),
	allowMultipleFlag: DS.attr('boolean', {defaulValue: 0}),
	immutable: DS.attr('boolean', {defaulValue: 0}),
	allowOtherFlag: DS.attr('boolean', {defaulValue: 0}),
	allowSign: DS.attr('boolean', {defaulValue: 0}),
	text: DS.attr('string'),
	class: DS.attr('string'),
	questionDependency: DS.attr('string'),
	mandatoryFlag: DS.attr('boolean', {defaulValue: 0}),
	questionGroupId: DS.attr('number'),
	questionTypeString: DS.attr('string',{defaultValue:"freeText"}),
	surveyId: DS.attr('number'),
	displayName: DS.attr('string'),
	keyId: DS.attr('number')
});

FLOW.Question.FIXTURES = [{
	keyId: 1,
	text: 'What is the name of the community?',
	displayName: 'What is the name of the community?',
	mandatory: false,
	order:1,
	questionTypeString:'freeText',
	questionSetId: 1
}, {
	keyId: 2,
	text: 'What is your occupation?',
	displayName: 'What is your occupation?',
	mandatory: false,
	order:2,
	questionTypeString:'option',
	questionSetId: 1
}, {
	keyId: 3,
	text: 'How much children do you have?',
	displayName: 'How much children do you have?',
	mandatory: false,
	order:3,
	questionTypeString:'number',
	questionSetId: 1
}, {
	keyId: 4,
	text: 'Please take a geolocation',
	displayName: 'Please take a geolocation',
	mandatory: false,
	order:4,
	questionTypeString:'geoLoc',
	questionSetId: 1
}, 	{
	keyId: 4,
	text: 'Please take a picture',
	displayName: 'Please take a picture',
	mandatory: false,
	order:5,
	questionTypeString:'photo',
	questionSetId: 1
},	{
	keyId: 4,
	text: 'Please make a video',
	displayName: 'Please make a video',
	questionTypeString:'video',
	order:6,
	mandatory: false,
	questionSetId: 1
},	{
	keyId: 4,
	text: 'What is the date today?',
	displayName: 'What is the date today?',
	questionTypeString:'date',
	order:7,
	mandatory: false,
	questionSetId: 1
}];

FLOW.QuestionOption = DS.Model.extend({
	questionId: DS.attr('number'),
	text: DS.attr('string'),
	keyId: DS.attr('number')
});

FLOW.QuestionOption.FIXTURES = [{
	keyId: 1,
	text: 'teacher',
	questionId: 1
}, {
	keyId: 2,
	text: 'cook',
	questionId: 1
},{
	keyId: 3,
	text: 'minister',
	questionId: 1
},{
	keyId: 4,
	text: 'programmer',
	questionId: 1
}];<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Erik Nordstrøm <erikn@ict-infer.no>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

function(head, req)
{
	provides("html", function ()
	{
		html = "";

		function trv_pd (vd)
		{
			html += "" + vd.due_date + "	";

			html += "<date datetime=\""
				+ vd.due_ts + "\">"
				+ vd.due_zclock + "	";
		}

		function trv_pr (vd)
		{
			html += "" + vd.delivered_date + "	";

			html += "<date datetime=\""
				+ vd.delivered_ts + "\">"
				+ vd.delivered_zclock + "	";
		}

		function trv_app (vd)
		{
			html += "" + vd.score + "	";
		}

		function tr (trv, row)
		{
			html += "
";

			vd = row.value; // view-emitted data values

			html += ""
				+ vd.course + "	";

			html += "" + vd.title + "	";

			trv(vd);

			html += "
";
		}

		function table (first_row, n, title, ths, trv)
		{
			row = first_row;

			if (row && ('key' in row) && row.key[0] === n)
			{
				html += "
" + title + "
";
				html += "
";
				html += "

" + ths + "

";
				html += "
";

				do
				{
					tr(trv, row);
					row = getRow();
				} while (row && ('key' in row) && row.key[0] === n)

				html += "

";
			}

			return row;
		}

		ths_common = "Course	Assignment	";
		ths_pd = ths_common + "Due	";
		ths_pr = ths_common + "Delivered	";
		ths_app = ths_common + "Score	";

		row = getRow();
		row = table(row, 0, "Pending delivery", ths_pd, trv_pd);
		row = table(row, 1, "Pending review", ths_pr, trv_pr);
		row = table(row, 2, "Approved", ths_app, trv_app);

		return html;
	});
}
<commit_msg>HTML5 validation fixes.<commit_after>/*
 * Copyright (c) 2016 Erik Nordstrøm <erikn@ict-infer.no>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

function(head, req)
{
	provides("html", function ()
	{
		html = "<!DOCTYPE html><title>DDU</title>";

		function trv_pd (vd)
		{
			html += "" + vd.due_date + "	";

			html += "<time datetime=\""
				+ vd.due_ts + "\">"
				+ vd.due_zclock + "</time>	";
		}

		function trv_pr (vd)
		{
			html += "" + vd.delivered_date + "	";

			html += "<time datetime=\""
				+ vd.delivered_ts + "\">"
				+ vd.delivered_zclock + "</time>	";
		}

		function trv_app (vd)
		{
			html += "" + vd.score + "	";
		}

		function tr (trv, row)
		{
			html += "
";

			vd = row.value; // view-emitted data values

			html += ""
				+ vd.course + "	";

			html += "" + vd.title + "	";

			trv(vd);

			html += "
";
		}

		function table (first_row, n, title, ths, trv)
		{
			row = first_row;

			if (row && ('key' in row) && row.key[0] === n)
			{
				html += "
" + title + "
";
				html += "
";
				html += "

" + ths + "

";
				html += "
";

				do
				{
					tr(trv, row);
					row = getRow();
				} while (row && ('key' in row) && row.key[0] === n)

				html += "

";
			}

			return row;
		}

		ths_common = "Course	Assignment	";
		ths_pd = ths_common + "Due	";
		ths_pr = ths_common + "Delivered	";
		ths_app = ths_common + "Score	";

		row = getRow();
		row = table(row, 0, "Pending delivery", ths_pd, trv_pd);
		row = table(row, 1, "Pending review", ths_pr, trv_pr);
		row = table(row, 2, "Approved", ths_app, trv_app);

		return html;
	});
}
<|endoftext|>


<commit_before>YUI.add("auction", function(Y) {

    Y.namespace("Bridge");

    function Auction() {
        Auction.superclass.constructor.apply(this, arguments);
    };

    Y.extend(Auction, Y.Widget, {
        renderUI: function() {
            this._renderAuction();
        },

        bindUI: function() {
            this.after("bidsChange", this._afterBidsChange);
            this.after("dealerChange", this._afterDealerChange);
        },

        syncUI: function() {
            this._uiSetBids(this.get("bids"));
        },

        _afterBidsChange: function(event) {
            this._uiSetBids(event.newVal);
        },

        _afterDealerChange: function(event) {
            this._uiSetDealer(event.newVal);
        },

        _uiSetDealer: function(dealer) {
            this._uiSetBids(this.get("bids"));
        },

        _renderAuction: function() {
            var html, headers,
                dealer = this.get("dealer"),
                vulnerable = this.get("vulnerable"),
                contentBox = this.get("contentBox");
            headers = Y.Array.map(Y.Bridge.DIRECTIONS, function(direction) {
                var classNames = [this.getClassName("header", direction.toLowerCase())];
                if (vulnerable === "BOTH") {
                    classNames[classNames.length] = this.getClassName("header", "vulnerable");
                } else if (["NS", "EW"].indexOf(vulnerable) !== -1) {
                    if (vulnerable.indexOf(direction) !== -1) {
                        classNames[classNames.length] = this.getClassName("header", "vulnerable");
                    }
                }

                return {
                    name: direction,
                    classNames: classNames.join(" ")
                };
            }, this);
            html = Y.mustache(Auction.AUCTION_TEMPLATE, {
                headers: headers,
                headersCN: this.getClassName("headers")
            });

            contentBox.set("innerHTML", html);
        },

        _uiSetBids: function(bids) {
            var bidsNode, html, dealerPosition,
                dealer = this.get("dealer"),
                contentBox = this.get("contentBox");
            bidsNode = contentBox.one("." + this.getClassName("bids"));
            dealerPosition = Y.Array.indexOf(Y.Bridge.DIRECTIONS, dealer);

            bids = Y.Array.map(bids, function(bid, i) {
                var player = Y.Bridge.DIRECTIONS[(i + dealerPosition) % 4],
                    classNames = [this.getClassName("bid", bid.bid.toLowerCase())];

                if (bid.alert) {
                    classNames[classNames.length] = this.getClassName("bid", "alerted");
                }

                return {
                    name: Y.Bridge.renderBid(bid.bid),
                    classNames: classNames.join(" "),
                    alert: bid.alert,
                    player: player
                };
            }, this);

            for(var i = 0; i < dealerPosition; i++) {
                // add empty bids
                bids.unshift({});
            }

            html = Y.mustache(Auction.BIDS_TEMPLATE, {
                bids: bids
            });

            bidsNode.set("innerHTML", html);
            Y.later(0, this, function() {
                var scrollHeight = bidsNode.get("scrollHeight"),
                    offsetHeight = bidsNode.get("offsetHeight");

                bidsNode.set("scrollTop", scrollHeight - offsetHeight);
            });
        }

    }, {

        NAME: "auction",

        ATTRS: {

            dealer: {
                value: "N"
            },

            vulnerable: {
                value: "NONE"
            },

            bids: {
                value: []
            },

            strings: {
                value: {
                    modifiers: {
                        PASS: "Pass",
                        X: "Dbl",
                        XX: "Rdbl"
                    },
                    suits: {
                        C: "♣",
                        D: "♦",
                        H: "♥",
                        S: "♠",
                        NT: "NT"
                    }
                }
            }
        },

        AUCTION_TEMPLATE: ''
            + '
'
            +   '{{#headers}}'
            +     '
{{name}}
'
            +   '{{/headers}}'
            + '
'
            + '

'
            + '
'
            + '

',

        BIDS_TEMPLATE: ''
            + '{{#bids}}'
            +   '
'
            +     '{{#name}}'
            +       '<button type="button" class="yui3-auction-bid {{classNames}}" data-player="{{player}}" title="{{alert}}">'
            +         '{{{name}}}'
            +       '</button>'
            +     '{{/name}}'
            +   '
'
            + '{{/bids}}'

    });

    Y.Bridge.Auction = Auction;

}, "0", { requires: ["widget"] });
<commit_msg>fixed auction widget<commit_after>YUI.add("auction", function(Y) {

    Y.namespace("Bridge");

    function Auction() {
        Auction.superclass.constructor.apply(this, arguments);
    };

    Y.extend(Auction, Y.Widget, {
        renderUI: function() {
            this._renderAuction();
        },

        bindUI: function() {
            this.after("bidsChange", this._afterBidsChange);
            this.after("dealerChange", this._afterDealerChange);
            this.after("vulnerableChange", this._afterVulnerableChange);
        },

        syncUI: function() {
            this._uiSetBids(this.get("bids"));
        },

        _afterBidsChange: function(event) {
            this._uiSetBids(event.newVal);
        },

        _afterDealerChange: function(event) {
            this._uiSetDealer(event.newVal);
        },

        _afterVulnerableChange: function(event) {
            this._uiSetVulnerable(event.newVal);
        },

        _uiSetDealer: function(dealer) {
            this._uiSetBids(this.get("bids"));
        },

        _renderAuction: function() {
            var html, headers,
                dealer = this.get("dealer"),
                contentBox = this.get("contentBox");
            headers = Y.Array.map(Y.Bridge.DIRECTIONS, function(direction) {
                return {
                    name: direction,
                    classNames: this.getClassName("header", direction.toLowerCase())
                };
            }, this);
            html = Y.mustache(Auction.AUCTION_TEMPLATE, {
                headers: headers,
                headersCN: this.getClassName("headers")
            });

            contentBox.set("innerHTML", html);
        },

        _uiSetBids: function(bids) {
            var bidsNode, html, dealerPosition,
                dealer = this.get("dealer"),
                contentBox = this.get("contentBox");
            bidsNode = contentBox.one("." + this.getClassName("bids"));
            dealerPosition = Y.Array.indexOf(Y.Bridge.DIRECTIONS, dealer);

            bids = Y.Array.map(bids, function(bid, i) {
                var player = Y.Bridge.DIRECTIONS[(i + dealerPosition) % 4],
                    classNames = [this.getClassName("bid", bid.bid.toLowerCase())];

                if (bid.alert) {
                    classNames[classNames.length] = this.getClassName("bid", "alerted");
                }

                return {
                    name: Y.Bridge.renderBid(bid.bid),
                    classNames: classNames.join(" "),
                    alert: bid.alert,
                    player: player
                };
            }, this);

            for(var i = 0; i < dealerPosition; i++) {
                // add empty bids
                bids.unshift({});
            }

            html = Y.mustache(Auction.BIDS_TEMPLATE, {
                bids: bids
            });

            bidsNode.set("innerHTML", html);
            Y.later(0, this, function() {
                var scrollHeight = bidsNode.get("scrollHeight"),
                    offsetHeight = bidsNode.get("offsetHeight");

                bidsNode.set("scrollTop", scrollHeight - offsetHeight);
            });
        },

        _uiSetVulnerable: function(vulnerable) {
            var headerNodeN, headerNodeE, headerNodeS, headerNodeW,
                contentBox = this.get("contentBox"),
                vulnerableCN = this.getClassName("header", "vulnerable");

            headerNodeN = contentBox.one("." + this.getClassName("header", "n")).removeClass(vulnerableCN);
            headerNodeE = contentBox.one("." + this.getClassName("header", "e")).removeClass(vulnerableCN);
            headerNodeS = contentBox.one("." + this.getClassName("header", "s")).removeClass(vulnerableCN);
            headerNodeW = contentBox.one("." + this.getClassName("header", "w")).removeClass(vulnerableCN);

            switch(vulnerable) {
            case "NONE":
                // DO NOTHING
                break;
            case "NS":
                headerNodeN.addClass(vulnerableCN);
                headerNodeS.addClass(vulnerableCN);
                break;
            case "EW":
                headerNodeE.addClass(vulnerableCN);
                headerNodeW.addClass(vulnerableCN);
                break;
            case "BOTH":
                headerNodeN.addClass(vulnerableCN);
                headerNodeE.addClass(vulnerableCN);
                headerNodeS.addClass(vulnerableCN);
                headerNodeW.addClass(vulnerableCN);
                break;
            }
        }

    }, {

        NAME: "auction",

        ATTRS: {

            dealer: {
                value: "N"
            },

            vulnerable: {
                value: "NONE"
            },

            bids: {
                value: []
            },

            strings: {
                value: {
                    modifiers: {
                        PASS: "Pass",
                        X: "Dbl",
                        XX: "Rdbl"
                    },
                    suits: {
                        C: "♣",
                        D: "♦",
                        H: "♥",
                        S: "♠",
                        NT: "NT"
                    }
                }
            }
        },

        AUCTION_TEMPLATE: ''
            + '
'
            +   '{{#headers}}'
            +     '
{{name}}
'
            +   '{{/headers}}'
            + '
'
            + '

'
            + '
'
            + '

',

        BIDS_TEMPLATE: ''
            + '{{#bids}}'
            +   '
'
            +     '{{#name}}'
            +       '<button type="button" class="yui3-auction-bid {{classNames}}" data-player="{{player}}" title="{{alert}}">'
            +         '{{{name}}}'
            +       '</button>'
            +     '{{/name}}'
            +   '
'
            + '{{/bids}}'

    });

    Y.Bridge.Auction = Auction;

}, "0", { requires: ["widget"] });
<|endoftext|>


<commit_before>define([
	"dojo/_base/declare", "dojo/on", "dojo/dom-construct",
	"dojo/_base/lang", "dojo/mouse","rql/js-array",
	"dojo/topic", "dojo/query", "dijit/layout/ContentPane",
	"dijit/Dialog", "dijit/popup", "dijit/TooltipDialog",
	"./AdvancedDownload", "dojo/dom-class","FileSaver","dojo/when"
], function(declare, on, domConstruct,
			lang, Mouse,rql,
			Topic, query, ContentPane,
			Dialog, popup, TooltipDialog,
			AdvancedDownload, domClass, saveAs, when){

	return declare([TooltipDialog], {
		containerType: "",
		selection: null,
		grid: null,

		_setSelectionAttr: function(val){
			// console.log("DownloadTooltipDialog set selection: ", val);
			this.selection = val;
		},
		timeout: function(val){
			var _self = this;
			this._timer = setTimeout(function(){
				popup.close(_self);
			}, val || 2500);
		},

		onMouseEnter: function(){
			if(this._timer){
				clearTimeout(this._timer);
			}

			this.inherited(arguments);
		},
		onMouseLeave: function(){
			popup.close(this);
		},

		downloadSelection: function(type,selection){

			var conf = this.downloadableConfig[this.containerType];
			var sel = selection.map(function(sel){
				return sel[conf.field || conf.pk]
			});

			console.log("DOWNLOAD TYPE: ", type)
			if (conf.generateDownloadFromStore && this.grid && this.grid.store && type && this["_to" + type]){
				var query = "in(" + (conf.field || conf.pk) + ",(" + sel.join(",") + "))&sort(+" + conf.pk + ")&limit(2500000)"
				when(this.grid.store.query({}), lang.hitch(this,function(results){
					results = rql.query(query,{},results);
					var data = this["_to" + type.toLowerCase()](results);
					saveAs(new Blob([data]), this.containerType + "_selection." + type);
				}));
			}else{

				var accept;
				switch(type){
					case "csv":
					case "tsv":
						accept = "text/" + type;
						break;
					case "excel":
						accept = "application/vnd.openxmlformats";
						break;
					default:
						accept = "application/" + type;
						break;
				}

				var baseUrl = (window.App.dataServiceURL ? (window.App.dataServiceURL) : "")

				if(baseUrl.charAt(-1) !== "/"){
					baseUrl = baseUrl + "/";
				}
				baseUrl = baseUrl + conf.dataType + "/";
				var query = "in(" + (conf.field || conf.pk) + ",(" + sel.join(",") + "))&sort(+" + conf.pk + ")&limit(2500000)"
				console.log("Download Query: ", query);

				baseUrl = baseUrl + "?&http_download=true&http_accept=" + accept

				if (window.App.authorizationToken){
					baseUrl = baseUrl + "&http_authorization=" + encodeURIComponent(window.App.authorizationToken)
				}

				var form = domConstruct.create("form", {
					style: "display: none;",
					id: "downloadForm",
					enctype: 'application/x-www-form-urlencoded',
					name: "downloadForm",
					method: "post",
					action: baseUrl
				}, this.domNode);
				domConstruct.create('input', {type: "hidden", value: encodeURIComponent(query), name: "rql"}, form);
				form.submit();
			 }
		},

		_tocsv: function(selection){
			var out = [];
			var keys = Object.keys(selection[0]);

			var header=[]
			keys.forEach(function(key){
				header.push(key);
			});
			out.push(header.join(","));
			selection.forEach(function(obj){
				var io = [];

				keys.forEach(function(key){
					io.push('"' + obj[key] + '"');
				})

				out.push(io.join(","));
			});

			return out.join("\n");

		},

		_totsv: function(selection){
			var out = [];
			var keys = Object.keys(selection[0]);

			var header=[]
			keys.forEach(function(key){
				header.push(key);
			});
			out.push(header.join("\t"));
			selection.forEach(function(obj){
				var io = [];

				keys.forEach(function(key){
					io.push('"' + obj[key] + '"');
				})

				out.push(io.join("\t"));
			});

			return out.join("\n");

		},

		startup: function(){
			if(this._started){
				return;
			}
			on(this.domNode, Mouse.enter, lang.hitch(this, "onMouseEnter"));
			on(this.domNode, Mouse.leave, lang.hitch(this, "onMouseLeave"));
			var _self = this;
			on(this.domNode, ".wsActionTooltip:click", function(evt){
				// console.log("evt.target: ", evt.target, evt.target.attributes);
				var rel = evt.target.attributes.rel.value;
				if(rel == "advancedDownload"){

					// console.log("Selection: ", _self.selection);
					var d = new Dialog({title: "Download"});
					var ad = new AdvancedDownload({selection: _self.selection, containerType: _self.containerType});
					domConstruct.place(ad.domNode, d.containerNode);
					d.show();
					return;
				}
				var conf = _self.downloadableConfig[_self.containerType];

				// var sel = _self.selection.map(function(sel){
				// 	return sel[conf.field || conf.pk]
				// });

				_self.downloadSelection(rel,_self.selection)
			});

			var dstContent = domConstruct.create("div", {});
			this.labelNode = domConstruct.create("div", {style: "background:#09456f;color:#fff;margin:0px;margin-bottom:4px;padding:4px;text-align:center;"}, dstContent);
			this.selectedCount = domConstruct.create("div", {}, dstContent);
			var table = domConstruct.create("table", {}, dstContent);

			var tr = domConstruct.create("tr", {}, table);
			var tData = this.tableDownloadsNode = domConstruct.create("td", {style: "vertical-align:top;"}, tr);
			//spacer
			domConstruct.create("td", {style: "width:10px;"}, tr);
			var oData = this.otherDownloadNode = domConstruct.create("td", {style: "vertical-align:top;"}, tr);

			domConstruct.create("div", {"class": "wsActionTooltip", rel: "tsv", innerHTML: "Text"}, tData);
			domConstruct.create("div", {"class": "wsActionTooltip", rel: "csv", innerHTML: "CSV"}, tData);
			// domConstruct.create("div", {"class": "wsActionTooltip", rel: "excel", innerHTML: "Excel"}, tData);

			tr = domConstruct.create("tr", {}, table);
			var td = domConstruct.create("td", {"colspan": 3, "style": "text-align:right"}, tr);
			this.advancedDownloadButton = domConstruct.create("span", {
				"class": "wsActionTooltip",
				style: "padding:4px;",
				rel: "advancedDownload",
				innerHTML: "More Options"
			}, td);

			this.set("content", dstContent);

			this._started = true;
			this.set("label", this.label);
			this.set("selection", this.selection);

		},

		_setLabelAttr: function(val){
			this.label = val;
			if(this._started){
				this.labelNode.innerHTML = "Download selected " + val + " (" + (this.selection ? this.selection.length : "0") + ") as...";
			}
		},

		downloadableDataTypes: {
			"dna+fasta": "DNA FASTA",
			"protein+fasta": "Protein FASTA"
		},

		"downloadableConfig": {
			"genome_data": {
				"label": "Genomes",
				"dataType": "genome",
				pk: "genome_id",
				tableData: true,
				advanced: true
			},
			"sequence_data": {
				"label": "Sequences",
				"dataType": "sequence",
				pk: "sequence_id",
				tableData: true,
				otherData: ["dna+fasta", "protein+fasta"]
			},
			"feature_data": {
				"label": "Features",
				"dataType": "genome_feature",
				pk: "feature_id",
				tableData: true,
				otherData: ["dna+fasta", "protein+fasta"]
			},
			"spgene_data": {
				dataType: "sp_gene",
				field: "feature_id",
				pk: "id",
				"label": "Specialty Genes",
				tableData: true
			},
			"pathway_data": {
				pk: "pathway_id",
				dataType: "pathway",
				"label": "Pathways",
				"generateDownloadFromStore": true,
				tableData: true
			},
			"gene_expression_data": {
				dataType: "transcriptomics_gene",
				pk: "pid",
				"label": "Gene Expression",
				tableData: true
			},
			"default": {
				"label": "Items",
				tableData: true
			}
		},

		_setContainerTypeAttr: function(val){
			// console.log("setContainerType: ", val);
			var label;
			this.containerType = val;

			var conf = this.downloadableConfig[val] || this.downloadableConfig["default"];

			this.set("label", conf.label);

			if(!this._started){
				return;
			}

			domConstruct.empty(this.otherDownloadNode);

			if(conf.otherData){
				conf.otherData.forEach(function(type){
					domConstruct.create("div", {
						"class": "wsActionTooltip",
						rel: type,
						innerHTML: this.downloadableDataTypes[type]
					}, this.otherDownloadNode);
				}, this);
			}

			if(conf.advanced){
				domClass.remove(this.advancedDownloadButton, "dijitHidden");
			}else{
				domClass.add(this.advancedDownloadButton, "dijitHidden");
			}

		}
	});

});
<commit_msg>resolve https://github.com/PATRIC3/patric3_website/#945<commit_after>define([
	"dojo/_base/declare", "dojo/on", "dojo/dom-construct",
	"dojo/_base/lang", "dojo/mouse", "rql/js-array",
	"dojo/topic", "dojo/query", "dijit/layout/ContentPane",
	"dijit/Dialog", "dijit/popup", "dijit/TooltipDialog",
	"./AdvancedDownload", "dojo/dom-class", "FileSaver", "dojo/when"
], function(declare, on, domConstruct,
			lang, Mouse, rql,
			Topic, query, ContentPane,
			Dialog, popup, TooltipDialog,
			AdvancedDownload, domClass, saveAs, when){

	return declare([TooltipDialog], {
		containerType: "",
		selection: null,
		grid: null,

		_setSelectionAttr: function(val){
			// console.log("DownloadTooltipDialog set selection: ", val);
			this.selection = val;
		},
		timeout: function(val){
			var _self = this;
			this._timer = setTimeout(function(){
				popup.close(_self);
			}, val || 2500);
		},

		onMouseEnter: function(){
			if(this._timer){
				clearTimeout(this._timer);
			}

			this.inherited(arguments);
		},
		onMouseLeave: function(){
			popup.close(this);
		},

		downloadSelection: function(type, selection){

			var conf = this.downloadableConfig[this.containerType];
			var sel = selection.map(function(sel){
				return sel[conf.field || conf.pk]
			});

			console.log("DOWNLOAD TYPE: ", type)
			if(conf.generateDownloadFromStore && this.grid && this.grid.store && type && this["_to" + type]){
				var query = "in(" + (conf.field || conf.pk) + ",(" + sel.join(",") + "))&sort(+" + conf.pk + ")&limit(2500000)"
				when(this.grid.store.query({}), lang.hitch(this, function(results){
					results = rql.query(query, {}, results);
					var data = this["_to" + type.toLowerCase()](results);
					saveAs(new Blob([data]), this.containerType + "_selection." + type);
				}));
			}else{

				var accept;
				switch(type){
					case "csv":
					case "tsv":
						accept = "text/" + type;
						break;
					case "excel":
						accept = "application/vnd.openxmlformats";
						break;
					default:
						accept = "application/" + type;
						break;
				}

				var baseUrl = (window.App.dataServiceURL ? (window.App.dataServiceURL) : "")

				if(baseUrl.charAt(-1) !== "/"){
					baseUrl = baseUrl + "/";
				}
				baseUrl = baseUrl + conf.dataType + "/";
				var query = "in(" + (conf.field || conf.pk) + ",(" + sel.join(",") + "))&sort(+" + conf.pk + ")&limit(2500000)"
				console.log("Download Query: ", query);

				baseUrl = baseUrl + "?&http_download=true&http_accept=" + accept

				if(window.App.authorizationToken){
					baseUrl = baseUrl + "&http_authorization=" + encodeURIComponent(window.App.authorizationToken)
				}

				var form = domConstruct.create("form", {
					style: "display: none;",
					id: "downloadForm",
					enctype: 'application/x-www-form-urlencoded',
					name: "downloadForm",
					method: "post",
					action: baseUrl
				}, this.domNode);
				domConstruct.create('input', {type: "hidden", value: encodeURIComponent(query), name: "rql"}, form);
				form.submit();
			}
		},

		_tocsv: function(selection){
			var out = [];
			var keys = Object.keys(selection[0]);

			var header = []
			keys.forEach(function(key){
				header.push(key);
			});
			out.push(header.join(","));
			selection.forEach(function(obj){
				var io = [];

				keys.forEach(function(key){
					io.push('"' + obj[key] + '"');
				})

				out.push(io.join(","));
			});

			return out.join("\n");

		},

		_totsv: function(selection){
			var out = [];
			var keys = Object.keys(selection[0]);

			var header = []
			keys.forEach(function(key){
				header.push(key);
			});
			out.push(header.join("\t"));
			selection.forEach(function(obj){
				var io = [];

				keys.forEach(function(key){
					io.push('"' + obj[key] + '"');
				})

				out.push(io.join("\t"));
			});

			return out.join("\n");

		},

		startup: function(){
			if(this._started){
				return;
			}
			on(this.domNode, Mouse.enter, lang.hitch(this, "onMouseEnter"));
			on(this.domNode, Mouse.leave, lang.hitch(this, "onMouseLeave"));
			var _self = this;
			on(this.domNode, ".wsActionTooltip:click", function(evt){
				// console.log("evt.target: ", evt.target, evt.target.attributes);
				var rel = evt.target.attributes.rel.value;
				if(rel == "advancedDownload"){

					// console.log("Selection: ", _self.selection);
					var d = new Dialog({title: "Download"});
					var ad = new AdvancedDownload({selection: _self.selection, containerType: _self.containerType});
					domConstruct.place(ad.domNode, d.containerNode);
					d.show();
					return;
				}
				var conf = _self.downloadableConfig[_self.containerType];

				// var sel = _self.selection.map(function(sel){
				// 	return sel[conf.field || conf.pk]
				// });

				_self.downloadSelection(rel, _self.selection)
			});

			var dstContent = domConstruct.create("div", {});
			this.labelNode = domConstruct.create("div", {style: "background:#09456f;color:#fff;margin:0px;margin-bottom:4px;padding:4px;text-align:center;"}, dstContent);
			this.selectedCount = domConstruct.create("div", {}, dstContent);
			var table = domConstruct.create("table", {}, dstContent);

			var tr = domConstruct.create("tr", {}, table);
			var tData = this.tableDownloadsNode = domConstruct.create("td", {style: "vertical-align:top;"}, tr);
			//spacer
			domConstruct.create("td", {style: "width:10px;"}, tr);
			var oData = this.otherDownloadNode = domConstruct.create("td", {style: "vertical-align:top;"}, tr);

			domConstruct.create("div", {"class": "wsActionTooltip", rel: "tsv", innerHTML: "Text"}, tData);
			domConstruct.create("div", {"class": "wsActionTooltip", rel: "csv", innerHTML: "CSV"}, tData);
			// domConstruct.create("div", {"class": "wsActionTooltip", rel: "excel", innerHTML: "Excel"}, tData);

			tr = domConstruct.create("tr", {}, table);
			var td = domConstruct.create("td", {"colspan": 3, "style": "text-align:right"}, tr);
			this.advancedDownloadButton = domConstruct.create("span", {
				"class": "wsActionTooltip",
				style: "padding:4px;",
				rel: "advancedDownload",
				innerHTML: "More Options"
			}, td);

			this.set("content", dstContent);

			this._started = true;
			this.set("label", this.label);
			this.set("selection", this.selection);

		},

		_setLabelAttr: function(val){
			this.label = val;
			if(this._started){
				this.labelNode.innerHTML = "Download selected " + val + " (" + (this.selection ? this.selection.length : "0") + ") as...";
			}
		},

		downloadableDataTypes: {
			"dna+fasta": "DNA FASTA",
			"protein+fasta": "Protein FASTA"
		},

		"downloadableConfig": {
			"genome_data": {
				"label": "Genomes",
				"dataType": "genome",
				pk: "genome_id",
				tableData: true,
				advanced: true
			},
			"sequence_data": {
				"label": "Sequences",
				"dataType": "genome_sequence",
				pk: "sequence_id",
				tableData: true,
				otherData: ["dna+fasta", "protein+fasta"]
			},
			"feature_data": {
				"label": "Features",
				"dataType": "genome_feature",
				pk: "feature_id",
				tableData: true,
				otherData: ["dna+fasta", "protein+fasta"]
			},
			"spgene_data": {
				dataType: "sp_gene",
				field: "feature_id",
				pk: "id",
				"label": "Specialty Genes",
				tableData: true
			},
			"pathway_data": {
				pk: "pathway_id",
				dataType: "pathway",
				"label": "Pathways",
				"generateDownloadFromStore": true,
				tableData: true
			},
			"gene_expression_data": {
				dataType: "transcriptomics_gene",
				pk: "pid",
				"label": "Gene Expression",
				tableData: true
			},
			"default": {
				"label": "Items",
				tableData: true
			}
		},

		_setContainerTypeAttr: function(val){
			// console.log("setContainerType: ", val);
			var label;
			this.containerType = val;

			var conf = this.downloadableConfig[val] || this.downloadableConfig["default"];

			this.set("label", conf.label);

			if(!this._started){
				return;
			}

			domConstruct.empty(this.otherDownloadNode);

			if(conf.otherData){
				conf.otherData.forEach(function(type){
					domConstruct.create("div", {
						"class": "wsActionTooltip",
						rel: type,
						innerHTML: this.downloadableDataTypes[type]
					}, this.otherDownloadNode);
				}, this);
			}

			if(conf.advanced){
				domClass.remove(this.advancedDownloadButton, "dijitHidden");
			}else{
				domClass.add(this.advancedDownloadButton, "dijitHidden");
			}

		}
	});

});
<|endoftext|>