<commit_before>const ahk_js = require('../ahk.js');

describe('_load_get', () => {
    var empty = {};
    it('returns empty for empty query', () => {
        expect(ahk_js._load_get('ahkgen.com/'))
        .toEqual(empty);
    });

    it('takes values into object', () => {
        expect(ahk_js._load_get('ahkgen.com/?length=0'))
        .toEqual({'length': "0"});
    });

    it('takes array values into array', () =>{
        expect(ahk_js._load_get('ahkgen.com/?skey0%5B%5D=CTRL&skey0%5B%5D=ALT'))
        .toEqual({'skey0[]': ['CTRL', 'ALT']})
    });

    it('takes index array and turns into array', () =>{
        expect(ahk_js._load_get('ahkgen.com/?indexes%5B%5D=0'))
        .toEqual({'indexes[]': ['0']})
    });

    it('takes duplicate values into array', () =>{
        expect(ahk_js._load_get('ahkgen.com/?skey0=CTRL&skey0=ALT'))
        .toEqual({'skey0': ['CTRL', 'ALT']})
    });

    it('takes a basic query and returns expected data', () => {
        const result = ahk_js
            ._load_get('ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Replace');
        expect(result).toMatchSnapshot();
    })

    it('takes data in regardless of values', () => {
        const result = ahk_js
            ._load_get('ahkgen.com/?length=1&comment5=&func5=KEY&skeyValue5=a&input5=b&option5=Replace');
        expect(result).toMatchSnapshot();
    });
})

describe('_parse_get', () => {
    var empty = {};
    it('returns empty for empty', () => {
        expect(ahk_js._parse_get({})).toEqual(empty)
    });

    describe('takes a basic config and returns expected::', ()=> {
        it('returns promptly if not enough data is passed', () => {
            expect(ahk_js._parse_get({'length': '5'})).toHaveProperty('ERROR');
        });
        it('returns an error if length is not provided', () => {
            expect(ahk_js._parse_get({FOO:'bar'})).toHaveProperty('ERROR');
        });
        it('packs values down to lowest index', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment5=&func5=KEY&skeyValue5=a&input5=b&option5=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('packs values down to lowest index', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment5=&func5=KEY&skeyValue5=a&input5=b&option5=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a basic send value correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        })
        it('parses a basic send value correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/indexes%5B%5D=01&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        })
        it('parses a basic replace correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Replace'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a basic replace correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Replace'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (ctrl)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=CTRL&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (ctrl)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=CTRL&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (shift)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=SHIFT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (shift)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=SHIFT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt, shift, win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=SHIFT&skey0%5B%5D=ALT&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt, shift, win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=SHIFT&skey0%5B%5D=ALT&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an Activate Or Open correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&Window0=ahk_exe+chrome.exe&Program0=chrome.exe&option0=ActivateOrOpen'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an Activate Or Open correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=a&Window0=ahk_exe+chrome.exe&Program0=chrome.exe&option0=ActivateOrOpen'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&input0=0x00A2&option0=SendUnicodeChar'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&input0=0x00A2&option0=SendUnicodeChar'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&Window0=pandora&Program0=pandora.com&option0=ActivateOrOpenChrome'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&Window0=pandora&Program0=pandora.com&option0=ActivateOrOpenChrome'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an OpenConfig correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&option0=OpenConfig'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an OpenConfig correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&option0=OpenConfig'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Custom correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&Code0=send%2C+a&option0=Custom'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Custom correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&Code0=send%2C+a&option0=Custom'
            ))
            expect(result).toMatchSnapshot();
        });
    })
})
<commit_msg>format doc<commit_after>const ahk_js = require('../ahk.js');

describe('_load_get', () => {
    var empty = {};
    it('returns empty for empty query', () => {
        expect(ahk_js._load_get('ahkgen.com/'))
        .toEqual(empty);
    });

    it('takes values into object', () => {
        expect(ahk_js._load_get('ahkgen.com/?length=0'))
            .toEqual({ 'length': "0" });
    });

    it('takes array values into array', () => {
        expect(ahk_js._load_get('ahkgen.com/?skey0%5B%5D=CTRL&skey0%5B%5D=ALT'))
            .toEqual({ 'skey0[]': ['CTRL', 'ALT'] })
    });

    it('takes index array and turns into array', () => {
        expect(ahk_js._load_get('ahkgen.com/?indexes%5B%5D=0'))
            .toEqual({ 'indexes[]': ['0'] })
    });

    it('takes duplicate values into array', () => {
        expect(ahk_js._load_get('ahkgen.com/?skey0=CTRL&skey0=ALT'))
            .toEqual({ 'skey0': ['CTRL', 'ALT'] })
    });

    it('takes a basic query and returns expected data', () => {
        const result = ahk_js
            ._load_get('ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Replace');
        expect(result).toMatchSnapshot();
    })

    it('takes data in regardless of values', () => {
        const result = ahk_js
            ._load_get('ahkgen.com/?length=1&comment5=&func5=KEY&skeyValue5=a&input5=b&option5=Replace');
        expect(result).toMatchSnapshot();
    });
})

describe('_parse_get', () => {
    var empty = {};
    it('returns empty for empty', () => {
        expect(ahk_js._parse_get({})).toEqual(empty)
    });

    describe('takes a basic config and returns expected::', () => {
        it('returns promptly if not enough data is passed', () => {
            expect(ahk_js._parse_get({ 'length': '5' })).toHaveProperty('ERROR');
        });
        it('returns an error if length is not provided', () => {
            expect(ahk_js._parse_get({ FOO: 'bar' })).toHaveProperty('ERROR');
        });
        it('packs values down to lowest index', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment5=&func5=KEY&skeyValue5=a&input5=b&option5=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('packs values down to lowest index', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment5=&func5=KEY&skeyValue5=a&input5=b&option5=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a basic send value correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        })
        it('parses a basic send value correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/indexes%5B%5D=01&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        })
        it('parses a basic replace correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Replace'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a basic replace correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=a&input0=b&option0=Replace'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (ctrl)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=CTRL&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (ctrl)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=CTRL&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (shift)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=SHIFT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (shift)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=SHIFT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a modifier keys correctly (win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=ALT&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt, shift, win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=SHIFT&skey0%5B%5D=ALT&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a group modifier keys correctly (ctrl, alt, shift, win)', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skey0%5B%5D=CTRL&skey0%5B%5D=SHIFT&skey0%5B%5D=ALT&skey0%5B%5D=WIN&skeyValue0=a&input0=b&option0=Send'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an Activate Or Open correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=a&Window0=ahk_exe+chrome.exe&Program0=chrome.exe&option0=ActivateOrOpen'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an Activate Or Open correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=a&Window0=ahk_exe+chrome.exe&Program0=chrome.exe&option0=ActivateOrOpen'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&input0=0x00A2&option0=SendUnicodeChar'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&input0=0x00A2&option0=SendUnicodeChar'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&Window0=pandora&Program0=pandora.com&option0=ActivateOrOpenChrome'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Send Unicode Char correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&Window0=pandora&Program0=pandora.com&option0=ActivateOrOpenChrome'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an OpenConfig correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&option0=OpenConfig'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses an OpenConfig correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&option0=OpenConfig'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Custom correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?length=1&comment0=&func0=KEY&skeyValue0=b&Code0=send%2C+a&option0=Custom'
            ))
            expect(result).toMatchSnapshot();
        });
        it('parses a Custom correctly', () => {
            const result = ahk_js
            ._parse_get(ahk_js._load_get(
                'ahkgen.com/?indexes%5B%5D=0&comment0=&func0=KEY&skeyValue0=b&Code0=send%2C+a&option0=Custom'
            ))
            expect(result).toMatchSnapshot();
        });
    })
})
<|endoftext|>


<commit_before>/**
 * circus-common.js - contains codes widely used throughout the CIRCUS system.
 *
 * Currently this file contains scripts for dynamic layout elements.
 */

//Initialize
$(function(){
	// Enable rollover actions for elements with these classes
	$('.jq-btn').rolloverBtn();
	// Process elements with 'form-btn' and 'radio-to-button' classes
	$('body').autoStylize();
	// Adjust container height
	$('#container').height($(document).height() - 10);
});

$.fn.autoStylize = function() {
	return this.each(function() {
		var _this = $(this);
		_this.find('.radio-to-button').andSelf().filter('.radio-to-button').radioToButton({
			normal: 'radio-to-button-normal',
			hover: 'radio-to-button-hover',
			checked: 'radio-to-button-checked',
			disabled: 'radio-to-button-disabled'
		});
		_this.find('.form-btn').andSelf().filter('.form-btn').hoverStyle({
			normal: 'form-btn-normal',
			hover: 'form-btn-hover',
			disabled: 'form-btn-disabled'
		});
	});
}

// 'rollOverBtn' applies mouseover/mouseout handlers to highlight the target
// element by moving the background position.
$.fn.rolloverBtn = function(_switch) {
	return this.each(function() {
		var _this = $(this);
		if (!_this.data('rolloverBtnInit'))
		{
			_this
				.hover(
					function() {
						_this.css('background-position', '0 ' + _this.height() + 'px');
					},
					function(){ _this.css('background-position', '0 0'); }
				)
				.data('rolloverBtnInit', true);
		}
	});
};

// 'hoverStyle' applies CSS classes for 'disabled', 'hover' and 'normal' status.
$.fn.hoverStyle = function(styles) {
	return this.each(function() {
		var _this = $(this);
		var setStyle = function(hover)
		{
			$.each(styles, function(k, v) { _this.removeClass(v); });
			if (_this.attr('disabled')) {
				_this.addClass(styles['disabled']);
			} else if (hover) {
				_this.addClass(styles['hover']);
			} else {
				_this.addClass(styles['normal']);
			}
		};
		var flush = function() { setStyle(false); };
		_this
			.hover(
				function() { setStyle(true) },
				function() { setStyle(false) }
			)
			.bind('flush', function() { flush(); });
		flush();
	});
};

