<commit_before>/*
 *  Proxy (ES6 draft) 'enumerate' and 'ownKeys'.
 */

function objDump(obj) {
    var k;
    var keys = [];
    try {
        for (k in obj) {
            keys.push((k === null ? 'null' : typeof k) + ':' + String(k));
        }
    } catch (e) {
        keys = [ e.name ];
    }

    // Enumerate on proxy object triggers 'enumerate' trap.
    print('enum keys:', keys.join(' '));

    // Object.keys() on proxy object triggers 'ownKeys' trap.
    // If no such trap exists, enumerable property names of the *proxy*
    // object are listed (not the proxy target).
    try {
        print('Object.keys:', Duktape.enc('jx', Object.keys(obj)));
    } catch (e) {
        print('Object.keys:', e.name);
    }

    // Object.getOwnPropertyNames() on prxy object also triggers 'ownKeys'
    // trap.  If no such trap exists, property names (enumerable or not)
    // of the *proxy* object are listed (not the proxy target).
    try {
        print('Object.getOwnPropertyNames:', Duktape.enc('jx', Object.getOwnPropertyNames(obj)));
    } catch (e) {
        print('Object.getOwnPropertyNames:', e.name);
    }
}

/*===
basic test
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
enum keys: string:0 string:1 string:2 string:prop
Object.keys: ["0","1","2","prop"]
Object.getOwnPropertyNames: ["0","1","2","length","prop"]
proxy.foo: 1
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
enumerate: true true
enum keys: string:foo string:bar string:quux string:nonEnum
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux","nonEnum"]
enumerate: true true
enum keys: string:nosuch1 string:nosuch2
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
enum keys: string:foo string:bar string:quux string:enumProp
ownKeys: true true
Object.keys: ["foo","enumProp","nonEnumProp"]
ownKeys: true true
Object.getOwnPropertyNames: ["foo","enumProp","nonEnumProp"]
===*/

function basicEnumerationTest() {
    var target;
    var proxy;
    var handler;

    // Simple target object, no proxies.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    objDump(target);
    target = [ 'foo', 'bar', 'quux' ];
    target.prop = 'propval';
    objDump(target);

    // Simple target object, proxy without 'enumerate' or 'ownKeys'.
    // Enumeration goes through to the proxy target, same applies to
    // Object.keys() and Object.getOwnPropertyNames().

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    proxy = new Proxy(target, {
    });
    print('proxy.foo:', proxy.foo);
    objDump(proxy);

    // Proxy which returns Object.getOwnPropertyNames() from 'enumerate' trap.
    // This causes enumeration to enumerate 'through' to the target object,
    // except that also non-enumerable properties get enumerated.
    // Object.keys() and Object.getOwnPropertyNames() operate directly on
    // the proxy target.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    Object.defineProperty(target, 'nonEnum', {
        value: 'nonenumerable', writable: true, enumerable: false, configurable: true
    });
    handler = {
        enumerate: function (targ) {
            print('enumerate:', this === handler, targ === target);
            return Object.getOwnPropertyNames(targ);
        }
    };
    proxy = new Proxy(target, handler);
    objDump(proxy);

    // Proxy which fabricates non-existent keys in 'enumerate'.
    // Object.keys() and Object.getOwnPropertyNames()
    // operate on the proxy target and see the actual keys.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    handler = {
        enumerate: function (targ) {
            print('enumerate:', this === handler, targ === target);
            return [ 'nosuch1', 'nosuch2' ];
        }
    };
    proxy = new Proxy(target, handler);
    objDump(proxy);

    // Proxy which provides a subset of keys in 'ownKeys'.
    // Enumeration has no trap so it operates on the target directly
    // (and only sees enumerable properties).  Object.keys() and
    // Object.getOwnPropertyNames() use the 'ownKeys' trap.
    //
    // NOTE: ES6 draft algorithm for Object.keys() is that the trap
    // result list is processed to check whether or not each key is
    // enumerable (the check uses [[GetOwnProperty]]).  Duktape omits
    // this step now, so Object.keys() and Object.getOwnPropertyNames()
    // returns the same result for now.  However, the trap result will
    // still be cleaned up so that non-string keys, gaps, etc will be
    // eliminated.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    Object.defineProperties(target, {
        enumProp: {
            value: 'enumerable', writable: true, enumerable: true, configurable: true,
        },
        nonEnumProp: {
            value: 'non-enumerable', writable: true, enumerable: false, configurable: true,
        }
    });
    handler = {
        ownKeys: function (targ) {
            print('ownKeys:', this === handler, targ === target);
            return [ 'foo', 'enumProp', 'nonEnumProp' ];
        }
    };
    proxy = new Proxy(target, handler);
    objDump(proxy);
}

print('basic test');

try {
    basicEnumerationTest();
} catch (e) {
    print(e);
}

/*===
trap result test
fake trap result: undefined
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: null
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: true
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: false
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: 123
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: "foo"
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: ["foo","bar","quux"]
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
fake trap result: {"0":"foo","1":"bar","2":"quux","3":"baz",length:3}
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
fake trap result: ["foo",undefined,null,true,false,123,"quux"]
enum keys: string:foo string:quux
Object.keys: ["foo","quux"]
Object.getOwnPropertyNames: ["foo","quux"]
fake trap result: {"0":"foo","1":123,"3":"quux",length:5}
enum keys: string:foo string:quux
Object.keys: ["foo","quux"]
Object.getOwnPropertyNames: ["foo","quux"]
fake trap result: ["foo-gappy",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,"bar-gappy",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,"quux-gappy",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]
enum keys: string:foo-gappy string:bar-gappy string:quux-gappy
Object.keys: ["foo-gappy","bar-gappy","quux-gappy"]
Object.getOwnPropertyNames: ["foo-gappy","bar-gappy","quux-gappy"]
fake trap result: {"0":"foo","1":"bar","2":"quux"}
enum keys:
Object.keys: []
Object.getOwnPropertyNames: []
===*/

/* Check handling of various trap result checks: return value must be an object
 * but not necessarily an array, handling of gaps, handling of non-string values,
 * handling of missing 'length', etc.
 */

function trapResultTest() {
    var gappyArray = [];
    gappyArray[0] = 'foo-gappy';
    gappyArray[10] = 'bar-gappy';
    gappyArray[20] = 'quux-gappy';
    gappyArray.length = 30;
    var results = [
        undefined, null, true, false, 123, 'foo',                            // non-object -> TypeError
        [ 'foo', 'bar', 'quux' ],                                            // array
        { '0': 'foo', '1': 'bar', '2': 'quux', '3': 'baz', 'length': 3 },    // array-like object, 'baz' is skipped (over 'length')
        [ 'foo', undefined, null, true, false, 123, 'quux' ],                // non-string values
        { '0': 'foo', '1': 123, '3': 'quux', 'length': 5 },                  // non-string values and gaps, array-like object
        gappyArray,                                                          // array with gaps
        { '0': 'foo', '1': 'bar', '2': 'quux' },                             // object without 'length'
    ];

    results.forEach(function (trapResult) {
        var target = {
        };
        var proxy;

        print('fake trap result:', Duktape.enc('jx', trapResult))

        proxy = new Proxy(target, {
            enumerate: function (targ) { return trapResult; },
            ownKeys: function (targ) { return trapResult; }
        });

        objDump(proxy);
    });
}

print('trap result test');

try {
    trapResultTest();
} catch (e) {
    print(e);
}
<commit_msg>Typo fix<commit_after>/*
 *  Proxy (ES6 draft) 'enumerate' and 'ownKeys'.
 */

function objDump(obj) {
    var k;
    var keys = [];
    try {
        for (k in obj) {
            keys.push((k === null ? 'null' : typeof k) + ':' + String(k));
        }
    } catch (e) {
        keys = [ e.name ];
    }

    // Enumerate on proxy object triggers 'enumerate' trap.
    print('enum keys:', keys.join(' '));

    // Object.keys() on proxy object triggers 'ownKeys' trap.
    // If no such trap exists, enumerable property names of the *proxy*
    // object are listed (not the proxy target).
    try {
        print('Object.keys:', Duktape.enc('jx', Object.keys(obj)));
    } catch (e) {
        print('Object.keys:', e.name);
    }

    // Object.getOwnPropertyNames() on proxy object also triggers 'ownKeys'
    // trap.  If no such trap exists, property names (enumerable or not)
    // of the *proxy* object are listed (not the proxy target).
    try {
        print('Object.getOwnPropertyNames:', Duktape.enc('jx', Object.getOwnPropertyNames(obj)));
    } catch (e) {
        print('Object.getOwnPropertyNames:', e.name);
    }
}

/*===
basic test
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
enum keys: string:0 string:1 string:2 string:prop
Object.keys: ["0","1","2","prop"]
Object.getOwnPropertyNames: ["0","1","2","length","prop"]
proxy.foo: 1
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
enumerate: true true
enum keys: string:foo string:bar string:quux string:nonEnum
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux","nonEnum"]
enumerate: true true
enum keys: string:nosuch1 string:nosuch2
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
enum keys: string:foo string:bar string:quux string:enumProp
ownKeys: true true
Object.keys: ["foo","enumProp","nonEnumProp"]
ownKeys: true true
Object.getOwnPropertyNames: ["foo","enumProp","nonEnumProp"]
===*/

