<commit_before>/*
*
* @author Robert Haritonov (http://rhr.me)
*
* */

define([
    'jquery',
    'modules/module',
    'modules/utils',
    'modules/parseFileTree'
    ], function($, module, utils, parseFileTree) {

    function GlobalNav() {
        var _this = this;

        this.options.modulesOptions.globalNav = $.extend(true, {
            CATALOG : 'source_catalog',
            CATALOG_LIST : 'source_catalog_list',
            CATALOG_LIST_I : 'source_catalog_list_i',
                CATALOG_LIST_I_PREVIEW_NAME : 'thumbnail.png',
            CATALOG_LIST_ALL : 'source_catalog_all',
                CATALOG_LIST_ALL_A : 'source_a_bl',

            CATALOG_IMG_TUMBLER: 'catalog-image-tumbler',

            CATALOG_LIST_A : 'source_catalog_a source_a_g',
            CATALOG_LIST_A_IMG : 'source_catalog_img',
            CATALOG_LIST_A_TX : 'source_catalog_title',
            CATALOG_LIST_DATE : 'source_catalog_footer',
            CATALOG_LIST_BUBBLES : 'source_bubble',

            RES_LINK_TO_ALL : 'All',
            RES_AUTHOR : 'Author',
            RES_NO_DATA_ATTR : 'Data-nav attr not set',
            RES_NO_CATALOG : 'Specified catalog is empty or does not exist',
            RES_NO_CATALOG_INFO : 'Specified catalog does not have data about it',

            pageLimit : 999
        }, this.options.modulesOptions.globalNav);

        $(function(){
            _this.init();
        });
    }

    GlobalNav.prototype = module.createInstance();
    GlobalNav.prototype.constructor = GlobalNav;

    GlobalNav.prototype.init = function () {
        this.drawNavigation();
        this.drawToggler();
        this.hideImgWithError();
    };

    //Drawing navigation and page info in each catalog defined on page
    GlobalNav.prototype.drawNavigation = function () {
        var _this = this,
            L_CATALOG = $('.' + this.options.modulesOptions.globalNav.CATALOG),
            CATALOG_LIST = this.options.modulesOptions.globalNav.CATALOG_LIST,
            CATALOG_LIST_I = this.options.modulesOptions.globalNav.CATALOG_LIST_I,
                CATALOG_LIST_I_PREVIEW_NAME = this.options.modulesOptions.globalNav.CATALOG_LIST_I_PREVIEW_NAME,

            CATALOG_LIST_ALL = this.options.modulesOptions.globalNav.CATALOG_LIST_ALL,
                CATALOG_LIST_ALL_A = this.options.modulesOptions.globalNav.CATALOG_LIST_ALL_A,

            CATALOG_LIST_A = this.options.modulesOptions.globalNav.CATALOG_LIST_A,
                CATALOG_LIST_A_IMG = this.options.modulesOptions.globalNav.CATALOG_LIST_A_IMG,
                CATALOG_LIST_A_TX = this.options.modulesOptions.globalNav.CATALOG_LIST_A_TX,

            CATALOG_LIST_DATE = this.options.modulesOptions.globalNav.CATALOG_LIST_DATE,
            CATALOG_LIST_BUBBLES = this.options.modulesOptions.globalNav.CATALOG_LIST_BUBBLES,
            RES_LINK_TO_ALL = this.options.modulesOptions.globalNav.RES_LINK_TO_ALL,
            RES_AUTHOR = this.options.modulesOptions.globalNav.RES_AUTHOR,
            RES_NO_DATA_ATTR = this.options.modulesOptions.globalNav.RES_NO_DATA_ATTR,
            RES_NO_CATALOG = this.options.modulesOptions.globalNav.RES_NO_CATALOG,
            RES_NO_CATALOG_INFO = this.options.modulesOptions.globalNav.RES_NO_CATALOG_INFO,

            pageLimit = this.options.modulesOptions.globalNav.pageLimit;
            sortType = this.options.modulesOptions.globalNav.sortType || 'sortByDate';
            ignorePages = this.options.modulesOptions.globalNav.ignorePages || [];

        //TODO: refactor this module and write tests
        L_CATALOG.each(function () {
            var sourceCat = $(this),
                navListDir = sourceCat.attr('data-nav'),
                navListCat = sourceCat.attr('data-cat'),
                specifCatAndDirDefined = typeof navListDir !== 'undefined' && typeof navListCat !== 'undefined';

            //Filtering by specified catalogue
            var skipSpec = function(currentObj){
                var obj = currentObj,
                    response = true; // skip by default

                //obj['cat'] is an array
                //if cat has needed value
                if (typeof obj['cat'] !== 'undefined' && obj['cat'].indexOf(navListCat) > -1) {
                    response = false;

                //without-cat mode, showing all specs without cat field in info.json defined or
                } else if ( navListCat === 'without-cat' && (typeof obj['cat'] === 'undefined' || obj['cat'].length === 0) ) {

                    response = false;
                }

                return response;
            };

            //Filtering hidden specs
            var isHidden = function(currentObj){
                var obj = currentObj,
                    response = false; // skip by default

                //obj['cat'] is an array
                if (typeof obj['cat'] !== 'undefined' && obj['cat'].indexOf("hidden") > -1 ) {
                    response = true;
                }

                return response;
            };

            if ( (navListDir !== undefined) && (navListDir != '') ) { //Catalog has data about category

                var targetCat = parseFileTree.getCatAll(navListDir),
                	catObj;

				if (targetCat === undefined) return;

				if ( !sourceCat.find('.source_catalog_list').length ) {
					sourceCat.append('

');
				}

                //Looking for catalogue info
				if (typeof targetCat[ navListDir + '/specFile' ] === 'object') {
					catObj = targetCat[ navListDir + '/specFile' ];
				} else if ( typeof targetCat[ 'specFile' ] === 'object' ) {
					if (!!targetCat[ 'specFile' ][ 'specFile' ]) {
						catObj = targetCat[ 'specFile' ][ 'specFile' ];
					} else {
						catObj = targetCat[ 'specFile' ];
					}
				}

				if (typeof catObj === 'object' && !specifCatAndDirDefined) {

					if ( (!sourceCat.find('.source_catalog_title').length) && (catObj.title !== undefined) ) {
						sourceCat.prepend('
' + catObj.title + '
')
					}

					if ( (!sourceCat.find('.source_catalog_tx').length) && (catObj.info !== undefined) && ( $.trim(catObj.info) !== '' )) {
						sourceCat
							.children('.source_catalog_title')
							.first()
								.after('
' + catObj.info + '
')
					}

				} else {
					console.log(RES_NO_CATALOG_INFO);
				}

				var L_CATALOG_LIST = sourceCat.find('.' + CATALOG_LIST);

                // cast Object to Array of objects
                if (typeof targetCat === 'object'){
                    var targetCatArray = $.map(targetCat, function(k, v) {
                        if(typeof k['specFile'] === 'object') {
                            return [k];
                        }
                    });

                    // sort
                    targetCatArray.sort(function(a, b){
                    	if (sortType == 'sortByDate') {
                    		return _this.sortByDate(a, b)
                    	} else if (sortType == 'sortByAlpha') {
                    		return _this.sortByAlpha(a, b);
                    	} else {
							return _this.sortByDate(a, b)
									|| _this.sortByAlpha(a, b);
                    	}
                    });
                }

                //Collecting nav tree
                if (L_CATALOG_LIST.length === 1 && targetCatArray != undefined) {

                    var navTreeHTML = '',
                        authorName = '';

                    //Building navigation HTML
                    var addNavPosition = function (target) {

                        if (typeof target.author === 'undefined') {
                            authorName = '';
                        } else {
                            authorName = ' | ' + RES_AUTHOR + ': ' + target.author + '';
                        }

                        //fixing relative path due to server settings
                        var targetUrl = target.url;
                        if(targetUrl.charAt(0) !== '/')
                            targetUrl = '/' + targetUrl;

                        navTreeHTML += '' +
                                '
' +
                                '' +
                                '' +
                                '' + target.title + '' +
                                '
' + target.lastmod + authorName + '
';

                        // TODO: move to plugins
                        if(parseInt(target.bubbles)) {
                            navTreeHTML +=
                            '
' + target.bubbles + '
';
                        }

                        navTreeHTML +=
                                '' +
                                '
';

                    };

                    var navListItems = (pageLimit > targetCatArray.length)
                            ? targetCatArray.length
                            : pageLimit;

                    for (var j = 0; j < navListItems; j++) {
                        var targetPage = targetCatArray[j]['specFile'];

                        //Ignore page list
                        if ( $.inArray(targetPage.title, ignorePages) !== -1 ) {
                        	continue;
                        }

                        //Undefined title
                        if (targetPage === undefined || targetPage.title === undefined) {
                        	continue;
                        }

                        //Skip spec if we're filtering it by specific cat
                        if (specifCatAndDirDefined && skipSpec(targetCatArray[j]['specFile']) || isHidden(targetCatArray[j]['specFile']) ) {
                            continue; //skip
                        }

                        addNavPosition(targetPage);
                    }

                    //Injecting nav tree
                    L_CATALOG_LIST.html(navTreeHTML);

                    //Go to cat page link
                    if (targetCatArray.length > navListItems) {
                        L_CATALOG_LIST.append(
                            '
' +
                                ''+ RES_LINK_TO_ALL + ' ' + targetCatArray.length + '' +
                            '
');
                    }

                }

                if (targetCat === undefined) {
                    L_CATALOG_LIST.html(RES_NO_CATALOG);
                }

            } else {

            	if (navListDir !== undefined) {
					//Display error
					L_CATALOG_LIST.html(RES_NO_DATA_ATTR);
            	}
            }

        });
    };

    GlobalNav.prototype.drawToggler = function(){
        var _this = this,
            L_CATALOG = $('.' + _this.options.modulesOptions.globalNav.CATALOG),
            CATALOG_IMG_TUMBLER = _this.options.modulesOptions.globalNav.CATALOG_IMG_TUMBLER;

        L_CATALOG.filter('[data-nav*="base"],[data-nav*="project"]').each(function(){

            /* for each type of data-nav own localStorage */
            var _tumblerMode = $(this).attr('data-nav').substr(1),
                tumblerMode = localStorage.getItem( _tumblerMode + 'TumblerMode');

            if ( tumblerMode && tumblerMode == 'showPreview' ) {

                $(this)
                    .addClass('__show-preview')
                    .prepend('Скрыть превьюшки');

            } else {

                $(this).prepend('Показать превьюшки');
            }

        });

        $(document).on('click', '.' + CATALOG_IMG_TUMBLER, function(e) {
            e.preventDefault();

            var $this = $(this),
                tumblerText = $this.text(),
                _tumblerMode = $this.parent().attr('data-nav').substr(1);

            if ( tumblerText == 'Показать превьюшки' ) {
                tumblerText = 'Скрыть превьюшки';
                localStorage.setItem( _tumblerMode + "TumblerMode", "showPreview");
            } else {
                tumblerText = 'Показать превьюшки';
                localStorage.setItem( _tumblerMode + "TumblerMode", "hidePreview");
            }

            $this
                .text(tumblerText)
                .parent().toggleClass('__show-preview');

        });
    };

    GlobalNav.prototype.hideImgWithError = function(){
        var CATALOG_LIST_A_IMG = this.options.modulesOptions.globalNav.CATALOG_LIST_A_IMG;

        //check valid all img
        $('.' + CATALOG_LIST_A_IMG).each(function(){
            this.onerror = function(){
                $(this).remove();
            };
        });
    };

    GlobalNav.prototype.sortByDate = function (a, b) {
        a = parseInt(a['specFile'].lastmodSec);
        b = parseInt(b['specFile'].lastmodSec);

        if(a == b) return 0;
        else {
            return (a > b) ? -1 : 1;
        }
    };

    GlobalNav.prototype.sortByAlpha = function (a, b) {
        a = a['specFile'].title.replace(/(^\s+|\s+$)/g,'');
        b = b['specFile'].title.replace(/(^\s+|\s+$)/g,'');

        if(a == b) return 0;
        else {
            return (a > b) ? 1 : -1;
        }
    };

    return new GlobalNav();

});<commit_msg>show preview for /base by default<commit_after>/*
*
* @author Robert Haritonov (http://rhr.me)
*
* */

define([
    'jquery',
    'modules/module',
    'modules/utils',
    'modules/parseFileTree'
    ], function($, module, utils, parseFileTree) {

    function GlobalNav() {
        var _this = this;

        this.options.modulesOptions.globalNav = $.extend(true, {
            CATALOG : 'source_catalog',
            CATALOG_LIST : 'source_catalog_list',
            CATALOG_LIST_I : 'source_catalog_list_i',
                CATALOG_LIST_I_PREVIEW_NAME : 'thumbnail.png',
            CATALOG_LIST_ALL : 'source_catalog_all',
                CATALOG_LIST_ALL_A : 'source_a_bl',

            CATALOG_IMG_TUMBLER: 'catalog-image-tumbler',

            CATALOG_LIST_A : 'source_catalog_a source_a_g',
            CATALOG_LIST_A_IMG : 'source_catalog_img',
            CATALOG_LIST_A_TX : 'source_catalog_title',
            CATALOG_LIST_DATE : 'source_catalog_footer',
            CATALOG_LIST_BUBBLES : 'source_bubble',

            RES_LINK_TO_ALL : 'All',
            RES_AUTHOR : 'Author',
            RES_NO_DATA_ATTR : 'Data-nav attr not set',
            RES_NO_CATALOG : 'Specified catalog is empty or does not exist',
            RES_NO_CATALOG_INFO : 'Specified catalog does not have data about it',

            pageLimit : 999
        }, this.options.modulesOptions.globalNav);

        $(function(){
            _this.init();
        });
    }

    GlobalNav.prototype = module.createInstance();
    GlobalNav.prototype.constructor = GlobalNav;

    GlobalNav.prototype.init = function () {
        this.drawNavigation();
        this.drawToggler();
        this.hideImgWithError();
    };

    //Drawing navigation and page info in each catalog defined on page
    GlobalNav.prototype.drawNavigation = function () {
        var _this = this,
            L_CATALOG = $('.' + this.options.modulesOptions.globalNav.CATALOG),
            CATALOG_LIST = this.options.modulesOptions.globalNav.CATALOG_LIST,
            CATALOG_LIST_I = this.options.modulesOptions.globalNav.CATALOG_LIST_I,
                CATALOG_LIST_I_PREVIEW_NAME = this.options.modulesOptions.globalNav.CATALOG_LIST_I_PREVIEW_NAME,

            CATALOG_LIST_ALL = this.options.modulesOptions.globalNav.CATALOG_LIST_ALL,
                CATALOG_LIST_ALL_A = this.options.modulesOptions.globalNav.CATALOG_LIST_ALL_A,

            CATALOG_LIST_A = this.options.modulesOptions.globalNav.CATALOG_LIST_A,
                CATALOG_LIST_A_IMG = this.options.modulesOptions.globalNav.CATALOG_LIST_A_IMG,
                CATALOG_LIST_A_TX = this.options.modulesOptions.globalNav.CATALOG_LIST_A_TX,

            CATALOG_LIST_DATE = this.options.modulesOptions.globalNav.CATALOG_LIST_DATE,
            CATALOG_LIST_BUBBLES = this.options.modulesOptions.globalNav.CATALOG_LIST_BUBBLES,
            RES_LINK_TO_ALL = this.options.modulesOptions.globalNav.RES_LINK_TO_ALL,
            RES_AUTHOR = this.options.modulesOptions.globalNav.RES_AUTHOR,
            RES_NO_DATA_ATTR = this.options.modulesOptions.globalNav.RES_NO_DATA_ATTR,
            RES_NO_CATALOG = this.options.modulesOptions.globalNav.RES_NO_CATALOG,
            RES_NO_CATALOG_INFO = this.options.modulesOptions.globalNav.RES_NO_CATALOG_INFO,

            pageLimit = this.options.modulesOptions.globalNav.pageLimit;
            sortType = this.options.modulesOptions.globalNav.sortType || 'sortByDate';
            ignorePages = this.options.modulesOptions.globalNav.ignorePages || [];

        //TODO: refactor this module and write tests
        L_CATALOG.each(function () {
            var sourceCat = $(this),
                navListDir = sourceCat.attr('data-nav'),
                navListCat = sourceCat.attr('data-cat'),
                specifCatAndDirDefined = typeof navListDir !== 'undefined' && typeof navListCat !== 'undefined';

            //Filtering by specified catalogue
            var skipSpec = function(currentObj){
                var obj = currentObj,
                    response = true; // skip by default

                //obj['cat'] is an array
                //if cat has needed value
                if (typeof obj['cat'] !== 'undefined' && obj['cat'].indexOf(navListCat) > -1) {
                    response = false;

                //without-cat mode, showing all specs without cat field in info.json defined or
                } else if ( navListCat === 'without-cat' && (typeof obj['cat'] === 'undefined' || obj['cat'].length === 0) ) {

                    response = false;
                }

                return response;
            };

            //Filtering hidden specs
            var isHidden = function(currentObj){
                var obj = currentObj,
                    response = false; // skip by default

                //obj['cat'] is an array
                if (typeof obj['cat'] !== 'undefined' && obj['cat'].indexOf("hidden") > -1 ) {
                    response = true;
                }

                return response;
            };

            if ( (navListDir !== undefined) && (navListDir != '') ) { //Catalog has data about category

                var targetCat = parseFileTree.getCatAll(navListDir),
                	catObj;

				if (targetCat === undefined) return;

				if ( !sourceCat.find('.source_catalog_list').length ) {
					sourceCat.append('

');
				}

                //Looking for catalogue info
				if (typeof targetCat[ navListDir + '/specFile' ] === 'object') {
					catObj = targetCat[ navListDir + '/specFile' ];
				} else if ( typeof targetCat[ 'specFile' ] === 'object' ) {
					if (!!targetCat[ 'specFile' ][ 'specFile' ]) {
						catObj = targetCat[ 'specFile' ][ 'specFile' ];
					} else {
						catObj = targetCat[ 'specFile' ];
					}
				}

				if (typeof catObj === 'object' && !specifCatAndDirDefined) {

					if ( (!sourceCat.find('.source_catalog_title').length) && (catObj.title !== undefined) ) {
						sourceCat.prepend('
' + catObj.title + '
')
					}

					if ( (!sourceCat.find('.source_catalog_tx').length) && (catObj.info !== undefined) && ( $.trim(catObj.info) !== '' )) {
						sourceCat
							.children('.source_catalog_title')
							.first()
								.after('
' + catObj.info + '
')
					}

				} else {
					console.log(RES_NO_CATALOG_INFO);
				}

				var L_CATALOG_LIST = sourceCat.find('.' + CATALOG_LIST);

                // cast Object to Array of objects
                if (typeof targetCat === 'object'){
                    var targetCatArray = $.map(targetCat, function(k, v) {
                        if(typeof k['specFile'] === 'object') {
                            return [k];
                        }
                    });

                    // sort
                    targetCatArray.sort(function(a, b){
                    	if (sortType == 'sortByDate') {
                    		return _this.sortByDate(a, b)
                    	} else if (sortType == 'sortByAlpha') {
                    		return _this.sortByAlpha(a, b);
                    	} else {
							return _this.sortByDate(a, b)
									|| _this.sortByAlpha(a, b);
                    	}
                    });
                }

                //Collecting nav tree
                if (L_CATALOG_LIST.length === 1 && targetCatArray != undefined) {

                    var navTreeHTML = '',
                        authorName = '';

                    //Building navigation HTML
                    var addNavPosition = function (target) {

                        if (typeof target.author === 'undefined') {
                            authorName = '';
                        } else {
                            authorName = ' | ' + RES_AUTHOR + ': ' + target.author + '';
                        }

                        //fixing relative path due to server settings
                        var targetUrl = target.url;
                        if(targetUrl.charAt(0) !== '/')
                            targetUrl = '/' + targetUrl;

                        navTreeHTML += '' +
                                '
' +
                                '' +
                                '' +
                                '' + target.title + '' +
                                '
' + target.lastmod + authorName + '
';

                        // TODO: move to plugins
                        if(parseInt(target.bubbles)) {
                            navTreeHTML +=
                            '
' + target.bubbles + '
';
                        }

                        navTreeHTML +=
                                '' +
                                '
';

                    };

                    var navListItems = (pageLimit > targetCatArray.length)
                            ? targetCatArray.length
                            : pageLimit;

                    for (var j = 0; j < navListItems; j++) {
                        var targetPage = targetCatArray[j]['specFile'];

                        //Ignore page list
                        if ( $.inArray(targetPage.title, ignorePages) !== -1 ) {
                        	continue;
                        }

                        //Undefined title
                        if (targetPage === undefined || targetPage.title === undefined) {
                        	continue;
                        }

                        //Skip spec if we're filtering it by specific cat
                        if (specifCatAndDirDefined && skipSpec(targetCatArray[j]['specFile']) || isHidden(targetCatArray[j]['specFile']) ) {
                            continue; //skip
                        }

                        addNavPosition(targetPage);
                    }

                    //Injecting nav tree
                    L_CATALOG_LIST.html(navTreeHTML);

                    //Go to cat page link
                    if (targetCatArray.length > navListItems) {
                        L_CATALOG_LIST.append(
                            '
' +
                                ''+ RES_LINK_TO_ALL + ' ' + targetCatArray.length + '' +
                            '
');
                    }

                }

                if (targetCat === undefined) {
                    L_CATALOG_LIST.html(RES_NO_CATALOG);
                }

            } else {

            	if (navListDir !== undefined) {
					//Display error
					L_CATALOG_LIST.html(RES_NO_DATA_ATTR);
            	}
            }

        });
    };

    GlobalNav.prototype.drawToggler = function(){
        var _this = this,
            L_CATALOG = $('.' + _this.options.modulesOptions.globalNav.CATALOG),
            CATALOG_IMG_TUMBLER = _this.options.modulesOptions.globalNav.CATALOG_IMG_TUMBLER;

        L_CATALOG.filter('[data-nav*="base"],[data-nav*="project"]').each(function(){

            var $this = $(this),
                /* for each type of data-nav own localStorage */
                _tumblerMode = $this.attr('data-nav').substr(1),
                tumblerMode = localStorage.getItem( _tumblerMode + 'TumblerMode');

            if ( tumblerMode && tumblerMode == 'showPreview' ) {

                $this
                    .addClass('__show-preview')
                    .prepend('Скрыть превьюшки');

            } else if (!tumblerMode && _tumblerMode == 'base' ) {

                // for base spec show preview by default
                $this
                    .addClass('__show-preview')
                    .prepend('Скрыть превьюшки');

            } else {

                $this.prepend('Показать превьюшки');
            }

        });

        $(document).on('click', '.' + CATALOG_IMG_TUMBLER, function(e) {
            e.preventDefault();

            var $this = $(this),
                tumblerText = $this.text(),
                _tumblerMode = $this.parent().attr('data-nav').substr(1);

            if ( tumblerText == 'Показать превьюшки' ) {
                tumblerText = 'Скрыть превьюшки';
                localStorage.setItem( _tumblerMode + "TumblerMode", "showPreview");
            } else {
                tumblerText = 'Показать превьюшки';
                localStorage.setItem( _tumblerMode + "TumblerMode", "hidePreview");
            }

            $this
                .text(tumblerText)
                .parent().toggleClass('__show-preview');

        });
    };

    GlobalNav.prototype.hideImgWithError = function(){
        var CATALOG_LIST_A_IMG = this.options.modulesOptions.globalNav.CATALOG_LIST_A_IMG;

        //check valid all img
        $('.' + CATALOG_LIST_A_IMG).each(function(){
            this.onerror = function(){
                $(this).remove();
            };
        });
    };

    GlobalNav.prototype.sortByDate = function (a, b) {
        a = parseInt(a['specFile'].lastmodSec);
        b = parseInt(b['specFile'].lastmodSec);

        if(a == b) return 0;
        else {
            return (a > b) ? -1 : 1;
        }
    };

    GlobalNav.prototype.sortByAlpha = function (a, b) {
        a = a['specFile'].title.replace(/(^\s+|\s+$)/g,'');
        b = b['specFile'].title.replace(/(^\s+|\s+$)/g,'');

        if(a == b) return 0;
        else {
            return (a > b) ? 1 : -1;
        }
    };

    return new GlobalNav();

});<|endoftext|>


<commit_before>// If you want to create a new button you have to add some data (strings) to the following five arrays.
// Make sure that you add your data at the same position in each array.
// The buttons will be generated in order to the array's index. e.g. data at array's index '0' will generate the first button.

// enter the name of your module here
var moduleNames = new Array("Colormap",
                            "T1 Image",
                            "3D Background",
                            "Cingulum",
                            "Corpus Callosum",
                            "Corticospinal Tract",
                            "Fornix",
                            "ILF, IFO, Uncus",
                            "SLF, SOFF, Arcuate",
                            "ICP, MCP, SCP, ML",
                            "Download MITK");

// add the MITK-link to your module
var moduleLinks = new Array("mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/0bref_colormap.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/0cref_t1.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/0aref_alltracts.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/01CING.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/02CORPUS.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/03CST.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/04FORNIX.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/05ILF+IFO+UNCUS.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Adriane/06SLF+SOFF+ARCUATE.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=/opt/dti-atlas/SCENE-FILES/Patient1/07PEDUNCLES.mitk",
                            "http://www.mitk.org");

// add the filename of your icon for the module. Place the picture in subdirectory "pics".
// The picture's width should be 136 pixel; the height 123 pixel.
var picFilenames = new Array("0bref_colormap.png",
                             "0cref_t1.png",
                             "0aref_alltracts.png",
                             "01CING.png",
                             "02CORPUS.png",
                             "03CST.png",
                             "04FORNIX.png",
                             "05ILF+IFO+UNCUS.png",
                             "06SLF+SOFF+ARCUATE.png",
                             "07PEDUNCLES.png",
                             "button_mitk.png");

// if you want to create an animated icon, add the name of your animated gif (placed in subdirectory "pics"). Otherwise enter an empty string "".
// The animation's width should be 136 pixel; the height 123 pixel.
var aniFilenames = new Array("0bref_colormap.gif",
                             "0cref_t1.gif",
                             "0aaref_alltracts.png",
                             "01aCING.png",
                             "02aCORPUS.png",
                             "03aCST.png",
                             "04aFORNIX.png",
                             "05aILF+IFO+UNCUS.png",
                             "06aSLF+SOFF+ARCUATE.png",
                             "07aPEDUNCLES.png",
                             "button_mitka.png");

// if your module is not stable, you can mark it as experimental.
// just set true for experimental or false for stable.
var experimental = new Array(false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false);

// add the description for your module. The description is displayed in a PopUp-window.
var moduleDescriptions = new Array("This colormap represents the original diffusion acquisition that was used as input for tractography.",
                            "This T1-weighted image was aquired during the same imaging session as the diffusion image. It is roughly aligned with the diffusion image and provides additional, complementary information.",
                            "This dataset contains all fibers that were found by the global tractography approach. It can serve as a background for better orientation in the 3D view.",
                            "This dataset contains the Cingulum fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Corpus Callosum fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Corticospinal Tract fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Fornix fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Inferior Longitudinal Fasciculus, Inferior Fronto-Occipital, and the Uncus fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Superior Longitudinal Fasciculus, Superior OFF, and Arcuate fibers and most important regions of interest that were used to extract it.",
                            "This dataset is not in the same world coordinate system as the others and should not be opend in combination with any of the other datasets. It contains a 3D visualization of the cerebellum and the Inferior Cerebral Peduncles, Medial Cerebral Peduncle, Superior Cerebral Peduncles, and Medial Limnisci fibers and the and most important regions of interest that were used to extract it.",
                            "Download MITK");

var bttns = new Array();

var d = document, da = d.all;

// holds id of current mouseover-HTML-element
var currentTarget;

// get the id of current mouseover-HTML-element
d.onmouseover = function(o){
  var e = da ? event.srcElement : o.target;
  currentTarget = e.id;
}

// build-function called by onload-event in HTML-document
function createButtons(){

  for (i=0; i < moduleNames.length; i++){
    bttns[i] = new Button(moduleNames[i],moduleLinks[i], picFilenames[i], aniFilenames[i],moduleDescriptions[i]);
    bttns[i].createButton();
  }

  for (i=0; i < moduleNames.length; i++){

    if(experimental[i]){
      setExperimental(i);
    }
  }

  createClearFloat();
}

// Class Button
function Button(moduleName, moduleLink, picFilename, aniFilename, moduleDescr){

  // Properties
  this.bttnID = "bttn" + moduleName;
  this.modName = moduleName;
  this.modLink = moduleLink;
  this.picPath = "pics/" + picFilename;
  this.aniPath = "pics/" + aniFilename;
  this.modDescr = moduleDescr;

  // Methods
  this.createButton = function(){

    // get DIV-wrapper for Button and append it to HTML-document
    bttnWrapper = this.createWrapper();
    document.getElementById("bttnField").appendChild(bttnWrapper);

    // get link-element for picture and append it to DIV-wrapper
    bttnPicLink = this.createPicLink();
    bttnWrapper.appendChild(bttnPicLink);

    // set HTML attributes for button-element
    bttn = document.createElement("img");
    bttn.src = this.picPath;
    bttn.id = this.bttnID;
    bttn.className = "modBttn";
    bttn.height = 123;
    bttn.width = 136;
    bttn.onmouseover = function(){startAni(this.id);};
    bttn.onmouseout = function(){stopAni(this.id);};

    // append button to link-element
    bttnPicLink.appendChild(bttn);

    // create text-link and add it to DIV-wrapper
    bttnTxtLink = document.createElement("a");
    bttnTxtLink.href = this.modLink;
    bttnTxtLink.className = "txtLink";
    bttnTxtLink.appendChild(document.createTextNode(this.modName));
    bttnWrapper.appendChild(bttnTxtLink);

    // create pop-up link for module description
    bttnPopUpLink = document.createElement("a");
    modName = this.modName;
    modDescr = this.modDescr;
    bttnPopUpLink.onclick = function(){showPopUpWindow();};
    bttnPopUpLink.className = "popUpLink";
    bttnPopUpLink.id = "popup" + this.modName;
    bttnPopUpLink.appendChild(document.createTextNode("more info >>"));
    bttnWrapper.appendChild(document.createElement("br"));
    bttnWrapper.appendChild(bttnPopUpLink);

    return bttn;
  }

  this.createWrapper = function(){
    bttnWrapper = document.createElement("div");
    bttnWrapper.id = "wrapper" + this.modName;
    bttnWrapper.className = "bttnWrap";

    return bttnWrapper;
  }

  this.createPicLink = function(){
    picLink = document.createElement("a");
    picLink.href = this.modLink;
    picLink.id = "link" + this.modName;

    return picLink;
  }

}

function showPopUpWindow(){

  // modules position in array?
  modulePos = getPos(currentTarget,"popup");

  // get reference to anchor-element in HTML-document
  popUpAnchor = document.getElementById("popupAnchor");

  // check if a popUp is open
  if(popUpAnchor.hasChildNodes()){
    // if a popUp is open, remove it!
    popUpAnchor.removeChild(document.getElementById("popup"));
  }

  // create new container for popUp
  container = document.createElement("div");
  container.id = "popup";
  container.align = "right";

  // append popUp-container to HTML-document
  popUpAnchor.appendChild(container);

  // create close-button and append it to popUp-container
  bttnClose = document.createElement("img");
  bttnClose.src = "pics/popup_bttn_close.png";
  bttnClose.id = "bttnClose";
  bttnClose.onclick = function(){closeInfoWindow();};
  container.appendChild(bttnClose);

  // create container for content-elements
  contHeadline = document.createElement("div");
  contHeadline.id = "contHeadline";
  contDescription = document.createElement("div");
  contDescription.id = "contDescription";
  contModLink = document.createElement("div");
  contModLink.id = "contModLink";

  // append content-container to popUp-container
  container.appendChild(contHeadline);
  container.appendChild(contDescription);
  container.appendChild(contModLink);

  // create text-elements with content
  headline = document.createTextNode(moduleNames[modulePos] + " ");
  description = document.createTextNode(moduleDescriptions[modulePos]);
  moduleLink = document.createElement("a");
  moduleLink.href = moduleLinks[modulePos] ;
  moduleLink.className = 'moduleLink';
  moduleLinkTxt = document.createTextNode("Click here to open the " + moduleNames[modulePos].toLowerCase() + " dataset");
  moduleLink.appendChild(moduleLinkTxt);

  // append text-elements to their container
  contHeadline.appendChild(headline);
  contDescription.appendChild(description);
  contModLink.appendChild(moduleLink);
}

function getPos(id,prefix){

  if(prefix == "popup"){
    targetID = id.slice(5);
  }else{
    if(prefix == "bttn"){
      targetID = id.slice(4);
    }
  }

  for(i=0; i < moduleNames.length; i++ ){
    if(moduleNames[i] == targetID){
      return i;
    }
  }
}

function setExperimental(modPos){
  linkID = "link" + moduleNames[modPos];

  expPic = document.createElement("img");
  expPic.src = "pics/experimental.png";
  expPic.className = "expPic";
  //alert(bttns[modPos].bttnID);
  expPic.onmouseover = function(){startAni(bttns[modPos].bttnID);changeToHover(bttns[modPos].bttnID);};
  expPic.onmouseout = function(){stopAni(bttns[modPos].bttnID);changeToNormal(bttns[modPos].bttnID);};

  document.getElementById(linkID).appendChild(expPic);
}

function changeToHover(targetId){
  bttn = document.getElementById(targetId);
  bttn.className = "modBttnHover";
}

function changeToNormal(targetId){
  bttn = document.getElementById(targetId);
  bttn.className = "modBttn";
}

// function to close PopUp-window
function closeInfoWindow(){
  popUpAnchor = document.getElementById("popupAnchor");
  popUpAnchor.removeChild(document.getElementById("popup"));
}

function createClearFloat(){
  cf = document.createElement("div");
  cf.className = "clearfloat";
  document.getElementById("bttnField").appendChild(cf);
}

startAni = function(targetId){
  modulePos = getPos(targetId,"bttn");

  if(aniFilenames[modulePos] != ''){
    bttn = document.getElementById(targetId);
    bttn.src = "pics/" + aniFilenames[modulePos];
  }
}

stopAni = function(targetId){
  modulePos = getPos(targetId,"bttn");

  bttn = document.getElementById(targetId);
  bttn.src = "pics/" + picFilenames[modulePos];
}

<commit_msg>corrected paths for *.mitk files<commit_after>// If you want to create a new button you have to add some data (strings) to the following five arrays.
// Make sure that you add your data at the same position in each array.
// The buttons will be generated in order to the array's index. e.g. data at array's index '0' will generate the first button.

// enter the name of your module here
var moduleNames = new Array("Colormap",
                            "T1 Image",
                            "3D Background",
                            "Cingulum",
                            "Corpus Callosum",
                            "Corticospinal Tract",
                            "Fornix",
                            "ILF, IFO, Uncus",
                            "SLF, SOFF, Arcuate",
                            "ICP, MCP, SCP, ML",
                            "Download MITK");

// add the MITK-link to your module
var moduleLinks = new Array("mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/0bref_colormap.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/0cref_t1.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/0aref_alltracts.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/01CING.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/02CORPUS.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/03CST.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/04FORNIX.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/05ILF+IFO+UNCUS.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/06SLF+SOFF+ARCUATE.mitk",
                            "mitk://mitk.perspectives/org.mitk.diffusionimagingapp.perspectives.diffusionimagingapp?dataset=./atlas-data/07PEDUNCLES.mitk",
                            "http://www.mitk.org");

// add the filename of your icon for the module. Place the picture in subdirectory "pics".
// The picture's width should be 136 pixel; the height 123 pixel.
var picFilenames = new Array("0bref_colormap.png",
                             "0cref_t1.png",
                             "0aref_alltracts.png",
                             "01CING.png",
                             "02CORPUS.png",
                             "03CST.png",
                             "04FORNIX.png",
                             "05ILF+IFO+UNCUS.png",
                             "06SLF+SOFF+ARCUATE.png",
                             "07PEDUNCLES.png",
                             "button_mitk.png");

// if you want to create an animated icon, add the name of your animated gif (placed in subdirectory "pics"). Otherwise enter an empty string "".
// The animation's width should be 136 pixel; the height 123 pixel.
var aniFilenames = new Array("0bref_colormap.gif",
                             "0cref_t1.gif",
                             "0aaref_alltracts.png",
                             "01aCING.png",
                             "02aCORPUS.png",
                             "03aCST.png",
                             "04aFORNIX.png",
                             "05aILF+IFO+UNCUS.png",
                             "06aSLF+SOFF+ARCUATE.png",
                             "07aPEDUNCLES.png",
                             "button_mitka.png");

// if your module is not stable, you can mark it as experimental.
// just set true for experimental or false for stable.
var experimental = new Array(false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false,
                             false);

// add the description for your module. The description is displayed in a PopUp-window.
var moduleDescriptions = new Array("This colormap represents the original diffusion acquisition that was used as input for tractography.",
                            "This T1-weighted image was aquired during the same imaging session as the diffusion image. It is roughly aligned with the diffusion image and provides additional, complementary information.",
                            "This dataset contains all fibers that were found by the global tractography approach. It can serve as a background for better orientation in the 3D view.",
                            "This dataset contains the Cingulum fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Corpus Callosum fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Corticospinal Tract fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Fornix fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Inferior Longitudinal Fasciculus, Inferior Fronto-Occipital, and the Uncus fibers and most important regions of interest that were used to extract it.",
                            "This dataset contains the Superior Longitudinal Fasciculus, Superior OFF, and Arcuate fibers and most important regions of interest that were used to extract it.",
                            "This dataset is not in the same world coordinate system as the others and should not be opend in combination with any of the other datasets. It contains a 3D visualization of the cerebellum and the Inferior Cerebral Peduncles, Medial Cerebral Peduncle, Superior Cerebral Peduncles, and Medial Limnisci fibers and the and most important regions of interest that were used to extract it.",
                            "Download MITK");

var bttns = new Array();

var d = document, da = d.all;

// holds id of current mouseover-HTML-element
var currentTarget;

// get the id of current mouseover-HTML-element
d.onmouseover = function(o){
  var e = da ? event.srcElement : o.target;
  currentTarget = e.id;
}

// build-function called by onload-event in HTML-document
function createButtons(){

  for (i=0; i < moduleNames.length; i++){
    bttns[i] = new Button(moduleNames[i],moduleLinks[i], picFilenames[i], aniFilenames[i],moduleDescriptions[i]);
    bttns[i].createButton();
  }

  for (i=0; i < moduleNames.length; i++){

    if(experimental[i]){
      setExperimental(i);
    }
  }

  createClearFloat();
}

// Class Button
function Button(moduleName, moduleLink, picFilename, aniFilename, moduleDescr){

  // Properties
  this.bttnID = "bttn" + moduleName;
  this.modName = moduleName;
  this.modLink = moduleLink;
  this.picPath = "pics/" + picFilename;
  this.aniPath = "pics/" + aniFilename;
  this.modDescr = moduleDescr;

  // Methods
  this.createButton = function(){

    // get DIV-wrapper for Button and append it to HTML-document
    bttnWrapper = this.createWrapper();
    document.getElementById("bttnField").appendChild(bttnWrapper);

    // get link-element for picture and append it to DIV-wrapper
    bttnPicLink = this.createPicLink();
    bttnWrapper.appendChild(bttnPicLink);

    // set HTML attributes for button-element
    bttn = document.createElement("img");
    bttn.src = this.picPath;
    bttn.id = this.bttnID;
    bttn.className = "modBttn";
    bttn.height = 123;
    bttn.width = 136;
    bttn.onmouseover = function(){startAni(this.id);};
    bttn.onmouseout = function(){stopAni(this.id);};

    // append button to link-element
    bttnPicLink.appendChild(bttn);

    // create text-link and add it to DIV-wrapper
    bttnTxtLink = document.createElement("a");
    bttnTxtLink.href = this.modLink;
    bttnTxtLink.className = "txtLink";
    bttnTxtLink.appendChild(document.createTextNode(this.modName));
    bttnWrapper.appendChild(bttnTxtLink);

    // create pop-up link for module description
    bttnPopUpLink = document.createElement("a");
    modName = this.modName;
    modDescr = this.modDescr;
    bttnPopUpLink.onclick = function(){showPopUpWindow();};
    bttnPopUpLink.className = "popUpLink";
    bttnPopUpLink.id = "popup" + this.modName;
    bttnPopUpLink.appendChild(document.createTextNode("more info >>"));
    bttnWrapper.appendChild(document.createElement("br"));
    bttnWrapper.appendChild(bttnPopUpLink);

    return bttn;
  }

  this.createWrapper = function(){
    bttnWrapper = document.createElement("div");
    bttnWrapper.id = "wrapper" + this.modName;
    bttnWrapper.className = "bttnWrap";

    return bttnWrapper;
  }

  this.createPicLink = function(){
    picLink = document.createElement("a");
    picLink.href = this.modLink;
    picLink.id = "link" + this.modName;

    return picLink;
  }

}

function showPopUpWindow(){

  // modules position in array?
  modulePos = getPos(currentTarget,"popup");

  // get reference to anchor-element in HTML-document
  popUpAnchor = document.getElementById("popupAnchor");

  // check if a popUp is open
  if(popUpAnchor.hasChildNodes()){
    // if a popUp is open, remove it!
    popUpAnchor.removeChild(document.getElementById("popup"));
  }

  // create new container for popUp
  container = document.createElement("div");
  container.id = "popup";
  container.align = "right";

  // append popUp-container to HTML-document
  popUpAnchor.appendChild(container);

  // create close-button and append it to popUp-container
  bttnClose = document.createElement("img");
  bttnClose.src = "pics/popup_bttn_close.png";
  bttnClose.id = "bttnClose";
  bttnClose.onclick = function(){closeInfoWindow();};
  container.appendChild(bttnClose);

  // create container for content-elements
  contHeadline = document.createElement("div");
  contHeadline.id = "contHeadline";
  contDescription = document.createElement("div");
  contDescription.id = "contDescription";
  contModLink = document.createElement("div");
  contModLink.id = "contModLink";

  // append content-container to popUp-container
  container.appendChild(contHeadline);
  container.appendChild(contDescription);
  container.appendChild(contModLink);

  // create text-elements with content
  headline = document.createTextNode(moduleNames[modulePos] + " ");
  description = document.createTextNode(moduleDescriptions[modulePos]);
  moduleLink = document.createElement("a");
  moduleLink.href = moduleLinks[modulePos] ;
  moduleLink.className = 'moduleLink';
  moduleLinkTxt = document.createTextNode("Click here to open the " + moduleNames[modulePos].toLowerCase() + " dataset");
  moduleLink.appendChild(moduleLinkTxt);

  // append text-elements to their container
  contHeadline.appendChild(headline);
  contDescription.appendChild(description);
  contModLink.appendChild(moduleLink);
}

function getPos(id,prefix){

  if(prefix == "popup"){
    targetID = id.slice(5);
  }else{
    if(prefix == "bttn"){
      targetID = id.slice(4);
    }
  }

  for(i=0; i < moduleNames.length; i++ ){
    if(moduleNames[i] == targetID){
      return i;
    }
  }
}

function setExperimental(modPos){
  linkID = "link" + moduleNames[modPos];

  expPic = document.createElement("img");
  expPic.src = "pics/experimental.png";
  expPic.className = "expPic";
  //alert(bttns[modPos].bttnID);
  expPic.onmouseover = function(){startAni(bttns[modPos].bttnID);changeToHover(bttns[modPos].bttnID);};
  expPic.onmouseout = function(){stopAni(bttns[modPos].bttnID);changeToNormal(bttns[modPos].bttnID);};

  document.getElementById(linkID).appendChild(expPic);
}

function changeToHover(targetId){
  bttn = document.getElementById(targetId);
  bttn.className = "modBttnHover";
}

function changeToNormal(targetId){
  bttn = document.getElementById(targetId);
  bttn.className = "modBttn";
}

// function to close PopUp-window
function closeInfoWindow(){
  popUpAnchor = document.getElementById("popupAnchor");
  popUpAnchor.removeChild(document.getElementById("popup"));
}

function createClearFloat(){
  cf = document.createElement("div");
  cf.className = "clearfloat";
  document.getElementById("bttnField").appendChild(cf);
}

startAni = function(targetId){
  modulePos = getPos(targetId,"bttn");

  if(aniFilenames[modulePos] != ''){
    bttn = document.getElementById(targetId);
    bttn.src = "pics/" + aniFilenames[modulePos];
  }
}

stopAni = function(targetId){
  modulePos = getPos(targetId,"bttn");

  bttn = document.getElementById(targetId);
  bttn.src = "pics/" + picFilenames[modulePos];
}

<|endoftext|>


<commit_before>importScripts('openpgp.worker.min.js');

var sha256 = window.openpgp.crypto.hash.sha256;

var iterateOverSHA = function(seed) {
  var i;
  for (i = 0; i < 1024; i++) {
    var x = sha256(seed + i);

    if (x[31] === 0) {
      postMessage(i);
    }
  }

  postMessage("12345");
};

onmessage = function(e) {
  iterateOverSHA(e.data.pow);
};
<commit_msg>Replace inclusion of the whole openpgp.js inside proof-of-work implementation with sha256 from scrypt-async-js<commit_after>// stringToUTF8Bytes and sha256 function from scrypt-async-js library 1.2.0

function stringToUTF8Bytes(s) {
  var arr = [];
  for (var i = 0; i < s.length; i++) {
    var c = s.charCodeAt(i);
    if (c < 128) {
      arr.push(c);
    } else if (c > 127 && c < 2048) {
      arr.push((c>>6) | 192);
      arr.push((c & 63) | 128);
    } else {
      arr.push((c>>12) | 224);
      arr.push(((c>>6) & 63) | 128);
      arr.push((c & 63) | 128);
    }
  }
  return arr;
}

function sha256(m) {
  m = stringToUTF8Bytes(m);

  /** @const */ var K = [
    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b,
    0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
    0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7,
    0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
    0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152,
    0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
    0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
    0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
    0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819,
    0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
    0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
    0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
    0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
  ];

  var h0 = 0x6a09e667, h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a,
      h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19,
      w = new Array(64);

  function blocks(p) {
    var off = 0, len = p.length;
    while (len >= 64) {
      var a = h0, b = h1, c = h2, d = h3, e = h4, f = h5, g = h6, h = h7,
          u, i, j, t1, t2;

      for (i = 0; i < 16; i++) {
        j = off + i*4;
        w[i] = ((p[j] & 0xff)<<24) | ((p[j+1] & 0xff)<<16) |
               ((p[j+2] & 0xff)<<8) | (p[j+3] & 0xff);
      }

      for (i = 16; i < 64; i++) {
        u = w[i-2];
        t1 = ((u>>>17) | (u<<(32-17))) ^ ((u>>>19) | (u<<(32-19))) ^ (u>>>10);

        u = w[i-15];
        t2 = ((u>>>7) | (u<<(32-7))) ^ ((u>>>18) | (u<<(32-18))) ^ (u>>>3);

        w[i] = (((t1 + w[i-7]) | 0) + ((t2 + w[i-16]) | 0)) | 0;
      }

      for (i = 0; i < 64; i++) {
        t1 = ((((((e>>>6) | (e<<(32-6))) ^ ((e>>>11) | (e<<(32-11))) ^
             ((e>>>25) | (e<<(32-25)))) + ((e & f) ^ (~e & g))) | 0) +
             ((h + ((K[i] + w[i]) | 0)) | 0)) | 0;

        t2 = ((((a>>>2) | (a<<(32-2))) ^ ((a>>>13) | (a<<(32-13))) ^
             ((a>>>22) | (a<<(32-22)))) + ((a & b) ^ (a & c) ^ (b & c))) | 0;

        h = g;
        g = f;
        f = e;
        e = (d + t1) | 0;
        d = c;
        c = b;
        b = a;
        a = (t1 + t2) | 0;
      }

      h0 = (h0 + a) | 0;
      h1 = (h1 + b) | 0;
      h2 = (h2 + c) | 0;
      h3 = (h3 + d) | 0;
      h4 = (h4 + e) | 0;
      h5 = (h5 + f) | 0;
      h6 = (h6 + g) | 0;
      h7 = (h7 + h) | 0;

      off += 64;
      len -= 64;
    }
  }

  blocks(m);

  var i, bytesLeft = m.length % 64,
      bitLenHi = (m.length / 0x20000000) | 0,
      bitLenLo = m.length << 3,
      numZeros = (bytesLeft < 56) ? 56 : 120,
      p = m.slice(m.length - bytesLeft, m.length);

  p.push(0x80);
  for (i = bytesLeft + 1; i < numZeros; i++) p.push(0);
  p.push((bitLenHi>>>24) & 0xff);
  p.push((bitLenHi>>>16) & 0xff);
  p.push((bitLenHi>>>8)  & 0xff);
  p.push((bitLenHi>>>0)  & 0xff);
  p.push((bitLenLo>>>24) & 0xff);
  p.push((bitLenLo>>>16) & 0xff);
  p.push((bitLenLo>>>8)  & 0xff);
  p.push((bitLenLo>>>0)  & 0xff);

  blocks(p);

  return [
    (h0>>>24) & 0xff, (h0>>>16) & 0xff, (h0>>>8) & 0xff, (h0>>>0) & 0xff,
    (h1>>>24) & 0xff, (h1>>>16) & 0xff, (h1>>>8) & 0xff, (h1>>>0) & 0xff,
    (h2>>>24) & 0xff, (h2>>>16) & 0xff, (h2>>>8) & 0xff, (h2>>>0) & 0xff,
    (h3>>>24) & 0xff, (h3>>>16) & 0xff, (h3>>>8) & 0xff, (h3>>>0) & 0xff,
    (h4>>>24) & 0xff, (h4>>>16) & 0xff, (h4>>>8) & 0xff, (h4>>>0) & 0xff,
    (h5>>>24) & 0xff, (h5>>>16) & 0xff, (h5>>>8) & 0xff, (h5>>>0) & 0xff,
    (h6>>>24) & 0xff, (h6>>>16) & 0xff, (h6>>>8) & 0xff, (h6>>>0) & 0xff,
    (h7>>>24) & 0xff, (h7>>>16) & 0xff, (h7>>>8) & 0xff, (h7>>>0) & 0xff
  ];
}

var iterateOverSHA = function(seed) {
  var i;
  for (i = 0; i < 1024; i++) {
    var x = sha256(seed + i);

    if (x[31] === 0) {
      postMessage(i);
      close();
    }
  }

  postMessage("12345");
  close();
};

onmessage = function(e) {
  iterateOverSHA(e.data.pow);
};
<|endoftext|>


<commit_before>var landingpage = angular.module('landingpage');

landingpage.factory('BallotizeFactory', ['$http', function($http){
  var code = '';
  var user = '';

  var setUser = function(username){
    user = username;
    console.log('setUser called, user: ',user);
    return user;
  }

  var getUser = function(){
    console.log('getUser called, user: ',user);
    return user;
  }

  var setCode = function(input){
    return code = input;
  }

  var getCode = function(){
    return code;
  }

  var getBallot = function(input, username){
    $http({
       method: 'GET',
       url: '/ballot',
       params: {
         code: input,
         username: username
       }
     }).then(function success(response){
       console.log('success',response)
     }, function error(response){
       console.log('error',response);
     });
  }

  return {
    setUser: setUser,
    getUser: getUser,
    setCode: setCode,
    getCode: getCode,
    getBallot: getBallot
  }
}]);
<commit_msg>[feat] adds routing state to landingpage factory<commit_after>var landingpage = angular.module('landingpage');

landingpage.factory('BallotizeFactory', ['$http', '$state', function($http, $state){
  var code = '';
  var user = '';

  var setUser = function(username){
    user = username;
    console.log('setUser called, user: ',user);
    return user;
  }

  var getUser = function(){
    console.log('getUser called, user: ',user);
    return user;
  }

  var setCode = function(input){
    return code = input;
  }

  var getCode = function(){
    return code;
  }

  var getBallot = function(input, username){
    $http({
       method: 'GET',
       url: '/ballot',
       params: {
         code: input,
         username: username
       }
     }).then(function success(response){
       console.log('success',response)
       $state.go('uservote');
     }, function error(response){
       console.log('error',response);
     });
  }

  return {
    setUser: setUser,
    getUser: getUser,
    setCode: setCode,
    getCode: getCode,
    getBallot: getBallot
  }
}]);
<|endoftext|>


<commit_before>var categoriesController = (function() {

    function all(context) {
        var categories;

        //categoryModel.all()
        //    .then(function(res) {
        //        categories = res;
        //        console.log(categories);
        //        return templatesManager.get("categories");
        //    })
        //    .then(function(partial) {
        //        templatesManager.fill(context, partial, categories);
        //    })
        appManager.loadView("categories", context, false, categoryModel.all, false)
            .then(function() {
                $("#btn-add").on("click", function() {
                    categoryModel.add($("#tb-new-category-name").val());
                });

                $(".btn-category-show").on("click", function (e) {
                    var target = e.currentTarget;
                    // TODO: Save on localeStorage for better behave on refresh
                    categoryModel.currentId(+$(target).attr("id"));
                    context.redirect("/#/category/" + categoryModel.currentId());
                });
            });
    }

    function byId(context) {
        console.log('categories');
        categoryModel.currentId(+context.params["categoryId"]);
        var category;

        appManager.loadView("category", context, false, categoryModel.byId, categoryModel.currentId())
            .then(function() {
                sidebarController.config;

                eventManager.attachShowSection(context);
                eventManager.attachAddSection(context);

            });
        return false;
    }

    function add(context) {
        appManager.loadView("add-category", context)
            .then(function() {
                $("#btn-category-add").on("click", function() {
                    console.log($("#tb-category-add").val());
                    categoryModel.add({ name: $("#tb-category-add").val() })
                        .then(function () {
                            notificationController.publish('new category added');

                            context.redirect("/#/");
                        });
                });
            });
    }

    return {
        all: all,
        current: byId,
        add: add
    };
}())<commit_msg>[Client] Added restriction when trying to add a new category but not logged in<commit_after>var categoriesController = (function() {

    function all(context) {
        var categories;

        //categoryModel.all()
        //    .then(function(res) {
        //        categories = res;
        //        console.log(categories);
        //        return templatesManager.get("categories");
        //    })
        //    .then(function(partial) {
        //        templatesManager.fill(context, partial, categories);
        //    })
        appManager.loadView("categories", context, false, categoryModel.all, false)
            .then(function() {
                $("#btn-add").on("click", function() {
                    categoryModel.add($("#tb-new-category-name").val());
                });

                $(".btn-category-show").on("click", function (e) {
                    var target = e.currentTarget;
                    // TODO: Save on localeStorage for better behave on refresh
                    categoryModel.currentId(+$(target).attr("id"));
                    context.redirect("/#/category/" + categoryModel.currentId());
                });
            });
    }

    function byId(context) {
        console.log('categories');
        categoryModel.currentId(+context.params["categoryId"]);
        var category;

        appManager.loadView("category", context, false, categoryModel.byId, categoryModel.currentId())
            .then(function() {
                sidebarController.config;

                eventManager.attachShowSection(context);
                eventManager.attachAddSection(context);

            });
        return false;
    }

    function add(context) {
        if (appManager.checkIfLogged() === false) {
            toastr.warning('You must be logged in to add categories');
        }
        else {
            appManager.loadView("add-category", context)
                .then(function () {
                    $("#btn-category-add").on("click", function () {
                        console.log($("#tb-category-add").val());
                        categoryModel.add({ name: $("#tb-category-add").val() })
                            .then(function () {
                                notificationController.publish('new category added');

                                context.redirect("/#/");
                            });
                    });
                });
        }
    }

    return {
        all: all,
        current: byId,
        add: add
    };
}())<|endoftext|>


<commit_before>import React from 'react';
import './add-message.scss';

class Message extends React.Component {
    render() {
        return (

        <textarea
            name='message'
            placeholder='Enter a message...'
            value={this.props.value}
            onChange={this.handleChange.bind(this)}
            onKeyPress={this.handleKeyPress.bind(this)}/>

        );
    }

    handleChange(ev) {
        this.props.onChange(ev.target.value);
    }

    handleKeyPress(ev) {
        if (ev.which === 13) {
            const trimmedMessage = this.props.value.trim();

            if (trimmedMessage) {
                this.props.onSubmit({
                    text: trimmedMessage,
                    userId: this.props.userId
                });
            }

            ev.preventDefault();
        }
    }
}

export default Message;<commit_msg>wrap w/ class name to allow style to propagate via wix-param<commit_after>import React from 'react';
import './add-message.scss';

class Message extends React.Component {
    render() {
        return (

        <textarea
            name='message'
            className="add-message"
            placeholder='Enter a message...'
            value={this.props.value}
            onChange={this.handleChange.bind(this)}
            onKeyPress={this.handleKeyPress.bind(this)}/>

        );
    }

    handleChange(ev) {
        this.props.onChange(ev.target.value);
    }

    handleKeyPress(ev) {
        if (ev.which === 13) {
            const trimmedMessage = this.props.value.trim();

            if (trimmedMessage) {
                this.props.onSubmit({
                    text: trimmedMessage,
                    userId: this.props.userId
                });
            }

            ev.preventDefault();
        }
    }
}

export default Message;<|endoftext|>


<commit_before>"use strict";

define(['logManager',
        'loaderCircles',
        'js/Utils/GMEConcepts',
        'js/Dialogs/Import/ImportDialog',
        'text!html/Dialogs/Projects/ProjectsDialog.html',
        'css!/css/Dialogs/Projects/ProjectsDialog'], function (logManager,
                                                               LoaderCircles,
                                                               GMEConcepts,
                                                               ImportDialog,
                                                               projectsDialogTemplate) {

    var ProjectsDialog,
        DATA_PROJECT_NAME = "PROJECT_NAME";

    ProjectsDialog = function (client) {
        this._logger = logManager.create("ProjectsDialog");

        this._client = client;
        this._projectNames = [];
        this._projectList = {};
        this._filter = undefined;

        this._logger.debug("Created");
    };

    ProjectsDialog.prototype.show = function () {
        var self = this;

        this._initDialog();

        this._dialog.modal('show');

        this._dialog.on('hidden', function () {
            self._loader.destroy();
            self._dialog.remove();
            self._dialog.empty();
            self._dialog = undefined;
        });

        this._refreshProjectList();
    };

    ProjectsDialog.prototype._initDialog = function () {
        var self = this,
            selectedId;

        var openProject = function (projId) {
            if (self._projectList[projId].read === true) {
                self._client.selectProjectAsync(projId,function(){
                    self._dialog.modal('hide');
                });
            }
        };

        var doCreateProject = function () {
            var val = self._txtNewProjectName.val();

            if (val !== "" && self._projectNames.indexOf(val) === -1) {
                self._btnNewProjectCreate.addClass("disabled");
                self._createNewProject(val);
            }
        };

        var deleteProject = function (projId) {
            if (self._projectList[projId].delete === true) {
                self._client.deleteProjectAsync(selectedId,function(){
                    self._refreshProjectList();
                });
            }
        };

        var doCreateProjectFromFile = function () {
            var val = self._txtNewProjectName.val();

            if (val !== "" && self._projectNames.indexOf(val) === -1) {
                self._btnNewProjectImport.addClass("disabled");
                self._dialog.modal('hide');
                var d = new ImportDialog();
                d.show(function (fileContent) {
                    self._createProjectFromFile(val, fileContent);
                });
            }
        };

        this._dialog = $(projectsDialogTemplate);

        //get controls
        this._el = this._dialog.find('.modal-body').first();
        this._ul = this._el.find('ul').first();

        this._panelPuttons = this._dialog.find(".panel-buttons");
        this._panelCreateNew = this._dialog.find(".panel-create-new");

        this._btnOpen = this._dialog.find(".btn-open");
        this._btnDelete = this._dialog.find(".btn-delete");
        this._btnCreateNew = this._dialog.find(".btn-create-new");
        this._btnCreateFromFile = this._dialog.find(".btn-import-file");
        this._btnRefresh = this._dialog.find(".btn-refresh");

        this._btnNewProjectCancel = this._dialog.find(".btn-cancel");
        this._btnNewProjectCreate = this._dialog.find(".btn-save");
        this._btnNewProjectImport = this._dialog.find(".btn-import");

        this._txtNewProjectName = this._dialog.find(".txt-project-name");

        this._loader = new LoaderCircles({"containerElement": this._btnRefresh });
        this._loader.setSize(14);

        this._dialog.find('.tabContainer').first().groupedAlphabetTabs({'onClick': function (filter) {
            self._filter = filter;
            self._updateProjectNameList();
        }});

        //hook up event handlers - SELECT project in the list
        this._ul.on("click", "li:not(.disabled)", function (event) {
            selectedId = $(this).data(DATA_PROJECT_NAME);

            event.stopPropagation();
            event.preventDefault();

            if (self._projectList[selectedId].read === true) {
                self._ul.find('.active').removeClass('active');
                $(this).addClass('active');

                if (selectedId === self._activeProject) {
                    self._showButtons(false, selectedId);
                } else {
                    self._showButtons(true, selectedId);
                }
            }
        });

        //open on double click
        this._ul.on("dblclick", "li:not(.disabled)", function (event) {
            selectedId = $(this).data(DATA_PROJECT_NAME);

            event.stopPropagation();
            event.preventDefault();

            openProject(selectedId);
        });

        this._btnOpen.on('click', function (event) {
            self._btnOpen.addClass("disabled");
            self._btnDelete.addClass("disabled");

            event.stopPropagation();
            event.preventDefault();

            openProject(selectedId);
        });

        this._btnDelete.on('click', function (event) {
            self._btnOpen.addClass("disabled");
            self._btnDelete.addClass("disabled");

            deleteProject(selectedId);

            event.stopPropagation();
            event.preventDefault();
        });

        this._btnCreateNew.on('click', function (event) {
            self._txtNewProjectName.val('');
            self._panelPuttons.hide();
            self._panelCreateNew.show();
            self._txtNewProjectName.focus();
            self._btnNewProjectImport.hide();

            event.stopPropagation();
            event.preventDefault();
        });

        this._btnNewProjectCancel.on('click', function (event) {
            self._panelPuttons.show();
            self._panelCreateNew.hide();
            self._btnNewProjectCreate.show();
            self._btnNewProjectImport.show();

            self._filter = self._dialog.find('.tabContainer li.active').data('filter');
            self._updateProjectNameList();

            event.stopPropagation();
            event.preventDefault();
        });

        this._btnCreateFromFile.on('click', function (event) {
            self._txtNewProjectName.val('');
            self._panelPuttons.hide();
            self._panelCreateNew.show();
            self._txtNewProjectName.focus();
            self._btnNewProjectCreate.hide();

            event.stopPropagation();
            event.preventDefault();
        });

        this._txtNewProjectName.on('keyup', function () {
            var val = self._txtNewProjectName.val(),
                re = /^[0-9a-z_]+$/gi;

            if (val.length === 1) {
                self._filter = [val.toUpperCase(), val.toUpperCase()];
                self._updateProjectNameList();
            }

            if (!re.test(val) || self._projectNames.indexOf(val) !== -1) {
                self._panelCreateNew.addClass("error");
                self._btnNewProjectCreate.addClass("disabled");
                self._btnNewProjectImport.addClass("disabled");
            } else {
                self._panelCreateNew.removeClass("error");
                self._btnNewProjectCreate.removeClass("disabled");
                self._btnNewProjectImport.removeClass("disabled");
            }
        });

        this._btnNewProjectCreate.on('click', function (event) {
            doCreateProject();
            event.stopPropagation();
            event.preventDefault();
        });

        this._btnNewProjectImport.on('click', function (event) {
            doCreateProjectFromFile();
            event.stopPropagation();
            event.preventDefault();
        });

        this._txtNewProjectName.on('keydown', function (event) {
            // [enter]
            if (event.which === 13) {
                //create project
                doCreateProject();
                event.preventDefault();
                event.stopPropagation();
            }
        });

        this._btnRefresh.on('click', function (event) {
            self._refreshProjectList();

            event.stopPropagation();
            event.preventDefault();
        });
    };

    ProjectsDialog.prototype._refreshProjectList = function () {
        var self = this;

        this._loader.start();
        this._btnRefresh.addClass('disabled');
        this._btnRefresh.find('i').css('opacity', '0');

        this._client.getFullProjectListAsync(function(err,projectList){
            var p;
            self._activeProject = self._client.getActiveProject();
            self._projectList = {};
            self._projectNames = [];

            for (p in projectList) {
                if (projectList.hasOwnProperty(p)) {
                    self._projectNames.push(p);
                    self._projectList[p] = projectList[p];
                }
            }

            self._projectNames.sort(function compare(a, b) {
                //same read access right, sort by name
                if (self._projectList[a].read === self._projectList[b].read) {
                    if (a.toLowerCase()  b.toLowerCase())
                        return 1;

                    // a must be equal to b
                    return 0;
                } else {
                    //different read access right
                    //read-ony goes later in the order
                    if (self._projectList[a].read === true) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
            });

            self._updateProjectNameList();

            self._loader.stop();
            self._btnRefresh.find('i').css('opacity', '1');
            self._btnRefresh.removeClass('disabled');
        });
    };

    ProjectsDialog.prototype._showButtons = function (enabled, projectId) {
        if (enabled === true) {
            //btnOpen
            if (this._projectList[projectId].read === true) {
                this._btnOpen.show();
                this._btnOpen.removeClass('disabled');
            } else {
                this._btnOpen.hide();
                this._btnOpen.addClass('disabled');
            }

            //btnDelete
            if (this._projectList[projectId].delete === true) {
                this._btnDelete.show();
                this._btnDelete.removeClass('disabled');
            } else {
                this._btnDelete.hide();
                this._btnDelete.addClass('disabled');
            }
        } else {
            this._btnOpen.hide();
            this._btnOpen.addClass('disabled');
            this._btnDelete.hide();
            this._btnDelete.addClass('disabled');
        }

    };

    ProjectsDialog.prototype._createNewProject = function (projectName) {
        var _client = this._client,
            _dialog = this._dialog,
            _logger = this._logger;

        _client.createProjectAsync(projectName,function (err) {
            if (!err) {
                _client.selectProjectAsync(projectName, function (err) {
                    if (!err) {
                        GMEConcepts.createBasicProjectSeed();
                        _dialog.modal('hide');
                    } else {
                        _logger.error('CAN NOT OPEN NEW PROJECT: ' + err.stack);
                    }
                });
            } else {
                _logger.error('CAN NOT CREATE NEW PROJECT: ' + err.stack);
            }
        });
    };

    ProjectsDialog.prototype._updateProjectNameList = function () {
        var len = this._projectNames.length,
            i,
            li,
            displayProject;

        this._ul.empty();

        for (i = 0; i < len ; i += 1) {
            displayProject = false;
            if (this._filter !== undefined) {
                displayProject = (this._projectNames[i].toUpperCase()[0] >= this._filter[0] &&
                    this._projectNames[i].toUpperCase()[0] <= this._filter[1]);
            } else {
                displayProject = true;
            }

            if (displayProject) {
                li = $('
' + this._projectNames[i] + '');
                li.data(DATA_PROJECT_NAME, this._projectNames[i]);

                if (this._projectNames[i] === this._activeProject) {
                    li.addClass('active');
                }

                //check to see if the user has READ access to this project
                if (this._projectList[this._projectNames[i]].read !== true) {
                    li.addClass('disabled');
                }

                this._ul.append(li);
            }
        }

        this._showButtons(false);
    };

    ProjectsDialog.prototype._createProjectFromFile = function (projectName, jsonContent) {
        var _client = this._client,
            _logger = this._logger;

        _client.createProjectFromFileAsync(projectName, jsonContent, function (err) {
            if (!err) {
                _logger.debug('CREATE NEW PROJECT FROM FILE FINISHED SUCCESSFULLY');
            } else {
                _logger.error('CAN NOT CREATE NEW PROJECT FROM FILE: ' + err.message);
            }
        });
    };

    return ProjectsDialog;
});<commit_msg>bugfix: create empty / create from file correction on txtName ENTER<commit_after>"use strict";

define(['logManager',
        'loaderCircles',
        'js/Utils/GMEConcepts',
        'js/Dialogs/Import/ImportDialog',
        'text!html/Dialogs/Projects/ProjectsDialog.html',
        'css!/css/Dialogs/Projects/ProjectsDialog'], function (logManager,
                                                               LoaderCircles,
                                                               GMEConcepts,
                                                               ImportDialog,
                                                               projectsDialogTemplate) {

    var ProjectsDialog,
        DATA_PROJECT_NAME = "PROJECT_NAME",
        CREATE_TYPE_EMPTY = 'create_empty',
        CREATE_TYPE_IMPORT = 'create_import';

    ProjectsDialog = function (client) {
        this._logger = logManager.create("ProjectsDialog");

        this._client = client;
        this._projectNames = [];
        this._projectList = {};
        this._filter = undefined;

        this._logger.debug("Created");
    };

    ProjectsDialog.prototype.show = function () {
        var self = this;

        this._initDialog();

        this._dialog.modal('show');

        this._dialog.on('hidden', function () {
            self._loader.destroy();
            self._dialog.remove();
            self._dialog.empty();
            self._dialog = undefined;
        });

        this._refreshProjectList();
    };

    ProjectsDialog.prototype._initDialog = function () {
        var self = this,
            selectedId,
            createType;

        var openProject = function (projId) {
            if (self._projectList[projId].read === true) {
                self._client.selectProjectAsync(projId,function(){
                    self._dialog.modal('hide');
                });
            }
        };

        var doCreateProject = function () {
            var val = self._txtNewProjectName.val();

            if (val !== "" && self._projectNames.indexOf(val) === -1) {
                self._btnNewProjectCreate.addClass("disabled");
                self._createNewProject(val);
            }
        };

        var deleteProject = function (projId) {
            if (self._projectList[projId].delete === true) {
                self._client.deleteProjectAsync(selectedId,function(){
                    self._refreshProjectList();
                });
            }
        };

        var doCreateProjectFromFile = function () {
            var val = self._txtNewProjectName.val();

            if (val !== "" && self._projectNames.indexOf(val) === -1) {
                self._btnNewProjectImport.addClass("disabled");
                self._dialog.modal('hide');
                var d = new ImportDialog();
                d.show(function (fileContent) {
                    self._createProjectFromFile(val, fileContent);
                });
            }
        };

        this._dialog = $(projectsDialogTemplate);

        //get controls
        this._el = this._dialog.find('.modal-body').first();
        this._ul = this._el.find('ul').first();

        this._panelPuttons = this._dialog.find(".panel-buttons");
        this._panelCreateNew = this._dialog.find(".panel-create-new");

        this._btnOpen = this._dialog.find(".btn-open");
        this._btnDelete = this._dialog.find(".btn-delete");
        this._btnCreateNew = this._dialog.find(".btn-create-new");
        this._btnCreateFromFile = this._dialog.find(".btn-import-file");
        this._btnRefresh = this._dialog.find(".btn-refresh");

        this._btnNewProjectCancel = this._dialog.find(".btn-cancel");
        this._btnNewProjectCreate = this._dialog.find(".btn-save");
        this._btnNewProjectImport = this._dialog.find(".btn-import");

        this._txtNewProjectName = this._dialog.find(".txt-project-name");

        this._loader = new LoaderCircles({"containerElement": this._btnRefresh });
        this._loader.setSize(14);

        this._dialog.find('.tabContainer').first().groupedAlphabetTabs({'onClick': function (filter) {
            self._filter = filter;
            self._updateProjectNameList();
        }});

        //hook up event handlers - SELECT project in the list
        this._ul.on("click", "li:not(.disabled)", function (event) {
            selectedId = $(this).data(DATA_PROJECT_NAME);

            event.stopPropagation();
            event.preventDefault();

            if (self._projectList[selectedId].read === true) {
                self._ul.find('.active').removeClass('active');
                $(this).addClass('active');

                if (selectedId === self._activeProject) {
                    self._showButtons(false, selectedId);
                } else {
                    self._showButtons(true, selectedId);
                }
            }
        });

        //open on double click
        this._ul.on("dblclick", "li:not(.disabled)", function (event) {
            selectedId = $(this).data(DATA_PROJECT_NAME);

            event.stopPropagation();
            event.preventDefault();

            openProject(selectedId);
        });

        this._btnOpen.on('click', function (event) {
            self._btnOpen.addClass("disabled");
            self._btnDelete.addClass("disabled");

            event.stopPropagation();
            event.preventDefault();

            openProject(selectedId);
        });

        this._btnDelete.on('click', function (event) {
            self._btnOpen.addClass("disabled");
            self._btnDelete.addClass("disabled");

            deleteProject(selectedId);

            event.stopPropagation();
            event.preventDefault();
        });

        this._btnCreateNew.on('click', function (event) {
            createType = CREATE_TYPE_EMPTY;
            self._txtNewProjectName.val('');
            self._panelPuttons.hide();
            self._panelCreateNew.show();
            self._txtNewProjectName.focus();
            self._btnNewProjectImport.hide();

            event.stopPropagation();
            event.preventDefault();
        });

        this._btnNewProjectCancel.on('click', function (event) {
            createType = undefined;
            self._panelPuttons.show();
            self._panelCreateNew.hide();
            self._btnNewProjectCreate.show();
            self._btnNewProjectImport.show();

            self._filter = self._dialog.find('.tabContainer li.active').data('filter');
            self._updateProjectNameList();

            event.stopPropagation();
            event.preventDefault();
        });

        this._btnCreateFromFile.on('click', function (event) {
            createType = CREATE_TYPE_IMPORT;
            self._txtNewProjectName.val('');
            self._panelPuttons.hide();
            self._panelCreateNew.show();
            self._txtNewProjectName.focus();
            self._btnNewProjectCreate.hide();

            event.stopPropagation();
            event.preventDefault();
        });

        this._txtNewProjectName.on('keyup', function () {
            var val = self._txtNewProjectName.val(),
                re = /^[0-9a-z_]+$/gi;

            if (val.length === 1) {
                self._filter = [val.toUpperCase(), val.toUpperCase()];
                self._updateProjectNameList();
            }

            if (!re.test(val) || self._projectNames.indexOf(val) !== -1) {
                self._panelCreateNew.addClass("error");
                self._btnNewProjectCreate.addClass("disabled");
                self._btnNewProjectImport.addClass("disabled");
            } else {
                self._panelCreateNew.removeClass("error");
                self._btnNewProjectCreate.removeClass("disabled");
                self._btnNewProjectImport.removeClass("disabled");
            }
        });

        this._btnNewProjectCreate.on('click', function (event) {
            doCreateProject();
            event.stopPropagation();
            event.preventDefault();
        });

        this._btnNewProjectImport.on('click', function (event) {
            doCreateProjectFromFile();
            event.stopPropagation();
            event.preventDefault();
        });

        this._txtNewProjectName.on('keydown', function (event) {
            // [enter]
            if (event.which === 13) {
                //create project
                if (createType === CREATE_TYPE_EMPTY) {
                    doCreateProject();
                } else if (createType === CREATE_TYPE_IMPORT) {
                    doCreateProjectFromFile();
                }

                event.preventDefault();
                event.stopPropagation();
            }
        });

        this._btnRefresh.on('click', function (event) {
            self._refreshProjectList();

            event.stopPropagation();
            event.preventDefault();
        });
    };

    ProjectsDialog.prototype._refreshProjectList = function () {
        var self = this;

        this._loader.start();
        this._btnRefresh.addClass('disabled');
        this._btnRefresh.find('i').css('opacity', '0');

        this._client.getFullProjectListAsync(function(err,projectList){
            var p;
            self._activeProject = self._client.getActiveProject();
            self._projectList = {};
            self._projectNames = [];

            for (p in projectList) {
                if (projectList.hasOwnProperty(p)) {
                    self._projectNames.push(p);
                    self._projectList[p] = projectList[p];
                }
            }

            self._projectNames.sort(function compare(a, b) {
                //same read access right, sort by name
                if (self._projectList[a].read === self._projectList[b].read) {
                    if (a.toLowerCase()  b.toLowerCase())
                        return 1;

                    // a must be equal to b
                    return 0;
                } else {
                    //different read access right
                    //read-ony goes later in the order
                    if (self._projectList[a].read === true) {
                        return -1;
                    } else {
                        return 1;
                    }
                }
            });

            self._updateProjectNameList();

            self._loader.stop();
            self._btnRefresh.find('i').css('opacity', '1');
            self._btnRefresh.removeClass('disabled');
        });
    };

    ProjectsDialog.prototype._showButtons = function (enabled, projectId) {
        if (enabled === true) {
            //btnOpen
            if (this._projectList[projectId].read === true) {
                this._btnOpen.show();
                this._btnOpen.removeClass('disabled');
            } else {
                this._btnOpen.hide();
                this._btnOpen.addClass('disabled');
            }

            //btnDelete
            if (this._projectList[projectId].delete === true) {
                this._btnDelete.show();
                this._btnDelete.removeClass('disabled');
            } else {
                this._btnDelete.hide();
                this._btnDelete.addClass('disabled');
            }
        } else {
            this._btnOpen.hide();
            this._btnOpen.addClass('disabled');
            this._btnDelete.hide();
            this._btnDelete.addClass('disabled');
        }

    };

    ProjectsDialog.prototype._createNewProject = function (projectName) {
        var _client = this._client,
            _dialog = this._dialog,
            _logger = this._logger;

        _client.createProjectAsync(projectName,function (err) {
            if (!err) {
                _client.selectProjectAsync(projectName, function (err) {
                    if (!err) {
                        GMEConcepts.createBasicProjectSeed();
                        _dialog.modal('hide');
                    } else {
                        _logger.error('CAN NOT OPEN NEW PROJECT: ' + err.stack);
                    }
                });
            } else {
                _logger.error('CAN NOT CREATE NEW PROJECT: ' + err.stack);
            }
        });
    };

    ProjectsDialog.prototype._updateProjectNameList = function () {
        var len = this._projectNames.length,
            i,
            li,
            displayProject;

        this._ul.empty();

        for (i = 0; i < len ; i += 1) {
            displayProject = false;
            if (this._filter !== undefined) {
                displayProject = (this._projectNames[i].toUpperCase()[0] >= this._filter[0] &&
                    this._projectNames[i].toUpperCase()[0] <= this._filter[1]);
            } else {
                displayProject = true;
            }

            if (displayProject) {
                li = $('
' + this._projectNames[i] + '');
                li.data(DATA_PROJECT_NAME, this._projectNames[i]);

                if (this._projectNames[i] === this._activeProject) {
                    li.addClass('active');
                }

                //check to see if the user has READ access to this project
                if (this._projectList[this._projectNames[i]].read !== true) {
                    li.addClass('disabled');
                }

                this._ul.append(li);
            }
        }

        this._showButtons(false);
    };

    ProjectsDialog.prototype._createProjectFromFile = function (projectName, jsonContent) {
        var _client = this._client,
            _logger = this._logger;

        _client.createProjectFromFileAsync(projectName, jsonContent, function (err) {
            if (!err) {
                _logger.debug('CREATE NEW PROJECT FROM FILE FINISHED SUCCESSFULLY');
            } else {
                _logger.error('CAN NOT CREATE NEW PROJECT FROM FILE: ' + err.message);
            }
        });
    };

    return ProjectsDialog;
});<|endoftext|>