// 'radioToButton' can make radio buttons have appearance of normal buttons.
$.fn.radioToButton = function(styles) {
	return this.each(function() {
		var _radio = $(this);
		if (!_radio.is('input[type=radio]')) return;
		if (_radio.data('radioToButtonInit')) return;
		if (_radio.attr('label').length == 0) return;
		var setStyle = function(hover)
		{
			$.each(styles, function(k, v) { btn.removeClass(v); });
			if (_radio.attr('checked'))
			{
				btn.addClass(styles['checked']);
			} else if (_radio.attr('disabled')) {
				btn.addClass(styles['disabled']);
			} else if (hover) {
				btn.addClass(styles['hover']);
			} else {
				btn.addClass(styles['normal']);
			}
		};
		var flush = function() { setStyle(false); };
		var btn = $('<a>')
			.addClass(_radio.attr('className'))
			.text(_radio.attr('label'))
			.attr('title', _radio.attr('title'))
			.hover(
				function() { setStyle(true); },
				function() { setStyle(false); }
			)
			.click(function(){
				_radio.click();
				var container = $(_radio).closest('form');
				if (container.length == 0) container = $('body');
				$(':radio[name='+_radio.attr('name')+']', container).trigger('flush');
				return false;
			})
			.insertAfter(_radio);
		_radio
			.bind('flush', function() { flush(); })
			.hide(0)
			.data('radioToButtonInit', true);
		flush();
	});
};
<commit_msg>Re-adjust container height on window resize.<commit_after>/**
 * circus-common.js - contains codes widely used throughout the CIRCUS system.
 *
 * Currently this file contains scripts for dynamic layout elements.
 */

//Initialize
$(function(){
	// Enable rollover actions for elements with these classes
	$('.jq-btn').rolloverBtn();
	// Process elements with 'form-btn' and 'radio-to-button' classes
	$('body').autoStylize();
	// Adjust container height
	var resized = function() {
		$('#container').height($(document).height() - 10);
	};
	$(window).bind('resize', resized);
	resized();
});

$.fn.autoStylize = function() {
	return this.each(function() {
		var _this = $(this);
		_this.find('.radio-to-button').andSelf().filter('.radio-to-button').radioToButton({
			normal: 'radio-to-button-normal',
			hover: 'radio-to-button-hover',
			checked: 'radio-to-button-checked',
			disabled: 'radio-to-button-disabled'
		});
		_this.find('.form-btn').andSelf().filter('.form-btn').hoverStyle({
			normal: 'form-btn-normal',
			hover: 'form-btn-hover',
			disabled: 'form-btn-disabled'
		});
	});
}

// 'rollOverBtn' applies mouseover/mouseout handlers to highlight the target
// element by moving the background position.
$.fn.rolloverBtn = function(_switch) {
	return this.each(function() {
		var _this = $(this);
		if (!_this.data('rolloverBtnInit'))
		{
			_this
				.hover(
					function() {
						_this.css('background-position', '0 ' + _this.height() + 'px');
					},
					function(){ _this.css('background-position', '0 0'); }
				)
				.data('rolloverBtnInit', true);
		}
	});
};

// 'hoverStyle' applies CSS classes for 'disabled', 'hover' and 'normal' status.
$.fn.hoverStyle = function(styles) {
	return this.each(function() {
		var _this = $(this);
		var setStyle = function(hover)
		{
			$.each(styles, function(k, v) { _this.removeClass(v); });
			if (_this.attr('disabled')) {
				_this.addClass(styles['disabled']);
			} else if (hover) {
				_this.addClass(styles['hover']);
			} else {
				_this.addClass(styles['normal']);
			}
		};
		var flush = function() { setStyle(false); };
		_this
			.hover(
				function() { setStyle(true) },
				function() { setStyle(false) }
			)
			.bind('flush', function() { flush(); });
		flush();
	});
};

// 'radioToButton' can make radio buttons have appearance of normal buttons.
$.fn.radioToButton = function(styles) {
	return this.each(function() {
		var _radio = $(this);
		if (!_radio.is('input[type=radio]')) return;
		if (_radio.data('radioToButtonInit')) return;
		if (_radio.attr('label').length == 0) return;
		var setStyle = function(hover)
		{
			$.each(styles, function(k, v) { btn.removeClass(v); });
			if (_radio.attr('checked'))
			{
				btn.addClass(styles['checked']);
			} else if (_radio.attr('disabled')) {
				btn.addClass(styles['disabled']);
			} else if (hover) {
				btn.addClass(styles['hover']);
			} else {
				btn.addClass(styles['normal']);
			}
		};
		var flush = function() { setStyle(false); };
		var btn = $('<a>')
			.addClass(_radio.attr('className'))
			.text(_radio.attr('label'))
			.attr('title', _radio.attr('title'))
			.hover(
				function() { setStyle(true); },
				function() { setStyle(false); }
			)
			.click(function(){
				_radio.click();
				var container = $(_radio).closest('form');
				if (container.length == 0) container = $('body');
				$(':radio[name='+_radio.attr('name')+']', container).trigger('flush');
				return false;
			})
			.insertAfter(_radio);
		_radio
			.bind('flush', function() { flush(); })
			.hide(0)
			.data('radioToButtonInit', true);
		flush();
	});
};
<|endoftext|>


<commit_before>/*globals require: false, exports: false*/