function basicEnumerationTest() {
    var target;
    var proxy;
    var handler;

    // Simple target object, no proxies.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    objDump(target);
    target = [ 'foo', 'bar', 'quux' ];
    target.prop = 'propval';
    objDump(target);

    // Simple target object, proxy without 'enumerate' or 'ownKeys'.
    // Enumeration goes through to the proxy target, same applies to
    // Object.keys() and Object.getOwnPropertyNames().

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    proxy = new Proxy(target, {
    });
    print('proxy.foo:', proxy.foo);
    objDump(proxy);

    // Proxy which returns Object.getOwnPropertyNames() from 'enumerate' trap.
    // This causes enumeration to enumerate 'through' to the target object,
    // except that also non-enumerable properties get enumerated.
    // Object.keys() and Object.getOwnPropertyNames() operate directly on
    // the proxy target.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    Object.defineProperty(target, 'nonEnum', {
        value: 'nonenumerable', writable: true, enumerable: false, configurable: true
    });
    handler = {
        enumerate: function (targ) {
            print('enumerate:', this === handler, targ === target);
            return Object.getOwnPropertyNames(targ);
        }
    };
    proxy = new Proxy(target, handler);
    objDump(proxy);

    // Proxy which fabricates non-existent keys in 'enumerate'.
    // Object.keys() and Object.getOwnPropertyNames()
    // operate on the proxy target and see the actual keys.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    handler = {
        enumerate: function (targ) {
            print('enumerate:', this === handler, targ === target);
            return [ 'nosuch1', 'nosuch2' ];
        }
    };
    proxy = new Proxy(target, handler);
    objDump(proxy);

    // Proxy which provides a subset of keys in 'ownKeys'.
    // Enumeration has no trap so it operates on the target directly
    // (and only sees enumerable properties).  Object.keys() and
    // Object.getOwnPropertyNames() use the 'ownKeys' trap.
    //
    // NOTE: ES6 draft algorithm for Object.keys() is that the trap
    // result list is processed to check whether or not each key is
    // enumerable (the check uses [[GetOwnProperty]]).  Duktape omits
    // this step now, so Object.keys() and Object.getOwnPropertyNames()
    // returns the same result for now.  However, the trap result will
    // still be cleaned up so that non-string keys, gaps, etc will be
    // eliminated.

    target = { foo: 1, bar: 2, quux: [ 1, 2, 3 ] };
    Object.defineProperties(target, {
        enumProp: {
            value: 'enumerable', writable: true, enumerable: true, configurable: true,
        },
        nonEnumProp: {
            value: 'non-enumerable', writable: true, enumerable: false, configurable: true,
        }
    });
    handler = {
        ownKeys: function (targ) {
            print('ownKeys:', this === handler, targ === target);
            return [ 'foo', 'enumProp', 'nonEnumProp' ];
        }
    };
    proxy = new Proxy(target, handler);
    objDump(proxy);
}

print('basic test');

try {
    basicEnumerationTest();
} catch (e) {
    print(e);
}

/*===
trap result test
fake trap result: undefined
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: null
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: true
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: false
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: 123
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: "foo"
enum keys: TypeError
Object.keys: TypeError
Object.getOwnPropertyNames: TypeError
fake trap result: ["foo","bar","quux"]
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
fake trap result: {"0":"foo","1":"bar","2":"quux","3":"baz",length:3}
enum keys: string:foo string:bar string:quux
Object.keys: ["foo","bar","quux"]
Object.getOwnPropertyNames: ["foo","bar","quux"]
fake trap result: ["foo",undefined,null,true,false,123,"quux"]
enum keys: string:foo string:quux
Object.keys: ["foo","quux"]
Object.getOwnPropertyNames: ["foo","quux"]
fake trap result: {"0":"foo","1":123,"3":"quux",length:5}
enum keys: string:foo string:quux
Object.keys: ["foo","quux"]
Object.getOwnPropertyNames: ["foo","quux"]
fake trap result: ["foo-gappy",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,"bar-gappy",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,"quux-gappy",undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined,undefined]
enum keys: string:foo-gappy string:bar-gappy string:quux-gappy
Object.keys: ["foo-gappy","bar-gappy","quux-gappy"]
Object.getOwnPropertyNames: ["foo-gappy","bar-gappy","quux-gappy"]
fake trap result: {"0":"foo","1":"bar","2":"quux"}
enum keys:
Object.keys: []
Object.getOwnPropertyNames: []
===*/

/* Check handling of various trap result checks: return value must be an object
 * but not necessarily an array, handling of gaps, handling of non-string values,
 * handling of missing 'length', etc.
 */

function trapResultTest() {
    var gappyArray = [];
    gappyArray[0] = 'foo-gappy';
    gappyArray[10] = 'bar-gappy';
    gappyArray[20] = 'quux-gappy';
    gappyArray.length = 30;
    var results = [
        undefined, null, true, false, 123, 'foo',                            // non-object -> TypeError
        [ 'foo', 'bar', 'quux' ],                                            // array
        { '0': 'foo', '1': 'bar', '2': 'quux', '3': 'baz', 'length': 3 },    // array-like object, 'baz' is skipped (over 'length')
        [ 'foo', undefined, null, true, false, 123, 'quux' ],                // non-string values
        { '0': 'foo', '1': 123, '3': 'quux', 'length': 5 },                  // non-string values and gaps, array-like object
        gappyArray,                                                          // array with gaps
        { '0': 'foo', '1': 'bar', '2': 'quux' },                             // object without 'length'
    ];

    results.forEach(function (trapResult) {
        var target = {
        };
        var proxy;

        print('fake trap result:', Duktape.enc('jx', trapResult))

        proxy = new Proxy(target, {
            enumerate: function (targ) { return trapResult; },
            ownKeys: function (targ) { return trapResult; }
        });

        objDump(proxy);
    });
}

print('trap result test');

try {
    trapResultTest();
} catch (e) {
    print(e);
}
<|endoftext|>


<commit_before>var crm_field_masks = new CRMFieldMasks();
var operators = {
	'093': 'LifeCell',
    '063': 'LifeCell',
    '073': 'LifeCell',

    '050': 'Vodafone',
    '066': 'Vodafone',
    '095': 'Vodafone',
    '099': 'Vodafone',

    '039': 'Kyivstar',
    '067': 'Kyivstar',
    '096': 'Kyivstar',
    '097': 'Kyivstar',
    '098': 'Kyivstar',

    '091': '3Mob(Utel)',

    '092': 'PeopleNet',

    '094': 'Intertelecom',
	'unknown': 'Неизвестный оператор'

};
function check (num) {
    for(var key in operators){
        if(key == num){

            $('#operator').attr('value', operators[key]);
            $('#operator').attr('readonly','readonly');

            return true;
        }

    }
}

$(document).ready(function(){

    loadPhone();
	//	alert('here');

   // a way to check to make sure selector is working
	crm_field_masks.selector_check();
	crm_field_masks.run();

    $('#phone_contact').keyup(function () {
        $('#operator').attr('value', operators['unknown']);
        var a = $('input[name*="phone"]').val();
        a = a[4] + a[5] + a[6];
        console.log(a);
        check(a);
    });

	//	alert('there');
    // View relationships in leads
    if($("#LBL_CONTACT_INFORMATION").length && $("#list_subpanel_leads_bh_autotransport_1".length) && $('.machines').length == 0) {

        $('#list_subpanel_leads_bh_autotransport_1 > .table-responsive').clone()
			.removeClass()
			.addClass('machines detail view')
            .prepend('
Автомобили
')
            .insertBefore($("#detailpanel_2"));
        $('.machines').css('width', '100%');
        $('.machines').css('margin-top', '15px');
        $('.machines a.listViewThLinkS1').css('font-size', '10px');
        $('.machines a.listViewThLinkS1').removeAttr('href');
        $('.machines td').css('text-align', 'center');
        $('.machines .clickMenu').remove();
        $('.machines img').remove();

        $('#list_subpanel_activities > .table-responsive').clone()
            .removeClass()
            .addClass('activities detail view')
			.prepend('
Последнее событие
')
            .insertBefore($("#detailpanel_1"));

        $('.activities tbody tr:not(:last)').remove();
        $('.activities').css('width', '100%');
        $('.activities').css('margin-top', '15px');
        $('.activities a.listViewThLinkS1').css('font-size', '10px');
        $('.activities a.listViewThLinkS1').removeAttr('href');
        $('.activities .clickMenu').remove();
        $('.activities img').remove();
        $('.activities td').css('text-align', 'center');

        $('#tabcontent0 caption').css('color', 'red');
        $('#tabcontent0 caption').css('font-weight', 'bolder');
    }
    // View relationships in Marketing Company
    if($("#bh_marketing_company_detailview_tabs").length && $("#detailpanel_1").length) {
      if($('.product').length > 0){
          $('.product').remove();
      }
       var cust_panels = {
           'list_subpanel_bh_marketing_company_bh_campaine_products_1': 'Продукты компании',
           'list_subpanel_bh_marketing_company_bh_channels_impact_1': 'Каналы воздействия',
           'list_subpanel_bh_marketing_company_bh_marketing_directorate_1': 'Ректорат маркетингового воздейтвия',
           'list_subpanel_bh_marketing_company_bh_marketing_response_1': 'Отклик на маркетинговую компанию',
       };

        for(var key in cust_panels) {
            $('#'+ key +' > .table-responsive').clone()
                .removeClass()
                .addClass('product detail view')
                .prepend('
'+cust_panels[key]+'
')
                .insertAfter($("#detailpanel_1"));

        }
        $('.product').css('width', '100%');
        $('.product').css('margin-top', '15px');
        $('.product a.listViewThLinkS1').css('font-size', '10px');
        $('.product a.listViewThLinkS1').removeAttr('href');
        $('.product td').css('text-align', 'center');
        $('.product .clickMenu').remove();
        $('.product img').remove();
        $('#content caption').css('color', 'red');
        $('#content caption').css('font-weight', 'bolder');
    }
});

function loadPhone() {
    if($('#mdlDemo').length == 0) {
        $('body').append('

');
        $("#mdlDemo").append('<button type="button" class="btn btn-primary" id="btnConfig">Открыть телефон</button>');
    }

    // Save form to localStorage and validate
    $('#btnConfig').click(function(event) {

        event.preventDefault();

        // launch the phone window.

            var url      = '/custom/extension/application/crm_field_masks/phone/',
                features = 'menubar=no,location=no,resizable=no,scrollbars=no,status=no,addressbar=no,width=320,height=480';

            if (!localStorage.getItem('ctxPhone')) {
                window.open(url, 'CRM Phone', features);
                $('#mdlDemo').modal('hide');
                return false;
            } else {
                window.alert('Phone already open.');
            }

    });

   // $('#popup').position({ my: 'left top', at: 'left bottom', of: $('a').first() });

}

function CRMFieldMasks()
{
	that        = this;
	this.debug  = false;
	this.cache  = [];

	this.dependency = 'custom/Extension/application/crm_field_masks/jquery.inputmask.bundle.min.js';

	this.cache_and_log = function(name, value)
	{
		if(this.debug)
		{	this.cache[name] = value;
			console.log('CRMMASKS - ' + name + ' = ' + value );
		}
	}

	this.selector_check = function()
	{
		if(this.debug)
		{	this.cache_and_log('selector_check - begin', true );
			$('input[name*="phone"]').css('color','#00f !important');
			this.cache_and_log('selector_check - end', true );
		}
	}

	this.run = function()
	{
		this.cache_and_log('run - begin', true );
		dependency = this.dependency;

		// load dependencies
		$.getScript(dependency)
			.done(function( script, textStatus )
			{
				that.apply_masks();
				that.cache_and_log( 'dependency loaded', dependency );
			})
			.fail(function( jqxhr, settings, exception )
			{
				that.cache_and_log( 'dependency failed to load', dependency );
			});

		this.cache_and_log('run - end', true );
	}

	this.apply_masks = function()
	{
		this.cache_and_log('apply_masks - begin', true );

		$('input[name^="phone"]').inputmask({"mask": "[+38]([0]99) 999-99-99"}); //specifying options

		$('input[name*="fax"]').inputmask({"mask": "[+38]([0]99) 999-99-99"}); //specifying options
                $('input[name*="card_num"]').inputmask({"mask": "9999 9999 9999 9999",clearMaskOnLostFocus: true,
                        onincomplete: function(){
                             //alert("Пожалуйста, укажите 16 цифр в формате XXXX XXXX XXXX XXXX");
                             //$(this).css({'border' : '1px solid #ff0000'});
                             //$(':input[type="submit"]').prop('disabled', true);
                        }}
                    );
                $('input[name*="ukrpasport_nom"]').inputmask({"mask": "[AA]999999"});
                $('input[name*="date"]').inputmask({"mask": "99/99/9999"});
                $('input[name*="mfo"]').inputmask({"mask": "999999",clearMaskOnLostFocus: true});
                $('input[name*="inn"]').inputmask({"mask": "9999999999",clearMaskOnLostFocus: true,
                   onincomplete: function(){

                            // $(this).css({'border' : '1px solid #ff0000'});
                             //$(':input[type="submit"]').prop('disabled', true);
                        },
                    complete: function(){

                            // $(this).css({'border' : '1px solid #569b44'});
                             //$(':input[type="submit"]').prop('disabled', true);
                    }

                });

		this.cache_and_log('apply_masks - end', true );
	}

};
<commit_msg>загрузка окна телефона только после логина<commit_after>var crm_field_masks = new CRMFieldMasks();
var operators = {
	'093': 'LifeCell',
    '063': 'LifeCell',
    '073': 'LifeCell',

    '050': 'Vodafone',
    '066': 'Vodafone',
    '095': 'Vodafone',
    '099': 'Vodafone',

    '039': 'Kyivstar',
    '067': 'Kyivstar',
    '096': 'Kyivstar',
    '097': 'Kyivstar',
    '098': 'Kyivstar',

    '091': '3Mob(Utel)',

    '092': 'PeopleNet',

    '094': 'Intertelecom',
	'unknown': 'Неизвестный оператор'

};
function check (num) {
    for(var key in operators){
        if(key == num){

            $('#operator').attr('value', operators[key]);
            $('#operator').attr('readonly','readonly');

            return true;
        }

    }
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

$(document).ready(function(){

var module = getUrlVars()["module"];
var action = getUrlVars()["action"];

if ((action!='Login') && (module!='Users')){
    loadPhone();
}
	//	alert('here');

   // a way to check to make sure selector is working
	crm_field_masks.selector_check();
	crm_field_masks.run();

    $('#phone_contact').keyup(function () {
        $('#operator').attr('value', operators['unknown']);
        var a = $('input[name*="phone"]').val();
        a = a[4] + a[5] + a[6];
        console.log(a);
        check(a);
    });

	//	alert('there');
    // View relationships in leads
    if($("#LBL_CONTACT_INFORMATION").length && $("#list_subpanel_leads_bh_autotransport_1".length) && $('.machines').length == 0) {

        $('#list_subpanel_leads_bh_autotransport_1 > .table-responsive').clone()
			.removeClass()
			.addClass('machines detail view')
            .prepend('
Автомобили
')
            .insertBefore($("#detailpanel_2"));
        $('.machines').css('width', '100%');
        $('.machines').css('margin-top', '15px');
        $('.machines a.listViewThLinkS1').css('font-size', '10px');
        $('.machines a.listViewThLinkS1').removeAttr('href');
        $('.machines td').css('text-align', 'center');
        $('.machines .clickMenu').remove();
        $('.machines img').remove();

        $('#list_subpanel_activities > .table-responsive').clone()
            .removeClass()
            .addClass('activities detail view')
			.prepend('
Последнее событие
')
            .insertBefore($("#detailpanel_1"));

        $('.activities tbody tr:not(:last)').remove();
        $('.activities').css('width', '100%');
        $('.activities').css('margin-top', '15px');
        $('.activities a.listViewThLinkS1').css('font-size', '10px');
        $('.activities a.listViewThLinkS1').removeAttr('href');
        $('.activities .clickMenu').remove();
        $('.activities img').remove();
        $('.activities td').css('text-align', 'center');

        $('#tabcontent0 caption').css('color', 'red');
        $('#tabcontent0 caption').css('font-weight', 'bolder');
    }
    // View relationships in Marketing Company
    if($("#bh_marketing_company_detailview_tabs").length && $("#detailpanel_1").length) {
      if($('.product').length > 0){
          $('.product').remove();
      }
       var cust_panels = {
           'list_subpanel_bh_marketing_company_bh_campaine_products_1': 'Продукты компании',
           'list_subpanel_bh_marketing_company_bh_channels_impact_1': 'Каналы воздействия',
           'list_subpanel_bh_marketing_company_bh_marketing_directorate_1': 'Ректорат маркетингового воздейтвия',
           'list_subpanel_bh_marketing_company_bh_marketing_response_1': 'Отклик на маркетинговую компанию',
       };

        for(var key in cust_panels) {
            $('#'+ key +' > .table-responsive').clone()
                .removeClass()
                .addClass('product detail view')
                .prepend('
'+cust_panels[key]+'
')
                .insertAfter($("#detailpanel_1"));

        }
        $('.product').css('width', '100%');
        $('.product').css('margin-top', '15px');
        $('.product a.listViewThLinkS1').css('font-size', '10px');
        $('.product a.listViewThLinkS1').removeAttr('href');
        $('.product td').css('text-align', 'center');
        $('.product .clickMenu').remove();
        $('.product img').remove();
        $('#content caption').css('color', 'red');
        $('#content caption').css('font-weight', 'bolder');
    }
});

function loadPhone() {
    if($('#mdlDemo').length == 0) {
        $('body').append('

');
        $("#mdlDemo").append('<button type="button" class="btn btn-primary" id="btnConfig">Открыть телефон</button>');
    }

    // Save form to localStorage and validate
    $('#btnConfig').click(function(event) {

        event.preventDefault();

        // launch the phone window.

            var url      = '/custom/extension/application/crm_field_masks/phone/',
                features = 'menubar=no,location=no,resizable=no,scrollbars=no,status=no,addressbar=no,width=320,height=480';

            if (!localStorage.getItem('ctxPhone')) {
                window.open(url, 'CRM Phone', features);
                $('#mdlDemo').modal('hide');
                return false;
            } else {
                window.alert('Phone already open.');
            }

    });

   // $('#popup').position({ my: 'left top', at: 'left bottom', of: $('a').first() });

}

function CRMFieldMasks()
{
	that        = this;
	this.debug  = false;
	this.cache  = [];

	this.dependency = 'custom/Extension/application/crm_field_masks/jquery.inputmask.bundle.min.js';

	this.cache_and_log = function(name, value)
	{
		if(this.debug)
		{	this.cache[name] = value;
			console.log('CRMMASKS - ' + name + ' = ' + value );
		}
	}

	this.selector_check = function()
	{
		if(this.debug)
		{	this.cache_and_log('selector_check - begin', true );
			$('input[name*="phone"]').css('color','#00f !important');
			this.cache_and_log('selector_check - end', true );
		}
	}

	this.run = function()
	{
		this.cache_and_log('run - begin', true );
		dependency = this.dependency;

		// load dependencies
		$.getScript(dependency)
			.done(function( script, textStatus )
			{
				that.apply_masks();
				that.cache_and_log( 'dependency loaded', dependency );
			})
			.fail(function( jqxhr, settings, exception )
			{
				that.cache_and_log( 'dependency failed to load', dependency );
			});

		this.cache_and_log('run - end', true );
	}

	this.apply_masks = function()
	{
		this.cache_and_log('apply_masks - begin', true );

		$('input[name^="phone"]').inputmask({"mask": "[+38]([0]99) 999-99-99"}); //specifying options

		$('input[name*="fax"]').inputmask({"mask": "[+38]([0]99) 999-99-99"}); //specifying options
                $('input[name*="card_num"]').inputmask({"mask": "9999 9999 9999 9999",clearMaskOnLostFocus: true,
                        onincomplete: function(){
                             //alert("Пожалуйста, укажите 16 цифр в формате XXXX XXXX XXXX XXXX");
                             //$(this).css({'border' : '1px solid #ff0000'});
                             //$(':input[type="submit"]').prop('disabled', true);
                        }}
                    );
                $('input[name*="ukrpasport_nom"]').inputmask({"mask": "[AA]999999"});
                $('input[name*="date"]').inputmask({"mask": "99/99/9999"});
                $('input[name*="mfo"]').inputmask({"mask": "999999",clearMaskOnLostFocus: true});
                $('input[name*="inn"]').inputmask({"mask": "9999999999",clearMaskOnLostFocus: true,
                   onincomplete: function(){

                            // $(this).css({'border' : '1px solid #ff0000'});
                             //$(':input[type="submit"]').prop('disabled', true);
                        },
                    complete: function(){

                            // $(this).css({'border' : '1px solid #569b44'});
                             //$(':input[type="submit"]').prop('disabled', true);
                    }

                });

		this.cache_and_log('apply_masks - end', true );
	}

};
<|endoftext|>


<commit_before>import { h, defineComponent, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'

import useCanRender from '../../composables/private/use-can-render.js'

import { listenOpts, noop } from '../../utils/event.js'

const hasObserver = typeof ResizeObserver !== 'undefined'
const resizeProps = hasObserver === true
  ? {}
  : {
      style: 'display:block;position:absolute;top:0;left:0;right:0;bottom:0;height:100%;width:100%;overflow:hidden;pointer-events:none;z-index:-1;',
      url: 'about: blank'
    }

export default defineComponent({
  name: 'QResizeObserver',

  props: {
    debounce: {
      type: [ String, Number ],
      default: 100
    }
  },

  emits: [ 'resize' ],

  setup (props, { emit }) {
    if (__QUASAR_SSR_SERVER__) { return noop }

    let timer, targetEl, size = { width: -1, height: -1 }

    function trigger (now) {
      if (now === true || props.debounce === 0 || props.debounce === '0') {
        onResize()
      }
      else if (!timer) {
        timer = setTimeout(onResize, props.debounce)
      }
    }

    function onResize () {
      timer = void 0

      const { offsetWidth: width, offsetHeight: height } = targetEl

      if (width !== size.width || height !== size.height) {
        size = { width, height }
        emit('resize', size)
      }
    }

    const vm = getCurrentInstance()

    // expose public methods
    Object.assign(vm.proxy, { trigger })

    if (hasObserver === true) {
      let observer

      onMounted(() => {
        targetEl = vm.proxy.$el.parentNode

        observer = new ResizeObserver(trigger)
        observer.observe(targetEl)

        onResize()
      })

      onBeforeUnmount(() => {
        clearTimeout(timer)

        if (observer !== void 0) {
          if (observer.disconnect !== void 0) {
            observer.disconnect()
          }
          else if (targetEl) { // FF for Android
            observer.unobserve(targetEl)
          }
        }
      })

      return noop
    }
    else { // no observer, so fallback to old iframe method
      const canRender = useCanRender()

      let curDocView

      function cleanup () {
        clearTimeout(timer)

        if (curDocView !== void 0) {
          // iOS is fuzzy, need to check it first
          if (curDocView.removeEventListener !== void 0) {
            curDocView.removeEventListener('resize', trigger, listenOpts.passive)
          }
          curDocView = void 0
        }
      }

      function onObjLoad () {
        cleanup()

        if (targetEl.contentDocument) {
          curDocView = targetEl.contentDocument.defaultView
          curDocView.addEventListener('resize', trigger, listenOpts.passive)
        }

        onResize()
      }

      onMounted(() => {
        targetEl = vm.proxy.$el
        onObjLoad()
      })

      onBeforeUnmount(cleanup)

      return () => {
        if (canRender.value === true) {
          return h('object', {
            style: resizeProps.style,
            tabindex: -1, // fix for Firefox
            type: 'text/html',
            data: resizeProps.url,
            'aria-hidden': 'true',
            onLoad: onObjLoad
          })
        }
      }
    }
  }
})
<commit_msg>Update QResizeObserver.js (#8997)<commit_after>import { h, defineComponent, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'

import useCanRender from '../../composables/private/use-can-render.js'

import { listenOpts, noop } from '../../utils/event.js'

const hasObserver = typeof ResizeObserver !== 'undefined'
const resizeProps = hasObserver === true
  ? {}
  : {
      style: 'display:block;position:absolute;top:0;left:0;right:0;bottom:0;height:100%;width:100%;overflow:hidden;pointer-events:none;z-index:-1;',
      url: '#blank'
    }

export default defineComponent({
  name: 'QResizeObserver',

  props: {
    debounce: {
      type: [ String, Number ],
      default: 100
    }
  },

  emits: [ 'resize' ],

  setup (props, { emit }) {
    if (__QUASAR_SSR_SERVER__) { return noop }

    let timer, targetEl, size = { width: -1, height: -1 }

    function trigger (now) {
      if (now === true || props.debounce === 0 || props.debounce === '0') {
        onResize()
      }
      else if (!timer) {
        timer = setTimeout(onResize, props.debounce)
      }
    }

    function onResize () {
      timer = void 0

      const { offsetWidth: width, offsetHeight: height } = targetEl

      if (width !== size.width || height !== size.height) {
        size = { width, height }
        emit('resize', size)
      }
    }

    const vm = getCurrentInstance()

    // expose public methods
    Object.assign(vm.proxy, { trigger })

    if (hasObserver === true) {
      let observer

      onMounted(() => {
        targetEl = vm.proxy.$el.parentNode

        observer = new ResizeObserver(trigger)
        observer.observe(targetEl)

        onResize()
      })

      onBeforeUnmount(() => {
        clearTimeout(timer)

        if (observer !== void 0) {
          if (observer.disconnect !== void 0) {
            observer.disconnect()
          }
          else if (targetEl) { // FF for Android
            observer.unobserve(targetEl)
          }
        }
      })

      return noop
    }
    else { // no observer, so fallback to old iframe method
      const canRender = useCanRender()

      let curDocView

      function cleanup () {
        clearTimeout(timer)

        if (curDocView !== void 0) {
          // iOS is fuzzy, need to check it first
          if (curDocView.removeEventListener !== void 0) {
            curDocView.removeEventListener('resize', trigger, listenOpts.passive)
          }
          curDocView = void 0
        }
      }

      function onObjLoad () {
        cleanup()

        if (targetEl && targetEl.contentDocument) {
          curDocView = targetEl.contentDocument.defaultView
          curDocView.addEventListener('resize', trigger, listenOpts.passive)
        }

        onResize()
      }

      onMounted(() => {
        targetEl = vm.proxy.$el
        onObjLoad()
      })

      onBeforeUnmount(cleanup)

      return () => {
        if (canRender.value === true) {
          return h('object', {
            style: resizeProps.style,
            tabindex: -1, // fix for Firefox
            type: 'text/html',
            data: resizeProps.url,
            'aria-hidden': 'true',
            onLoad: onObjLoad
          })
        }
      }
    }
  }
})
<|endoftext|>


<commit_before>/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */
if(!Koowa) {
    var Koowa = {};
}

(function($){
console.log('kooaw.overlay.js');
/**
 * Overlay class
 */
Koowa.Overlay = Koowa.Class.extend({
    element : null,
    /**
     * @returns {object}
     */
    getOptions: function() {
        return $.extend(this.supr(), {
            selector: 'body',
            ajaxify: true,
            method: 'get',
            cache: false,
            dataType: 'text',
            evalScripts: false,
            evalStyles: false
        });
    },
    initialize: function(element, options) {
        var self = this;
console.log('Koowa.Overlay.init');
        this.supr();

        this.element = $(element);

        if (!this.options.url) {
            this.options.url = this.element.data('url');
        }

        this.options.complete = function(jqXHR) {
            // FIXME: jQuery cannot parse <body> tags inside $ function
            var element = $(jqXHR.responseText),
                body = element.find(self.options.selector).length ? element.find(self.options.selector) : element;
            console.log(body, element.find(self.options.selector));
            self.element.empty().append(body);

            if (self.options.evalScripts) {
                self.evaluateScripts(element.find('script[type=text/javascript]'));
            }

            if (self.options.evalStyles) {
                self.evaulateStyles(element.find('link[type=text/css]'));
            }

            if (self.options.ajaxify) {
                self.element.find('a[href]').each(function(i, el){
                    var link = $(el);

                    //Avoid links with data-noasync attributes
                    if(link.data('noasync') != null) {
                        return;
                    }

                    link.on('click', function(event){
                        event.preventDefault();
                        event.stopPropagation();
                        self.send({url: this.href, data: {tmpl:''}});
                    });
                });

                self.element.find('.submittable').on('click', function(event){
                    event.preventDefault();

                    new Koowa.Form($(event.target).data('config')).submit();
                });

                self.element.find('.-koowa-grid').each(function(i, el){
                    var grid = $(el);

                    new Koowa.Controller.Grid({
                        form: grid,
                        ajaxify: true,
                        transport: function(url, data, method){
                            data += '&tmpl=';
                            self.send({url: url, data: data, method: method});
                        }
                    });
                });

                self.element.find('.-koowa-form').each(function(i, el){
                    var form = $(el);
                    new Koowa.Controller.Form({
                        form: form,
                        ajaxify: true,
                        transport: function(url, data, method) {
                            data += '&tmpl=';
                            self.send({url: url, data: data, method: method});
                        }
                    });
                });
            }
        };
        this.setOptions(options);

        $.ajax(this.options);
    },
    send: function(options){
        options = $.extend({}, this.options, options);

        $.ajax(options);
    },
    evaulateStyles: function(styles) {
        styles.each(function(style) {
            $(style).appendTo($('head'));
        });
    },
    evaluateScripts: function(scripts) {
        var script,
            loadScript = function(script){
                new $.getScript(script.src, function() {
                    if(scripts.length) {
                        loadScript(scripts.shift());
                    } else {
                        //Remove existing domready events as they've fired by now anyway
                        $(document).off('ready');

                        $(document).ready();
                    }
                });
            };

        scripts = scripts.filter(function(script) {
            if(!script.src) {
                return false;
            }

            return !$('head').getElement('script[src$=' + script.src.replace(location.origin, '') + ']');
        });

        if(scripts.length) {
            loadScript(scripts.shift());
        }
    }
});

})(jQuery);<commit_msg>re #28 setOptions needs to happen earlier, using it to fetch element data attributs as well<commit_after>/**
 * Koowa Framework - http://developer.joomlatools.com/koowa
 *
 * @copyright	Copyright (C) 2007 - 2013 Johan Janssens and Timble CVBA. (http://www.timble.net)
 * @license		GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link		http://github.com/joomlatools/koowa for the canonical source repository
 */
if(!Koowa) {
    var Koowa = {};
}

(function($){
/**
 * Overlay class
 */
Koowa.Overlay = Koowa.Class.extend({
    element : null,
    /**
     * @returns {object}
     */
    getOptions: function() {
        return $.extend(this.supr(), {
            selector: 'body',
            ajaxify: true,
            method: 'get',
            cache: false,
            dataType: 'text',
            evalScripts: false,
            evalStyles: false
        });
    },
    initialize: function(element, options) {
        var self = this;

        this.supr();

        this.element = $(element);

        this.setOptions(options).setOptions(this.element.data());

        this.options.complete = function(jqXHR) {
            // FIXME: jQuery cannot parse <body> tags inside $ function
            var element = $(jqXHR.responseText),
                body = element.find(self.options.selector).length ? element.find(self.options.selector) : element;
            console.log(body, element.find(self.options.selector));
            self.element.empty().append(body);

            if (self.options.evalScripts) {
                self.evaluateScripts(element.find('script[type=text/javascript]'));
            }

            if (self.options.evalStyles) {
                self.evaulateStyles(element.find('link[type=text/css]'));
            }

            if (self.options.ajaxify) {
                self.element.find('a[href]').each(function(i, el){
                    var link = $(el);

                    //Avoid links with data-noasync attributes
                    if(link.data('noasync') != null) {
                        return;
                    }

                    link.on('click', function(event){
                        event.preventDefault();
                        event.stopPropagation();
                        self.send({url: this.href, data: {tmpl:''}});
                    });
                });

                self.element.find('.submittable').on('click', function(event){
                    event.preventDefault();

                    new Koowa.Form($(event.target).data('config')).submit();
                });

                self.element.find('.-koowa-grid').each(function(i, el){
                    var grid = $(el);

                    new Koowa.Controller.Grid({
                        form: grid,
                        ajaxify: true,
                        transport: function(url, data, method){
                            data += '&tmpl=';
                            self.send({url: url, data: data, method: method});
                        }
                    });
                });

                self.element.find('.-koowa-form').each(function(i, el){
                    var form = $(el);
                    new Koowa.Controller.Form({
                        form: form,
                        ajaxify: true,
                        transport: function(url, data, method) {
                            data += '&tmpl=';
                            self.send({url: url, data: data, method: method});
                        }
                    });
                });
            }
        };

        $.ajax(this.options);
    },
    send: function(options){
        options = $.extend({}, this.options, options);

        $.ajax(options);
    },
    evaulateStyles: function(styles) {
        styles.each(function(style) {
            $(style).appendTo($('head'));
        });
    },
    evaluateScripts: function(scripts) {
        var script,
            loadScript = function(script){
                new $.getScript(script.src, function() {
                    if(scripts.length) {
                        loadScript(scripts.shift());
                    } else {
                        //Remove existing domready events as they've fired by now anyway
                        $(document).off('ready');

                        $(document).ready();
                    }
                });
            };

        scripts = scripts.filter(function(script) {
            if(!script.src) {
                return false;
            }

            return !$('head').getElement('script[src$=' + script.src.replace(location.origin, '') + ']');
        });

        if(scripts.length) {
            loadScript(scripts.shift());
        }
    }
});

})(jQuery);<|endoftext|>


<commit_before>import { parse } from 'babylon';
import { tryRequire } from '../utils';

const typescript = tryRequire('typescript');

const defaultCompileOptions = {
  module: typescript.ModuleKind.CommonJS,
  target: typescript.ScriptTarget.Latest,
  jsx: typescript.JsxEmit.React,
};

export default function parseTypescript(content, filePath) {
  if (!typescript) {
    return [];
  }

  const result = typescript.transpile(
    content,
    defaultCompileOptions,
    filePath);

  // TODO avoid parse source file twice, use Typescript native traverser to find out dependencies.
  // Reference: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#traversing-the-ast-with-a-little-linter
  return parse(result, {
    sourceType: 'module',
    plugins: ['*'],
  });
}
<commit_msg>Fix error when Typescript is not installed (#282)<commit_after>import { parse } from 'babylon';
import { tryRequire } from '../utils';

const typescript = tryRequire('typescript');

export default function parseTypescript(content, filePath) {
  if (!typescript) {
    return [];
  }

  const defaultCompileOptions = {
    module: typescript.ModuleKind.CommonJS,
    target: typescript.ScriptTarget.Latest,
    jsx: typescript.JsxEmit.React,
  };

  const result = typescript.transpile(
    content,
    defaultCompileOptions,
    filePath);

  // TODO avoid parse source file twice, use Typescript native traverser to find out dependencies.
  // Reference: https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#traversing-the-ast-with-a-little-linter
  return parse(result, {
    sourceType: 'module',
    plugins: ['*'],
  });
}
<|endoftext|>


<commit_before>const React = require('react');

const CompLibrary = require('../../core/CompLibrary');
const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;

const CWD = process.cwd();

const translate = require('../../server/translate.js').translate;

const siteConfig = require(`${CWD}/siteConfig.js`);
const releases = require(`${CWD}/releases.json`);
const pulsarManagerReleases = require(`${CWD}/pulsar-manager-release.json`)
const connectors = require(`${CWD}/data/connectors.js`);

function getLatestArchiveMirrorUrl(version, type) {
    return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}

function getLatestOffloadersMirrorUrl(version) {
    return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/apache-pulsar-offloaders-${version}-bin.tar.gz`
}

function distUrl(version, type) {
    return `https://www.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}

function distOffloadersUrl(version) {
    return `https://www.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-offloaders-${version}-bin.tar.gz`
}

function archiveUrl(version, type) {
    if (version.includes('incubating')) {
        return `https://archive.apache.org/dist/incubator/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
    } else {
        return `https://archive.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
    }
}

function connectorDistUrl(name, version) {
    return `https://www.apache.org/dist/pulsar/pulsar-${version}/connectors/pulsar-io-${name}-${version}.nar`
}

function connectorDownloadUrl(name, version) {
    return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/connectors/pulsar-io-${name}-${version}.nar`
}

function getLatestPulsarManagerArchiveMirrorUrl(version, type) {
  return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-manager/apache-pulsar-manager-${version}-${type}.tar.gz`
}

function pulsarManagerDistUrl(version, type) {
  return `https://www.apache.org/dist/pulsar/pulsar-manager/pulsar-manager-${version}/apache-pulsar-manager-${version}-${type}.tar.gz`
}

class Download extends React.Component {
  render() {
    const latestVersion = releases[0];
    const latestPulsarManagerVersion = pulsarManagerReleases[0];
    const latestArchiveMirrorUrl = getLatestArchiveMirrorUrl(latestVersion, 'bin');
    const latestSrcArchiveMirrorUrl = getLatestArchiveMirrorUrl(latestVersion, 'src');
    const latestPulsarManagerArchiveMirrorUrl = getLatestPulsarManagerArchiveMirrorUrl(latestPulsarManagerVersion, 'bin');
    const latestPulsarManagerSrcArchiveMirrorUrl = getLatestPulsarManagerArchiveMirrorUrl(latestPulsarManagerVersion, 'src');
    const latestArchiveUrl = distUrl(latestVersion, 'bin');
    const latestSrcArchiveUrl = distUrl(latestVersion, 'src')
    const pulsarManagerLatestArchiveUrl = pulsarManagerDistUrl(latestPulsarManagerVersion, 'bin');
    const pulsarManagerLatestSrcArchiveUrl = pulsarManagerDistUrl(latestPulsarManagerVersion, 'src');

    const releaseInfo = releases.map(version => {
      return {
        version: version,
        binArchiveUrl: archiveUrl(version, 'bin'),
        srcArchiveUrl: archiveUrl(version, 'src')
      }
    });

    return (

        <Container className="mainContainer documentContainer postContainer">

<translate>Apache Pulsar downloads</translate>

<translate>Release notes</translate>

                <a href={`${siteConfig.baseUrl}${this.props.language}/release-notes`}>Release notes for all Pulsar's versions

<translate>Current version (Stable)</translate> {latestVersion}

                  <translate>Release</translate>
                  <translate>Link</translate>
                  <translate>Crypto files</translate>

                  <translate>Binary</translate>

                    apache-pulsar-{latestVersion}-bin.tar.gz

                    <a href={`${latestArchiveUrl}.asc`}>asc,
                    <a href={`${latestArchiveUrl}.sha512`}>sha512

                  <translate>Source</translate>

                    apache-pulsar-{latestVersion}-src.tar.gz

                    <a href={`${latestSrcArchiveUrl}.asc`}>asc,
                    <a href={`${latestSrcArchiveUrl}.sha512`}>sha512

<translate>Tiered storage offloaders</translate>

                    <translate>Release</translate>
                    <translate>Link</translate>
                    <translate>Crypto files</translate>

                    <translate>Offloaders</translate>

                      apache-pulsar-offloaders-{latestVersion}-bin.tar.gz

                      <a href={`${distOffloadersUrl(latestVersion)}.asc`}>asc,
                      <a href={`${distOffloadersUrl(latestVersion)}.sha512`}>sha512

<translate>Pulsar IO connectors</translate>

                  <translate>IO connector</translate>
                  <translate>Archive</translate>
                  <translate>Crypto files</translate>

              {connectors.map(
                connector =>

                        <a href={`${connector.link}`} target="_blank">{connector.longName}

                        <a href={`${connectorDownloadUrl(connector.name, latestVersion)}`} target="_blank">pulsar-io-{connector.name}-{latestVersion}.nar

                        <a href={`${connectorDistUrl(connector.name, latestVersion)}.asc`}>asc,
                        <a href={`${connectorDistUrl(connector.name, latestVersion)}.sha512`}>sha512

              )}

<translate>Release Integrity</translate>

            <MarkdownBlock>
              You must [verify](https://www.apache.org/info/verification.html) the integrity of the downloaded files.
              We provide OpenPGP signatures for every release file. This signature should be matched against the
              [KEYS](https://www.apache.org/dist/pulsar/KEYS) file which contains the OpenPGP keys of
              Pulsar's Release Managers. We also provide `SHA-512` checksums for every release file.
              After you download the file, you should calculate a checksum for your download, and make sure it is
              the same as ours.
            </MarkdownBlock>

<translate>Getting started</translate>

              <translate>
                Once you've downloaded a Pulsar release, instructions on getting up and running with a standalone cluster
                that you can run on your laptop can be found in the{' '}
              </translate>
                <a href={`${siteConfig.baseUrl}docs/${this.props.language}/standalone`}><translate>Run Pulsar locally</translate> <translate>tutorial</translate>.

              <translate>
              If you need to connect to an existing Pulsar cluster or instance using an officially supported client,
              see the client docs for these languages:
              </translate>

                  <translate>Client guide</translate>
                  <translate>API docs</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-java`}><translate>The Pulsar java client</translate>
                  <translate>The Pulsar java client</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-go`}><translate>The Pulsar go client</translate>
                  <translate>The Pulsar go client</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-python`}><translate>The Pulsar python client</translate>
                  <translate>The Pulsar python client</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-cpp`}><translate>The Pulsar C++ client</translate>
                  <translate>The Pulsar C++ client</translate>

<translate>Older releases</translate>

                  <translate>Release</translate>
                  <translate>Binary</translate>
                  <translate>Source</translate>
                  <translate>Release notes</translate>

                {releaseInfo.map(
                  info => {
                        var sha = "sha512"
                        if (info.version.includes('1.19.0-incubating') || info.version.includes('1.20.0-incubating')) {
                            sha = "sha"
                        }
                        return info.version !== latestVersion && (

                        {info.version}

                        apache-pulsar-{info.version}-bin-tar.gz
                          (<a href={`${info.binArchiveUrl}.asc`}>asc,
                          <a href={`${info.binArchiveUrl}.${sha}`}>{`${sha}`})

                          apache-pulsar-{info.version}-src-tar.gz

                          (<a href={`${info.srcArchiveUrl}.asc`}>asc,
                          <a href={`${info.srcArchiveUrl}.${sha}`}>{`${sha}`})

                          <a href={`${siteConfig.baseUrl}${this.props.language}/release-notes#${info.version}`}><translate>Release Notes</translate>

                      )
                    }
                )}

<translate>Apache Pulsar Manager downloads</translate>

<translate>Release notes</translate>

                <a href={`${siteConfig.baseUrl}${this.props.language}/pulsar-manager-release-notes`}>Release notes for all pulsar-manager's versions

<translate>Current version (Stable)</translate> {latestPulsarManagerVersion}

                  <translate>Release</translate>
                  <translate>Link</translate>
                  <translate>Crypto files</translate>

                  <translate>Binary</translate>

                    apache-pulsar-manager-{latestPulsarManagerVersion}-bin.tar.gz

                    <a href={`${pulsarManagerLatestArchiveUrl}.asc`}>asc,
                    <a href={`${pulsarManagerLatestArchiveUrl}.sha512`}>sha512

                  <translate>Source</translate>

                    apache-pulsar-manager-{latestPulsarManagerVersion}-src.tar.gz

                    <a href={`${pulsarManagerLatestSrcArchiveUrl}.asc`}>asc,
                    <a href={`${pulsarManagerLatestSrcArchiveUrl}.sha512`}>sha512

        </Container>

    );
  }
}

module.exports = Download;
<commit_msg>Fix pulsar-manager download link (#5774)<commit_after>const React = require('react');

const CompLibrary = require('../../core/CompLibrary');
const MarkdownBlock = CompLibrary.MarkdownBlock; /* Used to read markdown */
const Container = CompLibrary.Container;
const GridBlock = CompLibrary.GridBlock;

const CWD = process.cwd();

const translate = require('../../server/translate.js').translate;

const siteConfig = require(`${CWD}/siteConfig.js`);
const releases = require(`${CWD}/releases.json`);
const pulsarManagerReleases = require(`${CWD}/pulsar-manager-release.json`)
const connectors = require(`${CWD}/data/connectors.js`);

function getLatestArchiveMirrorUrl(version, type) {
    return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}

function getLatestOffloadersMirrorUrl(version) {
    return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/apache-pulsar-offloaders-${version}-bin.tar.gz`
}

function distUrl(version, type) {
    return `https://www.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
}

function distOffloadersUrl(version) {
    return `https://www.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-offloaders-${version}-bin.tar.gz`
}

function archiveUrl(version, type) {
    if (version.includes('incubating')) {
        return `https://archive.apache.org/dist/incubator/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
    } else {
        return `https://archive.apache.org/dist/pulsar/pulsar-${version}/apache-pulsar-${version}-${type}.tar.gz`
    }
}

function connectorDistUrl(name, version) {
    return `https://www.apache.org/dist/pulsar/pulsar-${version}/connectors/pulsar-io-${name}-${version}.nar`
}

function connectorDownloadUrl(name, version) {
    return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-${version}/connectors/pulsar-io-${name}-${version}.nar`
}

function getLatestPulsarManagerArchiveMirrorUrl(version, type) {
  return `https://www.apache.org/dyn/mirrors/mirrors.cgi?action=download&filename=pulsar/pulsar-manager/pulsar-manager-${version}/apache-pulsar-manager-${version}-${type}.tar.gz`
}

function pulsarManagerDistUrl(version, type) {
  return `https://www.apache.org/dist/pulsar/pulsar-manager/pulsar-manager-${version}/apache-pulsar-manager-${version}-${type}.tar.gz`
}

class Download extends React.Component {
  render() {
    const latestVersion = releases[0];
    const latestPulsarManagerVersion = pulsarManagerReleases[0];
    const latestArchiveMirrorUrl = getLatestArchiveMirrorUrl(latestVersion, 'bin');
    const latestSrcArchiveMirrorUrl = getLatestArchiveMirrorUrl(latestVersion, 'src');
    const latestPulsarManagerArchiveMirrorUrl = getLatestPulsarManagerArchiveMirrorUrl(latestPulsarManagerVersion, 'bin');
    const latestPulsarManagerSrcArchiveMirrorUrl = getLatestPulsarManagerArchiveMirrorUrl(latestPulsarManagerVersion, 'src');
    const latestArchiveUrl = distUrl(latestVersion, 'bin');
    const latestSrcArchiveUrl = distUrl(latestVersion, 'src')
    const pulsarManagerLatestArchiveUrl = pulsarManagerDistUrl(latestPulsarManagerVersion, 'bin');
    const pulsarManagerLatestSrcArchiveUrl = pulsarManagerDistUrl(latestPulsarManagerVersion, 'src');

    const releaseInfo = releases.map(version => {
      return {
        version: version,
        binArchiveUrl: archiveUrl(version, 'bin'),
        srcArchiveUrl: archiveUrl(version, 'src')
      }
    });

    return (

        <Container className="mainContainer documentContainer postContainer">

<translate>Apache Pulsar downloads</translate>

<translate>Release notes</translate>

                <a href={`${siteConfig.baseUrl}${this.props.language}/release-notes`}>Release notes for all Pulsar's versions

<translate>Current version (Stable)</translate> {latestVersion}

                  <translate>Release</translate>
                  <translate>Link</translate>
                  <translate>Crypto files</translate>

                  <translate>Binary</translate>

                    apache-pulsar-{latestVersion}-bin.tar.gz

                    <a href={`${latestArchiveUrl}.asc`}>asc,
                    <a href={`${latestArchiveUrl}.sha512`}>sha512

                  <translate>Source</translate>

                    apache-pulsar-{latestVersion}-src.tar.gz

                    <a href={`${latestSrcArchiveUrl}.asc`}>asc,
                    <a href={`${latestSrcArchiveUrl}.sha512`}>sha512

<translate>Tiered storage offloaders</translate>

                    <translate>Release</translate>
                    <translate>Link</translate>
                    <translate>Crypto files</translate>

                    <translate>Offloaders</translate>

                      apache-pulsar-offloaders-{latestVersion}-bin.tar.gz

                      <a href={`${distOffloadersUrl(latestVersion)}.asc`}>asc,
                      <a href={`${distOffloadersUrl(latestVersion)}.sha512`}>sha512

<translate>Pulsar IO connectors</translate>

                  <translate>IO connector</translate>
                  <translate>Archive</translate>
                  <translate>Crypto files</translate>

              {connectors.map(
                connector =>

                        <a href={`${connector.link}`} target="_blank">{connector.longName}

                        <a href={`${connectorDownloadUrl(connector.name, latestVersion)}`} target="_blank">pulsar-io-{connector.name}-{latestVersion}.nar

                        <a href={`${connectorDistUrl(connector.name, latestVersion)}.asc`}>asc,
                        <a href={`${connectorDistUrl(connector.name, latestVersion)}.sha512`}>sha512

              )}

<translate>Release Integrity</translate>

            <MarkdownBlock>
              You must [verify](https://www.apache.org/info/verification.html) the integrity of the downloaded files.
              We provide OpenPGP signatures for every release file. This signature should be matched against the
              [KEYS](https://www.apache.org/dist/pulsar/KEYS) file which contains the OpenPGP keys of
              Pulsar's Release Managers. We also provide `SHA-512` checksums for every release file.
              After you download the file, you should calculate a checksum for your download, and make sure it is
              the same as ours.
            </MarkdownBlock>

<translate>Getting started</translate>

              <translate>
                Once you've downloaded a Pulsar release, instructions on getting up and running with a standalone cluster
                that you can run on your laptop can be found in the{' '}
              </translate>
                <a href={`${siteConfig.baseUrl}docs/${this.props.language}/standalone`}><translate>Run Pulsar locally</translate> <translate>tutorial</translate>.

              <translate>
              If you need to connect to an existing Pulsar cluster or instance using an officially supported client,
              see the client docs for these languages:
              </translate>

                  <translate>Client guide</translate>
                  <translate>API docs</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-java`}><translate>The Pulsar java client</translate>
                  <translate>The Pulsar java client</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-go`}><translate>The Pulsar go client</translate>
                  <translate>The Pulsar go client</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-python`}><translate>The Pulsar python client</translate>
                  <translate>The Pulsar python client</translate>

                  <a href={`${siteConfig.baseUrl}docs/${this.props.language}/client-libraries-cpp`}><translate>The Pulsar C++ client</translate>
                  <translate>The Pulsar C++ client</translate>

<translate>Older releases</translate>

                  <translate>Release</translate>
                  <translate>Binary</translate>
                  <translate>Source</translate>
                  <translate>Release notes</translate>

                {releaseInfo.map(
                  info => {
                        var sha = "sha512"
                        if (info.version.includes('1.19.0-incubating') || info.version.includes('1.20.0-incubating')) {
                            sha = "sha"
                        }
                        return info.version !== latestVersion && (

                        {info.version}

                        apache-pulsar-{info.version}-bin-tar.gz
                          (<a href={`${info.binArchiveUrl}.asc`}>asc,
                          <a href={`${info.binArchiveUrl}.${sha}`}>{`${sha}`})

                          apache-pulsar-{info.version}-src-tar.gz

                          (<a href={`${info.srcArchiveUrl}.asc`}>asc,
                          <a href={`${info.srcArchiveUrl}.${sha}`}>{`${sha}`})

                          <a href={`${siteConfig.baseUrl}${this.props.language}/release-notes#${info.version}`}><translate>Release Notes</translate>

                      )
                    }
                )}

<translate>Apache Pulsar Manager downloads</translate>

<translate>Release notes</translate>

                <a href={`${siteConfig.baseUrl}${this.props.language}/pulsar-manager-release-notes`}>Release notes for all pulsar-manager's versions

<translate>Current version (Stable)</translate> {latestPulsarManagerVersion}

                  <translate>Release</translate>
                  <translate>Link</translate>
                  <translate>Crypto files</translate>

                  <translate>Binary</translate>

                    apache-pulsar-manager-{latestPulsarManagerVersion}-bin.tar.gz

                    <a href={`${pulsarManagerLatestArchiveUrl}.asc`}>asc,
                    <a href={`${pulsarManagerLatestArchiveUrl}.sha512`}>sha512

                  <translate>Source</translate>

                    apache-pulsar-manager-{latestPulsarManagerVersion}-src.tar.gz

                    <a href={`${pulsarManagerLatestSrcArchiveUrl}.asc`}>asc,
                    <a href={`${pulsarManagerLatestSrcArchiveUrl}.sha512`}>sha512

        </Container>

    );
  }
}

module.exports = Download;
<|endoftext|>


<commit_before>/*jslint indent: 2, nomen: true, maxlen: 100, white: true  plusplus: true, browser: true*/
/*global describe, beforeEach, afterEach, it, spyOn, expect*/
/*global $*/

(function() {
  "use strict";

  describe("Arango Collection Model", function() {

    var myCollection;

    beforeEach(function() {
      myCollection = new window.arangoCollectionModel();
    });

    it("verifies urlRoot", function() {
      expect(myCollection.urlRoot).toEqual('/_api/collection');
    });

    it("verifies defaults", function() {
      expect(myCollection.get('id')).toEqual('');
      expect(myCollection.get('name')).toEqual('');
      expect(myCollection.get('status')).toEqual('');
      expect(myCollection.get('type')).toEqual('');
      expect(myCollection.get('isSystem')).toBeFalsy();
      expect(myCollection.get('picture')).toEqual('');
    });

    it("verifies set defaults", function() {
      var name = 'blub',
        status = 'active',
        type   = 'myType';
      myCollection = new window.arangoCollectionModel(
        {
          name    : name,
          status  : status,
          type    : type
        }
      );
      expect(myCollection.get('id')).toEqual('');
      expect(myCollection.get('name')).toEqual(name);
      expect(myCollection.get('status')).toEqual(status);
      expect(myCollection.get('type')).toEqual(type);
      expect(myCollection.isSystem).toBeFalsy();
      expect(myCollection.get('picture')).toEqual('');
    });

    it("verifies getProperties", function() {
      var id = "4711";
      spyOn($, "ajax").andCallFake(function(opt) {
        expect(opt.url).toEqual("/_api/collection/" + id + "/properties");
        expect(opt.type).toEqual("GET");
      });
      myCollection.set('id', id);
      myCollection.getProperties();
    });

    it("verifies getFigures", function() {
      var id = "4711";
      spyOn($, "ajax").andCallFake(function(opt) {
        expect(opt.url).toEqual("/_api/collection/" + id + "/figures");
        expect(opt.type).toEqual("GET");
      });
      myCollection.set('id', id);
      myCollection.getFigures();
    });

    it("verifies getRevision", function() {
      var id = "4711";
      spyOn($, "ajax").andCallFake(function(opt) {
        expect(opt.url).toEqual("/_api/collection/" + id + "/revision");
        expect(opt.type).toEqual("GET");
      });
      myCollection.set('id', id);
      myCollection.getRevision();
    });

    it("verifies getIndex", function() {
      var id = "4711";
      spyOn($, "ajax").andCallFake(function(opt) {
        expect(opt.url).toEqual("/_api/index/?collection=" + id);
        expect(opt.type).toEqual("GET");
      });
      myCollection.set('id', id);
      myCollection.getIndex();
    });
  });

}());
<commit_msg>Added tests for correct behaviour of callback functions in arangoCollection Model<commit_after>/*jslint indent: 2, nomen: true, maxlen: 100, white: true  plusplus: true, browser: true*/
/*global describe, beforeEach, afterEach, it, spyOn, expect, jasmine*/
/*global $, arangoHelper*/

(function() {
  "use strict";

  describe("Arango Collection Model", function() {

    var myCollection;

    beforeEach(function() {
      myCollection = new window.arangoCollectionModel();
    });

    it("verifies urlRoot", function() {
      expect(myCollection.urlRoot).toEqual('/_api/collection');
    });

    it("verifies defaults", function() {
      expect(myCollection.get('id')).toEqual('');
      expect(myCollection.get('name')).toEqual('');
      expect(myCollection.get('status')).toEqual('');
      expect(myCollection.get('type')).toEqual('');
      expect(myCollection.get('isSystem')).toBeFalsy();
      expect(myCollection.get('picture')).toEqual('');
    });

    it("verifies set defaults", function() {
      var name = 'blub',
        status = 'active',
        type   = 'myType';
      myCollection = new window.arangoCollectionModel(
        {
          name    : name,
          status  : status,
          type    : type
        }
      );
      expect(myCollection.get('id')).toEqual('');
      expect(myCollection.get('name')).toEqual(name);
      expect(myCollection.get('status')).toEqual(status);
      expect(myCollection.get('type')).toEqual(type);
      expect(myCollection.isSystem).toBeFalsy();
      expect(myCollection.get('picture')).toEqual('');
    });

    describe("checking ajax", function() {
      var url, type, shouldFail, successResult, failResult, id, data;

      beforeEach(function() {
        id = "4711";
        successResult = "success";
        failResult = "fail";
        myCollection.set('id', id);
        spyOn($, "ajax").andCallFake(function(opt) {
          expect(opt.url).toEqual(url);
          expect(opt.type).toEqual(type);
          expect(opt.success).toEqual(jasmine.any(Function));
          expect(opt.error).toEqual(jasmine.any(Function));
          if (opt.data) {
            expect(opt.data).toEqual(data);
          }
          if (shouldFail) {
            opt.error(failResult);
          } else {
            opt.success(successResult);
          }
        });
      });

      describe("getProperties", function() {

        beforeEach(function() {
          url = "/_api/collection/" + id + "/properties";
          type = "GET";
        });

        it("success", function() {
          shouldFail = false;
          expect(myCollection.getProperties()).toEqual(successResult);
        });

        it("fail", function() {
          shouldFail = true;
          expect(myCollection.getProperties()).toEqual(failResult);
        });
      });

      describe("getFigures", function() {

        beforeEach(function() {
          url = "/_api/collection/" + id + "/figures";
          type = "GET";
        });

        it("success", function() {
          shouldFail = false;
          expect(myCollection.getFigures()).toEqual(successResult);
        });

        it("fail", function() {
          shouldFail = true;
          expect(myCollection.getFigures()).toEqual(failResult);
        });
      });

      describe("getRevision", function() {

        beforeEach(function() {
          url = "/_api/collection/" + id + "/revision";
          type = "GET";
        });

        it("success", function() {
          shouldFail = false;
          expect(myCollection.getRevision()).toEqual(successResult);
        });

        it("fail", function() {
          shouldFail = true;
          expect(myCollection.getRevision()).toEqual(failResult);
        });
      });

      describe("getFigures", function() {

        beforeEach(function() {
          url = "/_api/index/?collection=" + id;
          type = "GET";
        });

        it("success", function() {
          shouldFail = false;
          expect(myCollection.getIndex()).toEqual(successResult);
        });

        it("fail", function() {
          shouldFail = true;
          expect(myCollection.getIndex()).toEqual(failResult);
        });
      });

      describe("loadCollection", function() {

        beforeEach(function() {
          url = "/_api/collection/" + id + "/load";
          type = "PUT";
        });

        it("success", function() {
          shouldFail = false;
          spyOn(arangoHelper, "arangoNotification");
          myCollection.loadCollection();
          expect(myCollection.get("status")).toEqual("loaded");
        });

        it("fail", function() {
          shouldFail = true;
          spyOn(arangoHelper, "arangoError");
          myCollection.loadCollection();
          expect(arangoHelper.arangoError).toHaveBeenCalledWith("Collection error");
        });
      });

      describe("unloadCollection", function() {

        beforeEach(function() {
          url = "/_api/collection/" + id + "/unload";
          type = "PUT";
        });

        it("success", function() {
          shouldFail = false;
          spyOn(arangoHelper, "arangoNotification");
          myCollection.unloadCollection();
          expect(myCollection.get("status")).toEqual("unloaded");
        });

        it("fail", function() {
          shouldFail = true;
          spyOn(arangoHelper, "arangoError");
          myCollection.unloadCollection();
          expect(arangoHelper.arangoError).toHaveBeenCalledWith("Collection error");
        });
      });

      describe("renameCollection", function() {

        var name;

        beforeEach(function() {
          name = "newname";
          url = "/_api/collection/" + id + "/rename";
          type = "PUT";
          data = JSON.stringify({name: name});
        });

        it("success", function() {
          shouldFail = false;
          expect(myCollection.renameCollection(name)).toBeTruthy();
          expect(myCollection.get("name")).toEqual(name);
        });

        it("fail", function() {
          shouldFail = true;
          expect(myCollection.renameCollection(name)).toBeFalsy();
          expect(myCollection.get("name")).not.toEqual(name);
        });
      });

      describe("changeCollection", function() {
        var wfs, jns;

        beforeEach(function() {
          wfs = true;
          jns = 10 * 100 * 1000;
          url = "/_api/collection/" + id + "/properties";
          type = "PUT";
          data = JSON.stringify({waitForSync: wfs, journalSize: jns});
        });

        it("success", function() {
          shouldFail = false;
          expect(myCollection.changeCollection(wfs, jns)).toBeTruthy();
        });

        it("fail", function() {
          shouldFail = true;
          expect(myCollection.changeCollection(wfs, jns)).toBeFalsy();
        });
      });
    });
  });
}());
<|endoftext|>


<commit_before>
define(function (require, exports, module) {
    "use strict";

    var Core = app.getModule("core/Core");
    var AppInit = app.getModule("utils/AppInit");
    var EditorView = app.getModule("editors/EditorView");
    var Repository = app.getModule("core/Repository");
    var ProjectManager = app.getModule("engine/ProjectManager");
    var SelectionManager = app.getModule("engine/SelectionManager");
    var Engine = app.getModule("engine/Engine");

    var viewTemplate = require("text!htmlContent/Sitecore-Field-Editor-View.html");

    var $view = null;
    var _attributeElement = null;

    var input_title_id = "#sitecoreField_Title";
    var input_source_id = "#sitecoreField_Source";
    var input_shared_id = "#sitecoreField_Shared";
    var input_unversioned_id = "#sitecoreField_Unversioned";
    var input_sectionName_id = "#sitecoreField_SectionName";
    var input_standardValue_id = "#sitecoreField_StandardValue";
    var input_autoDocument_id = "#sitecoreField_Documentation";

    var fieldAttributes = [
        { name: "Title", kind: "string", default: null },
        { name: "SectionName", kind: "string", default: null },
        { name: "Source", kind: "string", default: null },
        { name: "Shared", kind: "boolean", default: false },
        { name: "Unversioned", kind: "boolean", default: false },
        { name: "StandardValue", kind: "string", default: null }
    ];

    var defaultInputValues = {};
    // populate the default input values for the field attributes
    fieldAttributes.forEach(function(fieldAttr) {
        defaultInputValues[fieldAttr.name] =
            fieldAttr.default === null
                ? "" // so that 'null' doesn't display in the input
                : fieldAttr.default;
    });
    // add the default input value for the Documentation input
    defaultInputValues["Documentation"] = true;

    // sets the input to the value that already exists for the attribute of the field
    function _setExistingValueForInput($input, attributeEle, name) {
        var existing = undefined;
        for (var i = 0; i < attributeEle.ownedElements.length; i++) {
            var ownedEle = attributeEle.ownedElements[i];
            if (ownedEle.name == name) {
                existing = ownedEle;
                break;
            }
        }

        var value = existing !== undefined ? existing.value : defaultInputValues[name];

        // intentionally using attr here to avoid caching
        var kind = $input.attr("data-kind");
        if (kind == "string") {
            $input.val(value);
        } else if (kind == "boolean") {
            $input.prop("checked", value);
        }
    };

    function show(elem) {
        if (elem instanceof type.UMLAttribute) {
            $view.show();

            _attributeElement = elem;

            _setExistingValueForInput($(input_title_id), _attributeElement, "Title");
            _setExistingValueForInput($(input_sectionName_id), _attributeElement, "SectionName");
            _setExistingValueForInput($(input_source_id), _attributeElement, "Source");
            _setExistingValueForInput($(input_shared_id), _attributeElement, "Shared");
            _setExistingValueForInput($(input_unversioned_id), _attributeElement, "Unversioned");
            _setExistingValueForInput($(input_standardValue_id), _attributeElement, "StandardValue");
            _setExistingValueForInput($(input_autoDocument_id), _attributeElement, "Documentation");
        } else {
            $view.hide();
            _attributeElement = null;
        }
    };

    // bind events for updating editor
    function _initializeEventHandlers() {
        $(Repository).on('updated', function (event, elems) {
            try {
                _.forEach(elems, function (elem) {
                    if (SelectionManager.getSelected() === elem) {
                        show(elem);
                    }
                });
            } catch (err) {
                console.error(err);
            }
        });

        $(ProjectManager).on('projectClosed', function (event) {
            try {
                show(null);
            } catch (err) {
                console.error(err);
            }
        });

        $(SelectionManager).on('selectionChanged', function (event, models, views) {
            try {
                if (models.length === 1) {
                    show(models[0]);
                } else {
                    show(null);
                }
            } catch (err) {
                console.error(err);
            }
        });
    };

    function createAttributeDocumentation(attributeEle) {
        var fieldAttributeMap = {};
        attributeEle.ownedElements.forEach(function(element) {
            if (element instanceof type.Tag) {
                fieldAttributeMap[element.name] = element.value;
            }
        });
        var docString = "";
        var numFieldAttributes = fieldAttributes.length;
        fieldAttributes.forEach(function(fieldAttribute, i) {
            var value = fieldAttributeMap[fieldAttribute.name];
            if (value === undefined || value === "") {
                value = fieldAttribute.default;
            }
            docString += fieldAttribute.name + ": " + JSON.stringify(value);
            if (numFieldAttributes > i + 1) {
                docString += ",\n";
            }
        });

        return docString;
    };

    function updateAttributeDocumentation(attributeEle) {
        var docString = createAttributeDocumentation(attributeEle);
        Engine.setProperty(attributeEle, "documentation", docString);
    };

    function _handleViewChangeForInput($input, attributeEle, name) {
        try {
            var existing = undefined;
            if (attributeEle) {
                for (var i = 0; i < attributeEle.ownedElements.length; i++) {
                    var ownedEle = attributeEle.ownedElements[i];
                    if (ownedEle.name == name) {
                        existing = ownedEle;
                        break;
                    }
                }
            }

            if (existing) {
                if (existing.kind == "string") {
                    var value = $input.val();
                    existing.value = value;
                } else if (existing.kind == "boolean") {
                    existing.value = $input.is(":checked");
                }
            } else {
                var value = undefined;

                // intentionally using attr to avoid caching
                var kind = $input.attr("data-kind");
                if (kind == "string") {
                    value = $input.val();
                } else if (kind == "boolean") {
                    value = $input.is(":checked");
                }

                var tag = new Core.Tag();
                tag.name = name;
                tag.kind = kind;
                tag.value = value;

                // add the tag
                attributeEle.ownedElements.push(tag);
            }

            // auto-update the documentation, if checked
            var $input_autoDocument = $(input_autoDocument_id);
            if ($input_autoDocument.is(":checked")) {
                updateAttributeDocumentation(attributeEle);
            }
        } catch (err) {
            console.error(err);
        }
    };

    AppInit.htmlReady(function () {
        $view = $(viewTemplate);

        $view.on("change", ".sitecore-field-attribute", function() {
            var $this = $(this);
            // intentionally using attr to avoid caching
            var name = $this.attr("data-name");
            _handleViewChangeForInput($this, _attributeElement, name);
        });

        EditorView.setupEditorView($view);
        show();

        _initializeEventHandlers();
    });

    exports.show = show;
    exports.fieldAttributes = fieldAttributes;
    exports.updateAttributeDocumentation = updateAttributeDocumentation;
    exports.createAttributeDocumentation = createAttributeDocumentation;
});

<commit_msg>Enhances the documentation format with markdown to make it more legible in generated documentation<commit_after>
define(function (require, exports, module) {
    "use strict";

    var Core = app.getModule("core/Core");
    var AppInit = app.getModule("utils/AppInit");
    var EditorView = app.getModule("editors/EditorView");
    var Repository = app.getModule("core/Repository");
    var ProjectManager = app.getModule("engine/ProjectManager");
    var SelectionManager = app.getModule("engine/SelectionManager");
    var Engine = app.getModule("engine/Engine");

    var viewTemplate = require("text!htmlContent/Sitecore-Field-Editor-View.html");

    var $view = null;
    var _attributeElement = null;

    var input_title_id = "#sitecoreField_Title";
    var input_source_id = "#sitecoreField_Source";
    var input_shared_id = "#sitecoreField_Shared";
    var input_unversioned_id = "#sitecoreField_Unversioned";
    var input_sectionName_id = "#sitecoreField_SectionName";
    var input_standardValue_id = "#sitecoreField_StandardValue";
    var input_autoDocument_id = "#sitecoreField_Documentation";

    var fieldAttributes = [
        { name: "Title", kind: "string", default: null },
        { name: "SectionName", kind: "string", default: null },
        { name: "Source", kind: "string", default: null },
        { name: "Shared", kind: "boolean", default: false },
        { name: "Unversioned", kind: "boolean", default: false },
        { name: "StandardValue", kind: "string", default: null }
    ];

    var defaultInputValues = {};
    // populate the default input values for the field attributes
    fieldAttributes.forEach(function(fieldAttr) {
        defaultInputValues[fieldAttr.name] =
            fieldAttr.default === null
                ? "" // so that 'null' doesn't display in the input
                : fieldAttr.default;
    });
    // add the default input value for the Documentation input
    defaultInputValues["Documentation"] = true;

    // sets the input to the value that already exists for the attribute of the field
    function _setExistingValueForInput($input, attributeEle, name) {
        var existing = undefined;
        for (var i = 0; i < attributeEle.ownedElements.length; i++) {
            var ownedEle = attributeEle.ownedElements[i];
            if (ownedEle.name == name) {
                existing = ownedEle;
                break;
            }
        }

        var value = existing !== undefined ? existing.value : defaultInputValues[name];

        // intentionally using attr here to avoid caching
        var kind = $input.attr("data-kind");
        if (kind == "string") {
            $input.val(value);
        } else if (kind == "boolean") {
            $input.prop("checked", value);
        }
    };

    function show(elem) {
        if (elem instanceof type.UMLAttribute) {
            $view.show();

            _attributeElement = elem;

            _setExistingValueForInput($(input_title_id), _attributeElement, "Title");
            _setExistingValueForInput($(input_sectionName_id), _attributeElement, "SectionName");
            _setExistingValueForInput($(input_source_id), _attributeElement, "Source");
            _setExistingValueForInput($(input_shared_id), _attributeElement, "Shared");
            _setExistingValueForInput($(input_unversioned_id), _attributeElement, "Unversioned");
            _setExistingValueForInput($(input_standardValue_id), _attributeElement, "StandardValue");
            _setExistingValueForInput($(input_autoDocument_id), _attributeElement, "Documentation");
        } else {
            $view.hide();
            _attributeElement = null;
        }
    };

    // bind events for updating editor
    function _initializeEventHandlers() {
        $(Repository).on('updated', function (event, elems) {
            try {
                _.forEach(elems, function (elem) {
                    if (SelectionManager.getSelected() === elem) {
                        show(elem);
                    }
                });
            } catch (err) {
                console.error(err);
            }
        });

        $(ProjectManager).on('projectClosed', function (event) {
            try {
                show(null);
            } catch (err) {
                console.error(err);
            }
        });

        $(SelectionManager).on('selectionChanged', function (event, models, views) {
            try {
                if (models.length === 1) {
                    show(models[0]);
                } else {
                    show(null);
                }
            } catch (err) {
                console.error(err);
            }
        });
    };

    function createAttributeDocumentation(attributeEle) {
        var fieldAttributeMap = {};
        attributeEle.ownedElements.forEach(function(element) {
            if (element instanceof type.Tag) {
                fieldAttributeMap[element.name] = element.value;
            }
        });
        var docString = "";
        var numFieldAttributes = fieldAttributes.length;
        fieldAttributes.forEach(function(fieldAttribute, i) {
            var value = fieldAttributeMap[fieldAttribute.name];
            if (value === undefined || value === "") {
                value = fieldAttribute.default;
            }

            docString += "**" + fieldAttribute.name + ":** `" + JSON.stringify(value) + "`";
            if (numFieldAttributes > i + 1) {
                docString += "  \n";
            }
        });

        return docString;
    };

    function updateAttributeDocumentation(attributeEle) {
        var docString = createAttributeDocumentation(attributeEle);
        Engine.setProperty(attributeEle, "documentation", docString);
    };

    function _handleViewChangeForInput($input, attributeEle, name) {
        try {
            var existing = undefined;
            if (attributeEle) {
                for (var i = 0; i < attributeEle.ownedElements.length; i++) {
                    var ownedEle = attributeEle.ownedElements[i];
                    if (ownedEle.name == name) {
                        existing = ownedEle;
                        break;
                    }
                }
            }

            if (existing) {
                if (existing.kind == "string") {
                    var value = $input.val();
                    existing.value = value;
                } else if (existing.kind == "boolean") {
                    existing.value = $input.is(":checked");
                }
            } else {
                var value = undefined;

                // intentionally using attr to avoid caching
                var kind = $input.attr("data-kind");
                if (kind == "string") {
                    value = $input.val();
                } else if (kind == "boolean") {
                    value = $input.is(":checked");
                }

                var tag = new Core.Tag();
                tag.name = name;
                tag.kind = kind;
                tag.value = value;

                // add the tag
                attributeEle.ownedElements.push(tag);
            }

            // auto-update the documentation, if checked
            var $input_autoDocument = $(input_autoDocument_id);
            if ($input_autoDocument.is(":checked")) {
                updateAttributeDocumentation(attributeEle);
            }
        } catch (err) {
            console.error(err);
        }
    };

    AppInit.htmlReady(function () {
        $view = $(viewTemplate);

        $view.on("change", ".sitecore-field-attribute", function() {
            var $this = $(this);
            // intentionally using attr to avoid caching
            var name = $this.attr("data-name");
            _handleViewChangeForInput($this, _attributeElement, name);
        });

        EditorView.setupEditorView($view);
        show();

        _initializeEventHandlers();
    });

    exports.show = show;
    exports.fieldAttributes = fieldAttributes;
    exports.updateAttributeDocumentation = updateAttributeDocumentation;
    exports.createAttributeDocumentation = createAttributeDocumentation;
});

<|endoftext|>