;(function (factory) {
	'use strict';
	// Module system.

	if (typeof exports !== 'undefined') {
		module.exports = factory(require('jquery'), require('slick-carousel'), require('isotope-layout'), require('isotope-packery'));
	} else {
		factory(jQuery);
	}

}(function factory($) {
		'use strict';

		var PAGE_CONFIG = {
			HEADER: {
				SLIDER_CONFIG: {
					dots: true,
					lazyLoad: 'ondemand',
					infinite: true,
					speed: 300,
					slidesToShow: 1,
					slidesToScroll: 1,
					autoplay: true,
					autoplaySpeed: 10000,
					fade: true,
					cssEase: 'linear',
				}
			},
			GALLERY: {
				SLIDER_CONFIG: {
					dots: false,
					arrows: false,
					lazyLoad: 'ondemand',
					infinite: true,
					speed: 1000,
					slidesToShow: 1,
					slidesToScroll: 1,
					autoplay: true,
					autoplaySpeed: 2000,
					fade: false,
					cssEase: 'linear'
				},
				LAYOUT_CONFIG: {
					layoutMode: 'packery',
					itemSelector: '.grid-item',
					transitionDuration: 0
				},
				GRID: {
					animation: {
						properties: {
							opacity: 1
						},
						duration: 400
					},
					rows: 3,
					cols: 4,
					tall: 1, // 1.2
					wide: 1, // 2.1
					shuffleOrder: true, // if document ORDER is metter
					getSize: function () {
						var result = this.rows * this.cols;

						// mobile view all cards should be 1.1
						if (window.innerWidth <= 797) {
							return result;
						}
						return  result - (this.tall + this.wide);
					},
					getAnimProps: function () {
						return Object.values(Object.keys(this.animation.properties)).join(' ');
					}
				}
			}
		},
			size = 1200,
			initialWindowWidth;

		depsCheck();

		/**
		 * Checks dep's for this module/script
		 * @param $
		 * @returns {boolean}
		 */
		function depsCheck() {
			var str =  'is required, please ensure it is loaded before loading this script!',
				error;

			if (typeof $ === 'undefined') {
				error = `jQuery.js ${str}`;
			} else if (typeof ($.fn.slick) === 'undefined') {
				error = `Slick.js (http://kenwheeler.github.io/slick) ${str}`;
			} else if (typeof ($.fn.isotope) === 'undefined') {
				error = `Isotope.js (http://isotope.metafizzy.co) ${str}`;
			} else {
				return true;
			}
			throw new Error(error);
		}

		/**
		 * Initialization of 'Slick' slider
		 * @param $root
		 * @param config
		 * @returns {boolean}
		 */
		function initSlider($root, config) {
			if ($root.hasClass('slick-initialized') || $root.children().length < 2) {return false}
			$root.length && $root.slick(config);
			return true;
		}

		/**
		 * Sets 'flip' effect to cards
		 * @param $cards
		 */
		function initCardFlipper($cards) {
			$cards.each(function() {
				var me = $(this);
				me.hover(function() {
					me.toggleClass('applyflip');
				});
			});
		}

		/**
		 * Initialization of Isotope grid for gallery
		 * @param $root {object} root element for grid
		 * @param config {object} config for isotope grid
		 */
		function initGalleryGrid($root, config) {
			return $root.isotope(config || PAGE_CONFIG.GALLERY.LAYOUT_CONFIG || {});
		}

		/**
		 * Sets all Event listeners on page
		 * @param $rootTarget
		 */
		function setEventListeners($rootTarget) {
			if (typeof $rootTarget === 'undefined') {
				$rootTarget = $(document);
			}

			$rootTarget
				.on('click touch', '#tab-dropdown li, #tab-controlls li', function(e) {
					var text = $(this)
							.find('.tab')
							.text(),
						$tab = $('.tab:contains("' + text + '")');

					$('#tab-dropdown li, #tab-controlls li')
						.removeClass('active')
						.find('.tab')
						.removeAttr('aria-expanded');

					$tab
						.attr('aria-expanded', true)
						.parent()
						.addClass('active');

					$('#tab-dropdown-label').text(text);

					$('#tab-dropdown').removeClass('open');
					// init show-more on active tab-pane
					showMoreToggle($('.active .grid'));
				})
				.on('click touch', '#gallery-show-more', function(e) {
					var selector = $(this).attr('aria-controls');

					e.stopPropagation();
					$('.grid.slick-initialized').slick('unslick');
					$(selector).addClass('more');
					$(this).addClass('hide');
				})
				.on('click touch', '#top-show-more', function(e) {
					var selector = $(this).attr('aria-controls');

					e.stopPropagation();
					$(selector).addClass('more');
					$(this).addClass('hide');
				})
				.on('click touch', '.btn-like:enabled', function(e) {
					var count = $(this).parent('.like').find('.count');

					e.stopPropagation();
					e.preventDefault();
					count.text(+count.text() + 1);
					$(this).attr('disabled', true);
				})
				.on('shown.bs.tab', 'a[data-toggle="tab"]', function(e) {
				 /**
					* [Bootstrap tabs event]
					* Fires on tab show after a tab has been shown.
					* Use event.target and event.relatedTarget to target the active tab and
					* the previous active tab (if available) respectively.
					* http://getbootstrap.com/javascript/#tabs
					*/
					reInitTabPane();
				})
				.on('resize', 'window', function() {
					var $cards = $('.card'),
						windowWidth = window.innerWidth;

					setColsRowsSize(windowWidth, PAGE_CONFIG.GALLERY.GRID);

					reInitTabPane();

					if ((windowWidth <= size && $cards.hasClass('card')) ||
						(windowWidth > size && !$cards.hasClass('card'))) {

						$cards.toggleClass('card static-card');
					}
				});
		}

		function reInitTabPane() {

			var CONFIG = PAGE_CONFIG.GALLERY;

			// resets all animation props
			$(CONFIG.LAYOUT_CONFIG.itemSelector || '.grid-item').css(CONFIG.GRID.getAnimProps(), '');

			// resets 'show more state'
			$('.grid.more').removeClass('more');

			// unbinds slider from unactive tab-pane
			$('.grid.slick-initialized').slick('unslick');

			// init gallery grid on active tab-pane
			initGalleryGrid($('.active .gallery-slide'));

			// init slider on active tab-pane
			initSlider($('.active .grid'), CONFIG.SLIDER_CONFIG);

			// init show-more on active tab-pane
			showMoreToggle($('.active .grid'));

			// runs animation of cards
			cardsAnimation();
		}

		/**
		 * Inits animation effect on cards
		 * @param $target {object} $ collection
		 */
		function cardsAnimation($target) {
			var stepTime = 100,
				$collection = $('.active .gallery-slide:not(.slick-cloned)')
					.find($target || PAGE_CONFIG.GALLERY.LAYOUT_CONFIG.itemSelector || '.grid-item');

			$collection.each(function (i) {
				var $this = $(this);
				setTimeout((function(x) {
					return function() {
						$this.animate(PAGE_CONFIG.GALLERY.GRID.animation.properties, PAGE_CONFIG.GALLERY.GRID.animation.duration || 400);
					}
				}(i)), stepTime + stepTime * i);
			});
		}

		/**
		 * Prepares the grid for further manipulations
		 * @param $grid
		 */
		function bildTheGrid($grid) {
			var GRID_CONFIG = PAGE_CONFIG.GALLERY.GRID;

			$grid.each(function () {
				var $tabGrid = $(this),
					$gridItemsArr = $tabGrid.find('.grid-item'),
					$slideTemplate = $('
'),
					$slide,
					count = 0;

				if (GRID_CONFIG.shuffleOrder) {
					shuffle($gridItemsArr);
				}

				$gridItemsArr.each(function (index) {
					var $card = $(this);

					// break items by slides
					if (index % GRID_CONFIG.getSize() === 0) {
						// create new slide
						$slide = $slideTemplate
							.clone()
							.addClass(`slide-${count++}`);

						// appending slide to tabGrid
						$tabGrid.append($slide);
					}

					// appending card to slide
					$slide.append($card);
				});

				// autocomplits slides by card copies
				setAutocomplit($slide, GRID_CONFIG.getSize());

				showMoreToggle($tabGrid, count);
			});
		}

		/**
		 * Show more option init
		 * @param $tabGrid
		 * @param count
		 */
		function showMoreToggle($tabGrid, count) {
			var slidesCount = count || $tabGrid.find('.gallery-slide').length;

			if (slidesCount > 1) {
				$tabGrid.next('.show-more').removeClass('hide');
			}
		}

		/**
		 * Autocomplits slide with clones of its own cards (from start) if it needs
		 * @param $slide
		 * @param size
		 */
		function setAutocomplit($slide, size) {
			var $arr = $slide.find('.grid-item'),
				arrLength = $arr.length;

			for (var i = 0, length = size - arrLength; i < length; i++) {
				if (arrLength < size) {
					$slide.append($arr.eq(i % arrLength).clone().attr('data-size', '1.1'));
				}
			}
		}

		/**
		 * Controls logic conected with sizes of cards
		 * @param $grid
		 * @returns {boolean}
		 */
		function setRandomCardSize($grid) {
			$grid.each(function () {
				var $tabGrid = $(this),
					GRID_SIZE = PAGE_CONFIG.GALLERY.GRID.getSize(); // 9

				$tabGrid
					.find('.gallery-slide')
					.each(function () {
						var $slide = $(this),
							index = randomNum(1, GRID_SIZE - 1),
							index2,
							arr;

						do {
							index2 = randomNum(1, GRID_SIZE < 9 ? 3: 6)
						} while (index === index2);

						arr = $slide.find(PAGE_CONFIG.GALLERY.LAYOUT_CONFIG.itemSelector || '.grid-item');
						arr.eq(index).attr('data-size', '2.1');
						arr.eq(index2).attr('data-size', '1.2');
					});
			});
			return true;
		}

		/**
		 * Returns random number from setted range
		 * Helper func
		 * @param s
		 * @param e
		 * @returns {*}
		 */
		function randomNum(s, e) {
			var start = s || 1, end = e || 8;

			return Math.floor(Math.random() * 10) % end + start;
		}

		/**
		 * Changes grid dimensions depending on screen size
		 * @param num {number} current window size
		 * @param obj {object} grid dimensions
		 */
		function setColsRowsSize(num, obj) {
			if (num > 1044) {
				obj.rows = 3;
				obj.cols = 4;
			} else if (797 < num && num <= 1044) {
				obj.rows = 3;
				obj.cols = 3;
			} else if (510 < num && num <= 797) {
				obj.rows = 4;
				obj.cols = 3;
			} else if (num <= 510)  {
				obj.rows = 4;
				obj.cols = 2;
			}
		}

		/**
		 * Shuffles array in random way
		 * @param array {array}
		 * @returns {array}
		 */
		function shuffle(array) {
			var currentIndex = array.length,
				temporaryValue,
				randomIndex;

			// While there remain elements to shuffle...
			while (0 !== currentIndex) {

				// Pick a remaining element...
				randomIndex = Math.floor(Math.random() * currentIndex);
				currentIndex -= 1;

				// And swap it with the current element.
				temporaryValue = array[currentIndex];
				array[currentIndex] = array[randomIndex];
				array[randomIndex] = temporaryValue;
			}

			return array;
		}

		/**
		 * function that executes when Dom is ready
		 */
		$(function () {
			var text = $('#tab-controlls > li.active').text(),
				$grid = $('.grid'),
				$cards = $('.card'),
				$tab,
				initialWindowWidth = window.innerWidth;

			$('#tab-dropdown-label').text(text);

			setColsRowsSize(initialWindowWidth, PAGE_CONFIG.GALLERY.GRID);

			if (initialWindowWidth <= size) {
				$cards.toggleClass('card static-card');
				$tab = $('.tab:contains("' + text + '")');

				$tab
					.attr('aria-expanded', true)
					.parent()
					.addClass('active');
			}

			initSlider($('#myCarousel'), PAGE_CONFIG.HEADER.SLIDER_CONFIG);

			bildTheGrid($grid);

			setRandomCardSize($grid);

			initGalleryGrid($('.active .gallery-slide'));

			initCardFlipper($('.card'));

			initSlider($('.active .grid'), PAGE_CONFIG.GALLERY.SLIDER_CONFIG);

			cardsAnimation();

			setEventListeners();
		});

		// module revile interface
		return {
			initSlider: initSlider,
			initCardFlipper: initCardFlipper,
			initGalleryGrid: initGalleryGrid
		}
	}));
<commit_msg>[TKMDPA-4073][js] ES6 to ES5 strings chnge for S&D2<commit_after>/*globals require: false, exports: false*/

;(function (factory) {
	'use strict';
	// Module system.

	if (typeof exports !== 'undefined') {
		module.exports = factory(require('jquery'), require('slick-carousel'), require('isotope-layout'), require('isotope-packery'));
	} else {
		factory(jQuery);
	}

}(function factory($) {
		'use strict';

		var PAGE_CONFIG = {
			HEADER: {
				SLIDER_CONFIG: {
					dots: true,
					lazyLoad: 'ondemand',
					infinite: true,
					speed: 300,
					slidesToShow: 1,
					slidesToScroll: 1,
					autoplay: true,
					autoplaySpeed: 10000,
					fade: true,
					cssEase: 'linear',
				}
			},
			GALLERY: {
				SLIDER_CONFIG: {
					dots: false,
					arrows: false,
					lazyLoad: 'ondemand',
					infinite: true,
					speed: 1000,
					slidesToShow: 1,
					slidesToScroll: 1,
					autoplay: true,
					autoplaySpeed: 2000,
					fade: false,
					cssEase: 'linear'
				},
				LAYOUT_CONFIG: {
					layoutMode: 'packery',
					itemSelector: '.grid-item',
					transitionDuration: 0
				},
				GRID: {
					animation: {
						properties: {
							opacity: 1
						},
						duration: 400
					},
					rows: 3,
					cols: 4,
					tall: 1, // 1.2
					wide: 1, // 2.1
					shuffleOrder: true, // if document ORDER is metter
					getSize: function () {
						var result = this.rows * this.cols;

						// mobile view all cards should be 1.1
						if (window.innerWidth <= 797) {
							return result;
						}
						return  result - (this.tall + this.wide);
					},
					getAnimProps: function () {
						return Object.values(Object.keys(this.animation.properties)).join(' ');
					}
				}
			}
		},
			size = 1200,
			initialWindowWidth;

		depsCheck();

		/**
		 * Checks dep's for this module/script
		 * @param $
		 * @returns {boolean}
		 */
		function depsCheck() {
			var str =  ' is required, please ensure it is loaded before loading this script!',
				error;

			if (typeof $ === 'undefined') {
				error = 'jQuery.js' + str;
			} else if (typeof ($.fn.slick) === 'undefined') {
				error = 'Slick.js (http://kenwheeler.github.io/slick)'+ str;
			} else if (typeof ($.fn.isotope) === 'undefined') {
				error = 'Isotope.js (http://isotope.metafizzy.co)' + str;
			} else {
				return true;
			}
			throw new Error(error);
		}

		/**
		 * Initialization of 'Slick' slider
		 * @param $root
		 * @param config
		 * @returns {boolean}
		 */
		function initSlider($root, config) {
			if ($root.hasClass('slick-initialized') || $root.children().length < 2) {return false}
			$root.length && $root.slick(config);
			return true;
		}

		/**
		 * Sets 'flip' effect to cards
		 * @param $cards
		 */
		function initCardFlipper($cards) {
			$cards.each(function() {
				var me = $(this);
				me.hover(function() {
					me.toggleClass('applyflip');
				});
			});
		}

		/**
		 * Initialization of Isotope grid for gallery
		 * @param $root {object} root element for grid
		 * @param config {object} config for isotope grid
		 */
		function initGalleryGrid($root, config) {
			return $root.isotope(config || PAGE_CONFIG.GALLERY.LAYOUT_CONFIG || {});
		}

		/**
		 * Sets all Event listeners on page
		 * @param $rootTarget
		 */
		function setEventListeners($rootTarget) {
			if (typeof $rootTarget === 'undefined') {
				$rootTarget = $(document);
			}

			$rootTarget
				.on('click touch', '#tab-dropdown li, #tab-controlls li', function(e) {
					var text = $(this)
							.find('.tab')
							.text(),
						$tab = $('.tab:contains("' + text + '")');

					$('#tab-dropdown li, #tab-controlls li')
						.removeClass('active')
						.find('.tab')
						.removeAttr('aria-expanded');

					$tab
						.attr('aria-expanded', true)
						.parent()
						.addClass('active');

					$('#tab-dropdown-label').text(text);

					$('#tab-dropdown').removeClass('open');
					// init show-more on active tab-pane
					showMoreToggle($('.active .grid'));
				})
				.on('click touch', '#gallery-show-more', function(e) {
					var selector = $(this).attr('aria-controls');

					e.stopPropagation();
					$('.grid.slick-initialized').slick('unslick');
					$(selector).addClass('more');
					$(this).addClass('hide');
				})
				.on('click touch', '#top-show-more', function(e) {
					var selector = $(this).attr('aria-controls');

					e.stopPropagation();
					$(selector).addClass('more');
					$(this).addClass('hide');
				})
				.on('click touch', '.btn-like:enabled', function(e) {
					var count = $(this).parent('.like').find('.count');

					e.stopPropagation();
					e.preventDefault();
					count.text(+count.text() + 1);
					$(this).attr('disabled', true);
				})
				.on('shown.bs.tab', 'a[data-toggle="tab"]', function(e) {
				 /**
					* [Bootstrap tabs event]
					* Fires on tab show after a tab has been shown.
					* Use event.target and event.relatedTarget to target the active tab and
					* the previous active tab (if available) respectively.
					* http://getbootstrap.com/javascript/#tabs
					*/
					reInitTabPane();
				})
				.on('resize', 'window', function() {
					var $cards = $('.card'),
						windowWidth = window.innerWidth;

					setColsRowsSize(windowWidth, PAGE_CONFIG.GALLERY.GRID);

					reInitTabPane();

					if ((windowWidth <= size && $cards.hasClass('card')) ||
						(windowWidth > size && !$cards.hasClass('card'))) {

						$cards.toggleClass('card static-card');
					}
				});
		}

		function reInitTabPane() {

			var CONFIG = PAGE_CONFIG.GALLERY;

			// resets all animation props
			$(CONFIG.LAYOUT_CONFIG.itemSelector || '.grid-item').css(CONFIG.GRID.getAnimProps(), '');

			// resets 'show more state'
			$('.grid.more').removeClass('more');

			// unbinds slider from unactive tab-pane
			$('.grid.slick-initialized').slick('unslick');

			// init gallery grid on active tab-pane
			initGalleryGrid($('.active .gallery-slide'));

			// init slider on active tab-pane
			initSlider($('.active .grid'), CONFIG.SLIDER_CONFIG);

			// init show-more on active tab-pane
			showMoreToggle($('.active .grid'));

			// runs animation of cards
			cardsAnimation();
		}

		/**
		 * Inits animation effect on cards
		 * @param $target {object} $ collection
		 */
		function cardsAnimation($target) {
			var stepTime = 100,
				$collection = $('.active .gallery-slide:not(.slick-cloned)')
					.find($target || PAGE_CONFIG.GALLERY.LAYOUT_CONFIG.itemSelector || '.grid-item');

			$collection.each(function (i) {
				var $this = $(this);
				setTimeout((function(x) {
					return function() {
						$this.animate(PAGE_CONFIG.GALLERY.GRID.animation.properties, PAGE_CONFIG.GALLERY.GRID.animation.duration || 400);
					}
				}(i)), stepTime + stepTime * i);
			});
		}

		/**
		 * Prepares the grid for further manipulations
		 * @param $grid
		 */
		function bildTheGrid($grid) {
			var GRID_CONFIG = PAGE_CONFIG.GALLERY.GRID;

			$grid.each(function () {
				var $tabGrid = $(this),
					$gridItemsArr = $tabGrid.find('.grid-item'),
					$slideTemplate = $('
'),
					$slide,
					count = 0;

				if (GRID_CONFIG.shuffleOrder) {
					shuffle($gridItemsArr);
				}

				$gridItemsArr.each(function (index) {
					var $card = $(this);

					// break items by slides
					if (index % GRID_CONFIG.getSize() === 0) {
						// create new slide
						$slide = $slideTemplate
							.clone()
							.addClass(`slide-${count++}`);

						// appending slide to tabGrid
						$tabGrid.append($slide);
					}

					// appending card to slide
					$slide.append($card);
				});

				// autocomplits slides by card copies
				setAutocomplit($slide, GRID_CONFIG.getSize());

				showMoreToggle($tabGrid, count);
			});
		}

		/**
		 * Show more option init
		 * @param $tabGrid
		 * @param count
		 */
		function showMoreToggle($tabGrid, count) {
			var slidesCount = count || $tabGrid.find('.gallery-slide').length;

			if (slidesCount > 1) {
				$tabGrid.next('.show-more').removeClass('hide');
			}
		}

		/**
		 * Autocomplits slide with clones of its own cards (from start) if it needs
		 * @param $slide
		 * @param size
		 */
		function setAutocomplit($slide, size) {
			var $arr = $slide.find('.grid-item'),
				arrLength = $arr.length;

			for (var i = 0, length = size - arrLength; i < length; i++) {
				if (arrLength < size) {
					$slide.append($arr.eq(i % arrLength).clone().attr('data-size', '1.1'));
				}
			}
		}

		/**
		 * Controls logic conected with sizes of cards
		 * @param $grid
		 * @returns {boolean}
		 */
		function setRandomCardSize($grid) {
			$grid.each(function () {
				var $tabGrid = $(this),
					GRID_SIZE = PAGE_CONFIG.GALLERY.GRID.getSize(); // 9

				$tabGrid
					.find('.gallery-slide')
					.each(function () {
						var $slide = $(this),
							index = randomNum(1, GRID_SIZE - 1),
							index2,
							arr;

						do {
							index2 = randomNum(1, GRID_SIZE < 9 ? 3: 6)
						} while (index === index2);

						arr = $slide.find(PAGE_CONFIG.GALLERY.LAYOUT_CONFIG.itemSelector || '.grid-item');
						arr.eq(index).attr('data-size', '2.1');
						arr.eq(index2).attr('data-size', '1.2');
					});
			});
			return true;
		}

		/**
		 * Returns random number from setted range
		 * Helper func
		 * @param s
		 * @param e
		 * @returns {*}
		 */
		function randomNum(s, e) {
			var start = s || 1, end = e || 8;

			return Math.floor(Math.random() * 10) % end + start;
		}

		/**
		 * Changes grid dimensions depending on screen size
		 * @param num {number} current window size
		 * @param obj {object} grid dimensions
		 */
		function setColsRowsSize(num, obj) {
			if (num > 1044) {
				obj.rows = 3;
				obj.cols = 4;
			} else if (797 < num && num <= 1044) {
				obj.rows = 3;
				obj.cols = 3;
			} else if (510 < num && num <= 797) {
				obj.rows = 4;
				obj.cols = 3;
			} else if (num <= 510)  {
				obj.rows = 4;
				obj.cols = 2;
			}
		}

		/**
		 * Shuffles array in random way
		 * @param array {array}
		 * @returns {array}
		 */
		function shuffle(array) {
			var currentIndex = array.length,
				temporaryValue,
				randomIndex;

			// While there remain elements to shuffle...
			while (0 !== currentIndex) {

				// Pick a remaining element...
				randomIndex = Math.floor(Math.random() * currentIndex);
				currentIndex -= 1;

				// And swap it with the current element.
				temporaryValue = array[currentIndex];
				array[currentIndex] = array[randomIndex];
				array[randomIndex] = temporaryValue;
			}

			return array;
		}

		/**
		 * function that executes when Dom is ready
		 */
		$(function () {
			var text = $('#tab-controlls > li.active').text(),
				$grid = $('.grid'),
				$cards = $('.card'),
				$tab,
				initialWindowWidth = window.innerWidth;

			$('#tab-dropdown-label').text(text);

			setColsRowsSize(initialWindowWidth, PAGE_CONFIG.GALLERY.GRID);

			if (initialWindowWidth <= size) {
				$cards.toggleClass('card static-card');
				$tab = $('.tab:contains("' + text + '")');

				$tab
					.attr('aria-expanded', true)
					.parent()
					.addClass('active');
			}

			initSlider($('#myCarousel'), PAGE_CONFIG.HEADER.SLIDER_CONFIG);

			bildTheGrid($grid);

			setRandomCardSize($grid);

			initGalleryGrid($('.active .gallery-slide'));

			initCardFlipper($('.card'));

			initSlider($('.active .grid'), PAGE_CONFIG.GALLERY.SLIDER_CONFIG);

			cardsAnimation();

			setEventListeners();
		});

		// module revile interface
		return {
			initSlider: initSlider,
			initCardFlipper: initCardFlipper,
			initGalleryGrid: initGalleryGrid
		}
	}));
<|endoftext|>


<commit_before>var tls = require('tls'),
    util = require('util'),
    zlib = require('zlib'),
    Stream = require('stream'),

    parser = require("./parser"),
    bplist = require("./bplist"),
    SiriParser = parser.SiriParser,

    SIRI_SERVER = "17.151.230.4",
    //SIRI_SERVER = "17.174.8.5",
    SIRI_PORT = 443;

function Server(options, commandListener) { // Server {{{
    if (!(this instanceof Server)) return new Server(options, commandListener);
    tls.Server.call(this, options);

    if (commandListener) {
        this.on("command", commandListener);
    }

    this.on("secureConnection", secureConnectionListener);
    this.on("clientError", function(err, conn) {
        conn.destroy(err);
    });
}

util.inherits(Server, tls.Server);

exports.Server = Server;
exports.createServer = function(options, listener) {
    return new Server(options, listener);
}

function secureConnectionListener(clientStream) {
    var self = this,
        clientParser = new SiriParser(parser.SIRI_REQUEST),
        //clientCompressor = zlib.createDeflate(),

        serverStream = tls.connect(SIRI_PORT, SIRI_SERVER),
        serverParser = new SiriParser(parser.SIRI_RESPONSE),
        serverCompressor = zlib.createDeflate(),
        device = new SiriDevice();

    clientStream.pipe(serverStream);
    //只解析请求，不做修改
    //clientCompressor._flush = zlib.Z_SYNC_FLUSH;
    //clientCompressor.pipe(serverStream);
    clientStream.ondata = function(data, start, end) {
        clientParser.parse(data, start, end);
    };
    clientStream.on("end", clientStream.onend = function() {
        console.log("ClientStream end");
    });
    clientStream.on("close", function() {
        console.log("ClientStream close");
    });
    clientParser.onAccept = function(pkg) {
        if (pkg.getType() == parser.PKG_ACE_PLIST) {
            //fs.writeFileSync("data/" + getId() + ".client.json", pkg.rootNode().stringify());
        }
    };

    //准备压缩管道
    serverCompressor._flush = zlib.Z_SYNC_FLUSH;
    device.pipe(serverCompressor).pipe(clientStream);
    //截获服务器信息
    serverStream.ondata = function(data, start, end) {
        serverParser.parse(data, start, end);
    };
    serverStream.on("end", serverStream.onend = function() {
        console.log("ServerStream end");
    });
    serverStream.on("close", function() {
        console.log("ServerStream close");
    });

    serverParser.onAccept = function(pkg) {
        switch (pkg.getType()) {
            case parser.PKG_HTTP_HEADER:
            case parser.PKG_HTTP_ACEHEADER:
            case parser.PKG_HTTP_UNKNOW:
                clientStream.write(pkg.getData());
                break;
            case parser.PKG_ACE_UNKNOW:
                serverCompressor.write(pkg.getData());
                break;
            case parser.PKG_ACE_PLIST:
                //fs.writeFileSync("data/" + getId() + ".server.json", pkg.rootNode().stringify());
                device.receivePackage(pkg);
                break;
            default:
                console.log("Unknow package type:" + pkg.type + "!");
        }
    };
    device.onCommand = function(str) {
        self.emit("command", str, device);
    };

    console.log("Client connect.");
}
// }}}

var WRITE_FORCE = true;

function SiriDevice() { // Device {{{

    Stream.call(this);
    this.writable = false;
    this.readable = true;

    this.serverResponse = [];
    this.proxied = true;
    this.completed = true;

    this.aceId = null;
    this.refId = null;
    this.version = null;
}

util.inherits(SiriDevice, Stream);

function getRecognizedText(obj) {
    var arr;
    if (obj["class"] != "SpeechRecognized") return null;
    arr = [];
    obj.properties.recognition.properties.phrases.forEach(function(item) {
        item.properties.interpretations[0].properties.tokens.forEach(function(item) {
            arr.push(item.properties.text);
        });
    });
    return arr.join("");
}

SiriDevice.prototype.onCommand = function() {
    //Do nothing
};

SiriDevice.prototype.getCompletedPackage = function() {
    return new parser.ACEBinaryPlist(bplist.fromPObject({
        "properties": {
            "callbacks": []
        },
        "refId": "string:" + this.refId,
        "v": "string:" + this.version,
        "class": "string:RequestCompleted",
        "aceId": "string:" + this.aceId,
        "group": "string:com.apple.ace.system"
    }));
};

SiriDevice.prototype.writePackage = function(pkg, check) {
    if (check !== WRITE_FORCE && this.completed) return;
    this.emit('data', pkg.getData());
};

SiriDevice.prototype.receivePackage = function(pkg) {
    var obj = pkg.rootNode().toObject();

    this.refId = obj.refId;
    this.aceId = obj.aceId;
    this.version = obj.v;

    switch (obj["class"]) {
        case "SpeechRecognized":
            this.serverResponse = [];
            this.proxied = false;
            this.completed = false;

            this.writePackage(pkg, WRITE_FORCE);
            this.onCommand(getRecognizedText(obj));
            break;
        default:
            if (this.proxied) {
                this.writePackage(pkg, WRITE_FORCE);
            } else {
                this.serverResponse.push(pkg);
            }
            break;
    }
};

SiriDevice.prototype.proxy = function() {
    var self = this;
    this.serverResponse.forEach(function(pkg, index) {
        self.writePackage(pkg);
    });
    this.proxied = true;
    this.completed = true;
};

SiriDevice.prototype.say = function(str, speakable) {
    this.writePackage(new parser.ACEBinaryPlist(bplist.fromPObject({
        "properties": {
            "temporary": "null:false",
            "dialogPhase": "string:Completion",
            "scrollToTop": "null:false",
            "views": [{
                "class": "string:AssistantUtteranceView",
                "properties": {
                    "dialogIdentifier": "string:Misc#answer",
                    "speakableText": "unicode:" + (speakable === undefined ? str : speakable),
                    "text": "unicode:" + str
                },
                "group": "string:com.apple.ace.assistant"
            }]
        },
        "refId": "string:" + this.refId,
        "v": "string:" + this.version,
        "class": "string:AddViews",
        "aceId": "string:" + this.aceId,
        "group": "string:com.apple.ace.assistant"
    })));
};

SiriDevice.prototype.end = function(str) {
    if (str !== undefined) this.say(str);
    this.writePackage(this.getCompletedPackage());
    this.completed = true;
};
// }}}

//Test
var fs = require("fs"),
    siri = exports,
    tmp = 0;

function getId() {
    tmp++;
    return (tmp < 100 ? "0" : "") + (tmp < 10 ? "0" : "") + tmp;
}

//*
siri.createServer({
    key: fs.readFileSync('./server.passless.key'),
    cert: fs.readFileSync('./server.passless.crt')
}, function(command, device) {
    console.log(command);
    if (command == "你好") {
        device.say("3");
        setTimeout(function() {
            device.say("2");
            setTimeout(function() {
                device.say("1");
                setTimeout(function() {
                    device.end("Siri代理向你问好,哈哈哈!");
                }, 1000);
            }, 1000);
        }, 1000);
    } else {
        device.proxy();
    }
}).listen(4433, function() {
    console.log("Proxy start.");
});
//*/
// vim600: sw=4 ts=4 fdm=marker syn=javascript
<commit_msg>update<commit_after>var tls = require('tls'),
    util = require('util'),
    zlib = require('zlib'),
    Stream = require('stream'),

    parser = require("./parser"),
    bplist = require("./bplist"),
    SiriParser = parser.SiriParser,

    SIRI_SERVER = "17.151.230.4",
    //SIRI_SERVER = "17.174.8.5",
    SIRI_PORT = 443;

function Server(options, commandListener) { // Server {{{
    if (!(this instanceof Server)) return new Server(options, commandListener);
    tls.Server.call(this, options);

    if (commandListener) {
        this.on("command", commandListener);
    }

    this.on("secureConnection", secureConnectionListener);
    this.on("clientError", function(err, conn) {
        conn.destroy(err);
    });
}

util.inherits(Server, tls.Server);

exports.Server = Server;
exports.createServer = function(options, listener) {
    return new Server(options, listener);
}

function secureConnectionListener(clientStream) {
    var self = this,
        clientParser = new SiriParser(parser.SIRI_REQUEST),
        //clientCompressor = zlib.createDeflate(),

        serverStream = tls.connect(SIRI_PORT, SIRI_SERVER),
        serverParser = new SiriParser(parser.SIRI_RESPONSE),
        serverCompressor = zlib.createDeflate(),
        device = new SiriDevice();

    clientStream.pipe(serverStream);
    //只解析请求，不做修改
    //clientCompressor._flush = zlib.Z_SYNC_FLUSH;
    //clientCompressor.pipe(serverStream);
    clientStream.ondata = function(data, start, end) {
        clientParser.parse(data, start, end);
    };
    clientStream.on("end", clientStream.onend = function() {
        console.log("ClientStream end");
    });
    clientStream.on("close", function() {
        console.log("ClientStream close");
    });
    clientParser.onAccept = function(pkg) {
        if (pkg.getType() == parser.PKG_ACE_PLIST) {
            //fs.writeFileSync("data/" + getId() + ".client.json", pkg.rootNode().stringify());
        }
    };

    //准备压缩管道
    serverCompressor._flush = zlib.Z_SYNC_FLUSH;
    device.pipe(serverCompressor).pipe(clientStream);
    //截获服务器信息
    serverStream.ondata = function(data, start, end) {
        serverParser.parse(data, start, end);
    };
    serverStream.on("end", serverStream.onend = function() {
        console.log("ServerStream end");
    });
    serverStream.on("close", function() {
        console.log("ServerStream close");
    });

    serverParser.onAccept = function(pkg) {
        switch (pkg.getType()) {
            case parser.PKG_HTTP_HEADER:
            case parser.PKG_HTTP_ACEHEADER:
            case parser.PKG_HTTP_UNKNOW:
                clientStream.write(pkg.getData());
                break;
            case parser.PKG_ACE_UNKNOW:
                serverCompressor.write(pkg.getData());
                break;
            case parser.PKG_ACE_PLIST:
                //fs.writeFileSync("data/" + getId() + ".server.json", pkg.rootNode().stringify());
                device.receivePackage(pkg);
                break;
            default:
                console.log("Unknow package type:" + pkg.type + "!");
        }
    };
    device.onCommand = function(str) {
        self.emit("command", str, device);
    };

    console.log("Client connect.");
}
// }}}

var WRITE_FORCE = true;

function SiriDevice() { // Device {{{

    Stream.call(this);
    this.writable = false;
    this.readable = true;

    this.serverResponse = [];
    this.proxied = true;
    this.completed = true;

    this.aceId = null;
    this.refId = null;
    this.version = null;
}

util.inherits(SiriDevice, Stream);

function getRecognizedText(obj) {
    var arr;
    if (obj["class"] != "SpeechRecognized") return null;
    arr = [];
    obj.properties.recognition.properties.phrases.forEach(function(item) {
        item.properties.interpretations[0].properties.tokens.forEach(function(item) {
            arr.push(item.properties.text);
        });
    });
    return arr.join("");
}

SiriDevice.prototype.onCommand = function() {
    //Do nothing
};

SiriDevice.prototype.getCompletedPackage = function() {
    return new parser.ACEBinaryPlist(bplist.fromPObject({
        "properties": {
            "callbacks": []
        },
        "refId": "string:" + this.refId,
        "v": "string:" + this.version,
        "class": "string:RequestCompleted",
        "aceId": "string:" + this.aceId,
        "group": "string:com.apple.ace.system"
    }));
};

SiriDevice.prototype.writePackage = function(pkg, check) {
    if (check !== WRITE_FORCE && this.completed) return;
    this.emit('data', pkg.getData());
};

SiriDevice.prototype.receivePackage = function(pkg) {
    var obj = pkg.rootNode().toObject();

    this.refId = obj.refId;
    this.aceId = obj.aceId;
    this.version = obj.v;

    switch (obj["class"]) {
        case "SpeechRecognized":
            this.serverResponse = [];
            this.proxied = false;
            this.completed = false;

            this.writePackage(pkg, WRITE_FORCE);
            this.onCommand(getRecognizedText(obj));
            break;
        default:
            if (this.proxied) {
                this.writePackage(pkg, WRITE_FORCE);
            } else {
                this.serverResponse.push(pkg);
            }
            break;
    }
};

SiriDevice.prototype.proxy = function() {
    var self = this;
    this.serverResponse.forEach(function(pkg, index) {
        self.writePackage(pkg);
    });
    this.proxied = true;
    this.completed = true;
};

SiriDevice.prototype.say = function(str, speakable) {
    this.writePackage(new parser.ACEBinaryPlist(bplist.fromPObject({
        "properties": {
            "temporary": "null:false",
            "dialogPhase": "string:Completion",
            "scrollToTop": "null:false",
            "views": [{
                "class": "string:AssistantUtteranceView",
                "properties": {
                    "dialogIdentifier": "string:Misc#answer",
                    "speakableText": "unicode:" + (speakable === undefined ? str : speakable),
                    "text": "unicode:" + str
                },
                "group": "string:com.apple.ace.assistant"
            }]
        },
        "refId": "string:" + this.refId,
        "v": "string:" + this.version,
        "class": "string:AddViews",
        "aceId": "string:" + this.aceId,
        "group": "string:com.apple.ace.assistant"
    })));
};

SiriDevice.prototype.end = function(str) {
    if (str !== undefined) this.say(str);
    this.writePackage(this.getCompletedPackage());
    this.completed = true;
};
// }}}

//* Test
var fs = require("fs"),
    siri = exports,
    tmp = 0;

function getId() {
    tmp++;
    return (tmp < 100 ? "0" : "") + (tmp < 10 ? "0" : "") + tmp;
}

siri.createServer({
    key: fs.readFileSync('./server.passless.key'),
    cert: fs.readFileSync('./server.passless.crt')
}, function(command, device) {
    console.log(command);
    if (command == "你好") {
        device.say("3");
        setTimeout(function() {
            device.say("2");
            setTimeout(function() {
                device.say("1");
                setTimeout(function() {
                    device.end("Siri代理向你问好,哈哈哈!");
                }, 1000);
            }, 1000);
        }, 1000);
    } else {
        device.proxy();
    }
}).listen(4433, function() {
    console.log("Proxy start.");
});
//*/
// vim600: sw=4 ts=4 fdm=marker syn=javascript
<|endoftext|>


<commit_before>/**
 * Created by Alexander Lex on 3/4/14.
 */

var SET_SIZE_GROUP_PREFIX = 'SetSizeG_';
var EMPTY_GROUP_ID = 'EmptyGroup';
var SET_BASED_GROUPING_PREFIX = "SetG_";

var handleLogicGroups = function (subsets, level, parentGroup) {
    filterGroups = [];
    UpSetState.logicGroups.forEach(function (d) {
        var group = new QueryGroup(d.id, d.groupName, d.orClauses);
        var maskList = d.getListOfValues();

        getSubsetsForMaskList(subsets, maskList, function (d) {
            group.addSubSet(d);
        });

        filterGroups.push(group)

    })
}

var groupByOverlapDegree = function (subSets, level, parentGroup) {
    var degree = 2;
    var newGroups = []

    var defaultMask;
    if (parentGroup) {
        defaultMask = parentGroup.combinedSets;
    }

    var combinations = Math.pow(2, usedSets.length) - 1;

    var queries = []
    for (var i = 0; i <= combinations; i++) {
        fillMasks(i, usedSets.length, 2, queries, defaultMask);
    }
    for (var i = 0; i < queries.length; i++) {
        var name = "";
        for (var j = 0; j < queries[i].length; j++) {
            if (queries[i][j] === 1) {
                if (parentGroup.elementName !== usedSets[j].elementName)
                    name += usedSets[j].elementName + " ";
            }
        }
        var group = new Group("Overlap_G_" + i + "_" + parentGroup.id, name);
        group.level = level;
        getSubsetsForMaskList(subSets, [queries[i]], function (d) {
            group.addSubSet(d);
        });
        if (group.subSets.length > 0) {
            newGroups.unshift(group);
        }
    }

    return newGroups;
//    console.log(queries);

//    for (var i = 0; i < subSets.length; i++) {
//        mask = Array.apply(null, new Array(subSets.length)).map(Number.prototype.valueOf, 0);
//        mask[i] = 1;
//    }

}

var fillMasks = function (setMask, length, minSets, queries, defaultMask) {

    var bitMask = 1;

    var query;
    if (defaultMask) {
        var query = defaultMask.slice(0);
    }
    else {
        query = Array.apply(null, new Array(length)).map(Number.prototype.valueOf, 0);
    }
    var memberCount = 0;

    for (var setIndex = length - 1; setIndex >= 0; setIndex--) {
        if (query[setIndex] === 1) {
            // true if this element is in the default mask
            memberCount++;
        }
        else if ((setMask & bitMask) === 1) {
            query[setIndex] = 1;
            memberCount++;
        }
        else {
            query[setIndex] = 2;
        }
        setMask = setMask >> 1;
    }
    if (memberCount == minSets) {
        // FIXME this is to remove duplicates. We shouldn't produce them in the first place
        var duplicate = false;
        for (var i = 0; i < queries.length; i++) {
            if (queries[i].compare(query)) {
                duplicate = true;
                break;
            }
        }
        if (!duplicate) {
            queries.push(query);
        }
    }

//    var resultMasks = [];
//    for (var maskCount = 0; maskCount < length; maskCount++) {
//        for (var i = 0; i < length; i++) {
//            var newMask = masks[maskCount].slice(0);
//
//
//        }
//    }
}

var groupByRelevanceMeasure = function (subSets, level, parentGroup) {
    var newGroups = [];
    newGroups.push(new Group('GROUP_POS_DEV' + parentGroup.id, 'Positive Expected Value', level));
    newGroups.push(new Group('GROUP_NEG_DEV' + parentGroup.id, 'Negative Expected Value', level));
    newGroups.push(new Group(EMPTY_GROUP_ID + parentGroup.id, 'Empty Subset', level));
    for (var i = 0; i < subSets.length; i++) {
        var index = 0
        if (subSets[i].disproportionality > 0) {
            index = 0;
        }
        else if (subSets[i].disproportionality < 0) {
            index = 1;
        }
        else {
            index = 2;
        }
        newGroups[index].addSubSet(subSets[i])
    }
    return newGroups;
}

var groupByIntersectionSize = function (subSets, level, parentGroup) {
    var newGroups = [];
    newGroups.push(new Group(EMPTY_GROUP_ID + parentGroup.id, 'Empty Subset', level));
    var maxSetSize = Math.min(usedSets.length, UpSetState.maxCardinality);
    for (var i = UpSetState.minCardinality; i < maxSetSize; i++) {
        newGroups.push(new Group(SET_SIZE_GROUP_PREFIX + (i + 1) + '_' + parentGroup.id, (i + 1) + '-Set Subsets', level));
    }
    subSets.forEach(function (subSet) {
        var group = newGroups[subSet.nrCombinedSets];
        if (group != null)
            group.addSubSet(subSet);
        else
            console.log('Fail ' + group + subSet.nrCombinedSets);
    })
    return newGroups;
}

/**
 * Creates groups for all sets containing all subsets of this set
 */
var groupBySet = function (subSets, level, parentGroup) {

    // TODO add empty subset

    var newGroups = [];
    newGroups.push(new Group(EMPTY_GROUP_ID, 'Empty Subset', level));

    for (var i = 0; i < usedSets.length; i++) {
        var group = new Group(SET_BASED_GROUPING_PREFIX + (i + 1) + parentGroup.id, usedSets[i].elementName, level);
        group.combinedSets = Array.apply(null, new Array(usedSets.length)).map(Number.prototype.valueOf, 2);
        group.combinedSets[i] = 1;
        newGroups.push(group);

        subSets.forEach(function (subSet) {
            if (subSet.combinedSets[i] !== 0) {
                group.addSubSet(subSet);
            }
        });
    }
    return newGroups;
};

/** Collapse or uncollapse group */
var collapseGroup = function (group) {
    group.isCollapsed = !group.isCollapsed;

    UpSetState.collapseChanged = true;
    updateState();
    return;

};

var collapseAggregate = function (aggregate) {
    aggregate.isCollapsed = !aggregate.isCollapsed;
    updateState();
};

// ----------------------- Sort Functions ----------------------------

/** Filters the provided list of subsets to include only those of length >0. If no list of subsets is provided the global list is used. */
function getFilteredSubSets(subSetsToFilter) {
    if (!subSetsToFilter) {
        subSetsToFilter = subSets;
    }
    if (!UpSetState.hideEmpties) {
        return subSetsToFilter.slice(0);
    }
    var filteredSubSets = []
    for (var i = 0; i < subSetsToFilter.length; i++) {
        if (subSetsToFilter[i].items.length > 0) {
            filteredSubSets.push(subSetsToFilter[i]);
        }
    }
    return filteredSubSets;
}

var sortBySetItem = function (subSets, set) {
    if (!set) {
        set = usedSets[0];
    }
    var dataRows = getFilteredSubSets(subSets);
    var setIndex = usedSets.indexOf(set);
    dataRows.sort(function (a, b) {
        // move all elements that contain the clicked set to the top
        if (b.combinedSets[setIndex] !== a.combinedSets[setIndex]) {
            return b.combinedSets[setIndex] - a.combinedSets[setIndex];
        }
        // move all elements with fewer intersections to the top
        if (a.nrCombinedSets !== b.nrCombinedSets) {
            return a.nrCombinedSets - b.nrCombinedSets;
        }
        // if the number of combined sets is identical, we can pick the largest one
        return b.id - a.id;
    });
    return dataRows;
}

var sortByCombinationSize = function (subSets) {
    var dataRows = getFilteredSubSets(subSets);

// sort by number of combinations
    dataRows.sort(function (a, b) {
        if (a.nrCombinedSets !== b.nrCombinedSets) {
            return a.nrCombinedSets - b.nrCombinedSets;
        }
        // if the number of combined sets is identical, we can pick the largest one
        return b.id - a.id;
    });
    return dataRows;
}

/** sort by size of set overlap */
var sortBySubSetSize = function (subSets) {
    var dataRows = getFilteredSubSets(subSets);
    dataRows.sort(function (a, b) {
        return b.setSize - a.setSize;
    });
    return dataRows;
}

/** sort by size of set overlap */
var sortByExpectedValue = function (subSets) {
    var dataRows = getFilteredSubSets(subSets);

    dataRows.sort(function (a, b) {
        return Math.abs(b.disproportionality) - Math.abs(a.disproportionality);
    });
    return dataRows;
}

/**
 * Takes a list of groups and writes them into an array, according to the nesting & collapse rules
 * @param groupList
 * @returns {*}
 */
var unwrapGroups = function (groupList) {
    var dataRows = []
    for (var i = 0; i < groupList.length; i++) {
        var group = groupList[i];
        // ignoring an empty empty group
        if (group.id === EMPTY_GROUP_ID && group.setSize === 0 || (group.visibleSets.length === 0 && UpSetState.hideEmpties)) {
            continue;
        }
        dataRows.push(group);
        if (UpSetState.collapseAll) {
            group.isCollapsed = true;
        }
        if (UpSetState.expandAll) {
            group.isCollapsed = false;
        }
        if (UpSetState.levelTwoGrouping && group.nestedGroups) {
            dataRows = dataRows.concat(unwrapGroups(group.nestedGroups, []));
            continue;
        }
        if (!group.isCollapsed) {
            dataRows = dataRows.concat(StateMap[UpSetState.sorting](group.visibleSets));

            if (group.aggregate.subSets.length > 0 && !UpSetState.hideEmpties) {
                dataRows.push(group.aggregate);
                if (!group.aggregate.isCollapsed) {
                    for (var k = 0; k < group.aggregate.subSets.length; k++) {
                        dataRows.push(group.aggregate.subSets[k]);
                    }
                }
            }
        }
    }

    return dataRows;
};

var StateMap = {
    groupByIntersectionSize: groupByIntersectionSize,
    groupBySet: groupBySet,
    groupByRelevanceMeasure: groupByRelevanceMeasure,
    groupByOverlapDegree: groupByOverlapDegree,

    sortByCombinationSize: sortByCombinationSize,
    sortBySubSetSize: sortBySubSetSize,
    sortByExpectedValue: sortByExpectedValue,
    sortBySubSetSize: sortBySubSetSize,
    sortBySetItem: sortBySetItem
};

var StateOpt = {
    groupByIntersectionSize: 'groupByIntersectionSize',
    groupBySet: 'groupBySet',
    groupByRelevanceMeasure: 'groupByRelevanceMeasure',
    groupByOverlapDegree: 'groupByOverlapDegree',

    sortByCombinationSize: 'sortByCombinationSize',
    sortBySubSetSize: 'sortBySubSetSize',
    sortByExpectedValue: 'sortByExpectedValue',
    sortBySetItem: 'sortBySetItem'
};

var UpSetState = {
    collapseAll: false,
    expandAll: false,
    // collapseChanged: false,

    grouping: queryParameters["grouping"] || StateOpt.groupByIntersectionSize,
    levelTwoGrouping: undefined,
    sorting: StateOpt.sortByCombinationSize,

    /** hide empty subsets, groups and aggregates */
    hideEmpties: true,

    /** Sets the upper threshold of cardinality of subsets */
    maxCardinality: undefined,
    /** Sets the lower threshold of cardinality of subsets */
    minCardinality: 0,

    forceUpdate: false,

    /** user defined logic groups **/
    logicGroups: [],
    logicGroupChanged: false

};

var previousState = false;

var updateState = function (parameter) {
    var forceUpdate = !previousState || UpSetState.forceUpdate || (UpSetState.hideEmpties != previousState.hideEmpties);

    // true if pure sorting - no grouping
    if ((UpSetState.sorting && !UpSetState.grouping) && (forceUpdate || (previousState && previousState.sorting !== UpSetState.sorting))) {
        dataRows = StateMap[StateOpt[UpSetState.sorting]](subSets, parameter);
    }
    else if (UpSetState.grouping && (forceUpdate || (previousState && previousState.grouping !== UpSetState.grouping || previousState.levelTwoGrouping !== UpSetState.levelTwoGrouping))) {
        levelOneGroups = StateMap[StateOpt[UpSetState.grouping]](subSets, 1, "");

        if (UpSetState.levelTwoGrouping) {
            levelOneGroups.forEach(function (group) {
                group.nestedGroups = StateMap[StateOpt[UpSetState.levelTwoGrouping]](group.subSets, 2, group);
            });
        }
        dataRows = unwrapGroups(levelOneGroups);

    }
    else if (UpSetState.collapseChanged && UpSetState.grouping) {
        dataRows = unwrapGroups(levelOneGroups);
    }

    if (UpSetState.logicGroupChanged) {
        handleLogicGroups(subSets, 1);
        UpSetState.logicGroupChanged = false;

    }

    if (filterGroups && filterGroups.length > 0) {
        var filteredRows = unwrapGroups(filterGroups);
        var separator = new Separator("FILTER_SEPARATOR", 'Natural Intersections');
        filteredRows.push(separator);
        dataRows = filteredRows.concat(dataRows);
    }

    UpSetState.forceUpdate = false;
    UpSetState.expandAll = false;
    UpSetState.collapseAll = false;
    UpSetState.collapseChanged = false;

    renderRows.length = 0;

    var registry = {};
    var prefix = "";

    var count = 1;
    dataRows.forEach(function (element) {
        var wrapper = {};

        if (UpSetState.grouping === StateOpt.groupBySet || UpSetState.levelTwoGrouping === StateOpt.groupBySet) {
            if (element.type === ROW_TYPE.SUBSET) {
                wrapper.id = prefix + element.id;
            }
            else {
                prefix = element.id + "_";
                wrapper.id = element.id;
            }
        }
        else {

            if (registry.hasOwnProperty(element.id)) {
                count = registry[element.id];
                count += 1;
                registry[element.id] = count;
            }
            else {
                registry[element.id] = 1;
            }

            wrapper.id = element.id + '_' + count;
        }
        wrapper.data = element;
        renderRows.push(wrapper);

    });
    previousState = JSON.parse(JSON.stringify(UpSetState));

    queryParameters["grouping"] = UpSetState.grouping;
    updateQueryParameters();

};
<commit_msg>Showing group 2 markers<commit_after>/**
 * Created by Alexander Lex on 3/4/14.
 */

var SET_SIZE_GROUP_PREFIX = 'SetSizeG_';
var EMPTY_GROUP_ID = 'EmptyGroup';
var SET_BASED_GROUPING_PREFIX = "SetG_";

var handleLogicGroups = function (subsets, level, parentGroup) {
    filterGroups = [];
    UpSetState.logicGroups.forEach(function (d) {
        var group = new QueryGroup(d.id, d.groupName, d.orClauses);
        var maskList = d.getListOfValues();

        getSubsetsForMaskList(subsets, maskList, function (d) {
            group.addSubSet(d);
        });

        filterGroups.push(group)

    })
}

var groupByOverlapDegree = function (subSets, level, parentGroup) {
    var degree = 2;
    var newGroups = []

    var defaultMask;
    if (parentGroup) {
        defaultMask = parentGroup.combinedSets;
    }

    var combinations = Math.pow(2, usedSets.length) - 1;

    var queries = []
    for (var i = 0; i <= combinations; i++) {
        fillMasks(i, usedSets.length, 2, queries, defaultMask);
    }
    for (var i = 0; i < queries.length; i++) {
        var name = "";
        for (var j = 0; j < queries[i].length; j++) {
            if (queries[i][j] === 1) {
                if (parentGroup.elementName !== usedSets[j].elementName)
                    name += usedSets[j].elementName + " ";
            }
        }
        var group = new Group("Overlap_G_" + i + "_" + parentGroup.id, name);
        group.level = level;
        group.combinedSets = queries[i];
        getSubsetsForMaskList(subSets, [queries[i]], function (d) {
            group.addSubSet(d);
        });
        if (group.subSets.length > 0) {
            newGroups.unshift(group);
        }
    }

    return newGroups;
//    console.log(queries);

//    for (var i = 0; i < subSets.length; i++) {
//        mask = Array.apply(null, new Array(subSets.length)).map(Number.prototype.valueOf, 0);
//        mask[i] = 1;
//    }

}

var fillMasks = function (setMask, length, minSets, queries, defaultMask) {

    var bitMask = 1;

    var query;
    if (defaultMask) {
        var query = defaultMask.slice(0);
    }
    else {
        query = Array.apply(null, new Array(length)).map(Number.prototype.valueOf, 0);
    }
    var memberCount = 0;

    for (var setIndex = length - 1; setIndex >= 0; setIndex--) {
        if (query[setIndex] === 1) {
            // true if this element is in the default mask
            memberCount++;
        }
        else if ((setMask & bitMask) === 1) {
            query[setIndex] = 1;
            memberCount++;
        }
        else {
            query[setIndex] = 2;
        }
        setMask = setMask >> 1;
    }
    if (memberCount == minSets) {
        // FIXME this is to remove duplicates. We shouldn't produce them in the first place
        var duplicate = false;
        for (var i = 0; i < queries.length; i++) {
            if (queries[i].compare(query)) {
                duplicate = true;
                break;
            }
        }
        if (!duplicate) {
            queries.push(query);
        }
    }

//    var resultMasks = [];
//    for (var maskCount = 0; maskCount < length; maskCount++) {
//        for (var i = 0; i < length; i++) {
//            var newMask = masks[maskCount].slice(0);
//
//
//        }
//    }
}

var groupByRelevanceMeasure = function (subSets, level, parentGroup) {
    var newGroups = [];
    newGroups.push(new Group('GROUP_POS_DEV' + parentGroup.id, 'Positive Expected Value', level));
    newGroups.push(new Group('GROUP_NEG_DEV' + parentGroup.id, 'Negative Expected Value', level));
    newGroups.push(new Group(EMPTY_GROUP_ID + parentGroup.id, 'Empty Subset', level));
    for (var i = 0; i < subSets.length; i++) {
        var index = 0
        if (subSets[i].disproportionality > 0) {
            index = 0;
        }
        else if (subSets[i].disproportionality < 0) {
            index = 1;
        }
        else {
            index = 2;
        }
        newGroups[index].addSubSet(subSets[i])
    }
    return newGroups;
}

var groupByIntersectionSize = function (subSets, level, parentGroup) {
    var newGroups = [];
    newGroups.push(new Group(EMPTY_GROUP_ID + parentGroup.id, 'Empty Subset', level));
    var maxSetSize = Math.min(usedSets.length, UpSetState.maxCardinality);
    for (var i = UpSetState.minCardinality; i < maxSetSize; i++) {
        newGroups.push(new Group(SET_SIZE_GROUP_PREFIX + (i + 1) + '_' + parentGroup.id, (i + 1) + '-Set Subsets', level));
    }
    subSets.forEach(function (subSet) {
        var group = newGroups[subSet.nrCombinedSets];
        if (group != null)
            group.addSubSet(subSet);
        else
            console.log('Fail ' + group + subSet.nrCombinedSets);
    })
    return newGroups;
}

/**
 * Creates groups for all sets containing all subsets of this set
 */
var groupBySet = function (subSets, level, parentGroup) {

    // TODO add empty subset

    var newGroups = [];
    newGroups.push(new Group(EMPTY_GROUP_ID, 'Empty Subset', level));

    for (var i = 0; i < usedSets.length; i++) {
        var group = new Group(SET_BASED_GROUPING_PREFIX + (i + 1) + parentGroup.id, usedSets[i].elementName, level);
        group.combinedSets = Array.apply(null, new Array(usedSets.length)).map(Number.prototype.valueOf, 2);
        group.combinedSets[i] = 1;
        newGroups.push(group);

        subSets.forEach(function (subSet) {
            if (subSet.combinedSets[i] !== 0) {
                group.addSubSet(subSet);
            }
        });
    }
    return newGroups;
};

/** Collapse or uncollapse group */
var collapseGroup = function (group) {
    group.isCollapsed = !group.isCollapsed;

    UpSetState.collapseChanged = true;
    updateState();
    return;

};

var collapseAggregate = function (aggregate) {
    aggregate.isCollapsed = !aggregate.isCollapsed;
    updateState();
};

// ----------------------- Sort Functions ----------------------------

/** Filters the provided list of subsets to include only those of length >0. If no list of subsets is provided the global list is used. */
function getFilteredSubSets(subSetsToFilter) {
    if (!subSetsToFilter) {
        subSetsToFilter = subSets;
    }
    if (!UpSetState.hideEmpties) {
        return subSetsToFilter.slice(0);
    }
    var filteredSubSets = []
    for (var i = 0; i < subSetsToFilter.length; i++) {
        if (subSetsToFilter[i].items.length > 0) {
            filteredSubSets.push(subSetsToFilter[i]);
        }
    }
    return filteredSubSets;
}

var sortBySetItem = function (subSets, set) {
    if (!set) {
        set = usedSets[0];
    }
    var dataRows = getFilteredSubSets(subSets);
    var setIndex = usedSets.indexOf(set);
    dataRows.sort(function (a, b) {
        // move all elements that contain the clicked set to the top
        if (b.combinedSets[setIndex] !== a.combinedSets[setIndex]) {
            return b.combinedSets[setIndex] - a.combinedSets[setIndex];
        }
        // move all elements with fewer intersections to the top
        if (a.nrCombinedSets !== b.nrCombinedSets) {
            return a.nrCombinedSets - b.nrCombinedSets;
        }
        // if the number of combined sets is identical, we can pick the largest one
        return b.id - a.id;
    });
    return dataRows;
}

var sortByCombinationSize = function (subSets) {
    var dataRows = getFilteredSubSets(subSets);

// sort by number of combinations
    dataRows.sort(function (a, b) {
        if (a.nrCombinedSets !== b.nrCombinedSets) {
            return a.nrCombinedSets - b.nrCombinedSets;
        }
        // if the number of combined sets is identical, we can pick the largest one
        return b.id - a.id;
    });
    return dataRows;
}

/** sort by size of set overlap */
var sortBySubSetSize = function (subSets) {
    var dataRows = getFilteredSubSets(subSets);
    dataRows.sort(function (a, b) {
        return b.setSize - a.setSize;
    });
    return dataRows;
}

/** sort by size of set overlap */
var sortByExpectedValue = function (subSets) {
    var dataRows = getFilteredSubSets(subSets);

    dataRows.sort(function (a, b) {
        return Math.abs(b.disproportionality) - Math.abs(a.disproportionality);
    });
    return dataRows;
}

/**
 * Takes a list of groups and writes them into an array, according to the nesting & collapse rules
 * @param groupList
 * @returns {*}
 */
var unwrapGroups = function (groupList) {
    var dataRows = []
    for (var i = 0; i < groupList.length; i++) {
        var group = groupList[i];
        // ignoring an empty empty group
        if (group.id === EMPTY_GROUP_ID && group.setSize === 0 || (group.visibleSets.length === 0 && UpSetState.hideEmpties)) {
            continue;
        }
        dataRows.push(group);
        if (UpSetState.collapseAll) {
            group.isCollapsed = true;
        }
        if (UpSetState.expandAll) {
            group.isCollapsed = false;
        }
        if (UpSetState.levelTwoGrouping && group.nestedGroups) {
            dataRows = dataRows.concat(unwrapGroups(group.nestedGroups, []));
            continue;
        }
        if (!group.isCollapsed) {
            dataRows = dataRows.concat(StateMap[UpSetState.sorting](group.visibleSets));

            if (group.aggregate.subSets.length > 0 && !UpSetState.hideEmpties) {
                dataRows.push(group.aggregate);
                if (!group.aggregate.isCollapsed) {
                    for (var k = 0; k < group.aggregate.subSets.length; k++) {
                        dataRows.push(group.aggregate.subSets[k]);
                    }
                }
            }
        }
    }

    return dataRows;
};

var StateMap = {
    groupByIntersectionSize: groupByIntersectionSize,
    groupBySet: groupBySet,
    groupByRelevanceMeasure: groupByRelevanceMeasure,
    groupByOverlapDegree: groupByOverlapDegree,

    sortByCombinationSize: sortByCombinationSize,
    sortBySubSetSize: sortBySubSetSize,
    sortByExpectedValue: sortByExpectedValue,
    sortBySubSetSize: sortBySubSetSize,
    sortBySetItem: sortBySetItem
};

var StateOpt = {
    groupByIntersectionSize: 'groupByIntersectionSize',
    groupBySet: 'groupBySet',
    groupByRelevanceMeasure: 'groupByRelevanceMeasure',
    groupByOverlapDegree: 'groupByOverlapDegree',

    sortByCombinationSize: 'sortByCombinationSize',
    sortBySubSetSize: 'sortBySubSetSize',
    sortByExpectedValue: 'sortByExpectedValue',
    sortBySetItem: 'sortBySetItem'
};

var UpSetState = {
    collapseAll: false,
    expandAll: false,
    // collapseChanged: false,

    grouping: queryParameters["grouping"] || StateOpt.groupByIntersectionSize,
    levelTwoGrouping: undefined,
    sorting: StateOpt.sortByCombinationSize,

    /** hide empty subsets, groups and aggregates */
    hideEmpties: true,

    /** Sets the upper threshold of cardinality of subsets */
    maxCardinality: undefined,
    /** Sets the lower threshold of cardinality of subsets */
    minCardinality: 0,

    forceUpdate: false,

    /** user defined logic groups **/
    logicGroups: [],
    logicGroupChanged: false

};

var previousState = false;

var updateState = function (parameter) {
    var forceUpdate = !previousState || UpSetState.forceUpdate || (UpSetState.hideEmpties != previousState.hideEmpties);

    // true if pure sorting - no grouping
    if ((UpSetState.sorting && !UpSetState.grouping) && (forceUpdate || (previousState && previousState.sorting !== UpSetState.sorting))) {
        dataRows = StateMap[StateOpt[UpSetState.sorting]](subSets, parameter);
    }
    else if (UpSetState.grouping && (forceUpdate || (previousState && previousState.grouping !== UpSetState.grouping || previousState.levelTwoGrouping !== UpSetState.levelTwoGrouping))) {
        levelOneGroups = StateMap[StateOpt[UpSetState.grouping]](subSets, 1, "");

        if (UpSetState.levelTwoGrouping) {
            levelOneGroups.forEach(function (group) {
                group.nestedGroups = StateMap[StateOpt[UpSetState.levelTwoGrouping]](group.subSets, 2, group);
            });
        }
        dataRows = unwrapGroups(levelOneGroups);

    }
    else if (UpSetState.collapseChanged && UpSetState.grouping) {
        dataRows = unwrapGroups(levelOneGroups);
    }

    if (UpSetState.logicGroupChanged) {
        handleLogicGroups(subSets, 1);
        UpSetState.logicGroupChanged = false;

    }

    if (filterGroups && filterGroups.length > 0) {
        var filteredRows = unwrapGroups(filterGroups);
        var separator = new Separator("FILTER_SEPARATOR", 'Natural Intersections');
        filteredRows.push(separator);
        dataRows = filteredRows.concat(dataRows);
    }

    UpSetState.forceUpdate = false;
    UpSetState.expandAll = false;
    UpSetState.collapseAll = false;
    UpSetState.collapseChanged = false;

    renderRows.length = 0;

    var registry = {};
    var prefix = "";

    var count = 1;
    dataRows.forEach(function (element) {
        var wrapper = {};

        if (UpSetState.grouping === StateOpt.groupBySet || UpSetState.levelTwoGrouping === StateOpt.groupBySet) {
            if (element.type === ROW_TYPE.SUBSET) {
                wrapper.id = prefix + element.id;
            }
            else {
                prefix = element.id + "_";
                wrapper.id = element.id;
            }
        }
        else {

            if (registry.hasOwnProperty(element.id)) {
                count = registry[element.id];
                count += 1;
                registry[element.id] = count;
            }
            else {
                registry[element.id] = 1;
            }

            wrapper.id = element.id + '_' + count;
        }
        wrapper.data = element;
        renderRows.push(wrapper);

    });
    previousState = JSON.parse(JSON.stringify(UpSetState));

    queryParameters["grouping"] = UpSetState.grouping;
    updateQueryParameters();

};
<|endoftext|>