<commit_before>angular.module('ionic-geofence')
    .factory('geofenceService', function($window, $q, $log, $ionicLoading) {

        $window.geofence = $window.geofence || {
            addOrUpdate: function(fences) {
                var deffered = $q.defer();
                $log.log('Mocked geofence plugin addOrUpdate', fences);
                deffered.resolve();
                return deffered.promise;
            },
            remove: function(ids) {
                var deffered = $q.defer();
            	$log.log('Mocked geofence plugin remove', ids);
                deffered.resolve();
                return deffered.promise;
            },
            removeAll: function(){
                var deffered = $q.defer();
            	$log.log('Mocked geofence plugin removeAll');
                deffered.resolve();
                return deffered.promise;
            }
        };

        var geofenceService = {
            _geofences: [],
            createdGeofenceDraft: null,
            loadFromLocalStorage: function(){
            	var result = localStorage['geofences'];
		        var geofences = [];
		        if (result) {
		            try {
		                geofences = angular.fromJson(result);
		            } catch (ex) {

		            }
		        }
		        this._geofences = geofences;
            },
            getAll: function() {
                this.loadFromLocalStorage();
                return this._geofences;
            },
            addOrUpdate: function(geofence) {
                if ((this.createdGeofenceDraft && this.createdGeofenceDraft == geofence) ||
                    !this.findById(geofence.id)) {
                    this._geofences.push(geofence);
                }
                $window.geofence.addOrUpdate(geofence);
                localStorage['geofences'] = angular.toJson(this._geofences);
                if (this.createdGeofenceDraft) {
                    this.createdGeofenceDraft = null;
                }
            },
            findById: function(id) {
                if (this.createdGeofenceDraft && this.createdGeofenceDraft.id === id) {
                    return this.createdGeofenceDraft;
                }
                var geoFences = this._geofences.filter(function(g) {
                    return g.id === id
                });
                if (geoFences.length > 0) {
                    return geoFences[0];
                }
                return undefined;
            },
            remove: function(geofence) {
                var self = this;
                $ionicLoading.show({
                    template: 'Removing geofence...'
                });
                $window.geofence.remove(geofence.id).then(function(){
                    $ionicLoading.hide();
                    self._geofences.splice(self._geofences.indexOf(geofence), 1);
                    localStorage['geofences'] = angular.toJson(self._geofences);
                },function(reason){
                    $ionicLoading.show({
                        template: 'Error',
                        duration: 1500
                    });
                });
            },
            removeAll: function(){
                var self = this;
                $ionicLoading.show({
                    template: 'Removing all geofences...'
                });
                $window.geofence.removeAll().then(function(){
                    $ionicLoading.hide();
                    self._geofences.length = 0;
                    localStorage['geofences'] = angular.toJson(self._geofences);
                },function(reason){
                    $ionicLoading.show({
                        template: 'Error',
                        duration: 1500
                    });
                });
            },
            getNextNotificationId: function(){
                var max = 0;
                this._geofences.forEach(function(gf){
                    if(gf.notification && gf.notification.id){
                        if(gf.notification.id > max){
                            max = gf.notification.id;
                        }
                    }
                });
                return max+1;
            }
        };
        geofenceService.loadFromLocalStorage();
        return geofenceService;
    })
    .factory('geolocationService', function($q, $timeout) {
        var currentPositionCache;
        return {
            getCurrentPosition: function() {
                if(!currentPositionCache){
                    var deffered = $q.defer();
                    navigator.geolocation.getCurrentPosition(function(position){
                        deffered.resolve(currentPositionCache = position);
                        $timout(function(){
                            currentPositionCache = undefined;
                        }, 10000);
                    }, function(){
                        deffered.reject();
                    })
                    return deffered.promise;
                }
                return $q.when(currentPositionCache);
            }
        };
    });
<commit_msg>timeout fix<commit_after>angular.module('ionic-geofence')
    .factory('geofenceService', function ($window, $q, $log, $ionicLoading) {

        $window.geofence = $window.geofence || {
            addOrUpdate: function (fences) {
                var deffered = $q.defer();
                $log.log('Mocked geofence plugin addOrUpdate', fences);
                deffered.resolve();
                return deffered.promise;
            },
            remove: function (ids) {
                var deffered = $q.defer();
                $log.log('Mocked geofence plugin remove', ids);
                deffered.resolve();
                return deffered.promise;
            },
            removeAll: function () {
                var deffered = $q.defer();
                $log.log('Mocked geofence plugin removeAll');
                deffered.resolve();
                return deffered.promise;
            }
        };

        var geofenceService = {
            _geofences: [],
            createdGeofenceDraft: null,
            loadFromLocalStorage: function () {
                var result = localStorage['geofences'];
                var geofences = [];
                if (result) {
                    try {
                        geofences = angular.fromJson(result);
                    } catch (ex) {

                    }
                }
                this._geofences = geofences;
            },
            getAll: function () {
                this.loadFromLocalStorage();
                return this._geofences;
            },
            addOrUpdate: function (geofence) {
                if ((this.createdGeofenceDraft && this.createdGeofenceDraft == geofence) ||
                    !this.findById(geofence.id)) {
                    this._geofences.push(geofence);
                }
                $window.geofence.addOrUpdate(geofence);
                localStorage['geofences'] = angular.toJson(this._geofences);
                if (this.createdGeofenceDraft) {
                    this.createdGeofenceDraft = null;
                }
            },
            findById: function (id) {
                if (this.createdGeofenceDraft && this.createdGeofenceDraft.id === id) {
                    return this.createdGeofenceDraft;
                }
                var geoFences = this._geofences.filter(function (g) {
                    return g.id === id
                });
                if (geoFences.length > 0) {
                    return geoFences[0];
                }
                return undefined;
            },
            remove: function (geofence) {
                var self = this;
                $ionicLoading.show({
                    template: 'Removing geofence...'
                });
                $window.geofence.remove(geofence.id).then(function () {
                    $ionicLoading.hide();
                    self._geofences.splice(self._geofences.indexOf(geofence), 1);
                    localStorage['geofences'] = angular.toJson(self._geofences);
                }, function (reason) {
                    $ionicLoading.show({
                        template: 'Error',
                        duration: 1500
                    });
                });
            },
            removeAll: function () {
                var self = this;
                $ionicLoading.show({
                    template: 'Removing all geofences...'
                });
                $window.geofence.removeAll().then(function () {
                    $ionicLoading.hide();
                    self._geofences.length = 0;
                    localStorage['geofences'] = angular.toJson(self._geofences);
                }, function (reason) {
                    $ionicLoading.show({
                        template: 'Error',
                        duration: 1500
                    });
                });
            },
            getNextNotificationId: function () {
                var max = 0;
                this._geofences.forEach(function (gf) {
                    if (gf.notification && gf.notification.id) {
                        if (gf.notification.id > max) {
                            max = gf.notification.id;
                        }
                    }
                });
                return max + 1;
            }
        };
        geofenceService.loadFromLocalStorage();
        return geofenceService;
    })
    .factory('geolocationService', function ($q, $timeout) {
        var currentPositionCache;
        return {
            getCurrentPosition: function () {
                if (!currentPositionCache) {
                    var deffered = $q.defer();
                    navigator.geolocation.getCurrentPosition(function (position) {
                        deffered.resolve(currentPositionCache = position);
                        $timeout(function () {
                            currentPositionCache = undefined;
                        }, 10000);
                    }, function () {
                        deffered.reject();
                    })
                    return deffered.promise;
                }
                return $q.when(currentPositionCache);
            }
        };
    });
<|endoftext|>


<commit_before>var Util           = require('util')
  , Redis          = require('redis')
  , NodeMailer     = require('nodemailer')
  , StreamListener = require('./stream-listener')
  , Subscriptions  = require('./subscriptions');

/**************************
 ****  Mail Transport  ****
 **************************/

var mailTransport  = NodeMailer.createTransport("SMTP");

/**************************
 ****  StreamListener  ****
 **************************/

var streamListener = new StreamListener(Subscriptions.restore());

streamListener.on('subscribe', Subscriptions.backup(streamListener.subscriptions));
streamListener.on('unsubscribe', Subscriptions.backup(streamListener.subscriptions));

streamListener.on('subscribe', function(email, channel) {
    // TODO: elaborate, use rendering engine
    mailTransport.sendMail({
        from:                 "twailer@twailer.mstaessen.be",
        to:                   email,
        subject:              "[" + channel + "] Subscription confirmation",
        generateTextFromHTML: true,
        html:                 "
You successfully subscribed to the channel '" + channel + "'
"
    });
});

streamListener.on('unsubscribe', function(email, channel) {
    // TODO: elaborate, use rendering engine
    mailTransport.sendMail({
        from:                 "twailer@twailer.mstaessen.be",
        to:                   email,
        subject:              "[" + channel + "] Subscription removal confirmation",
        generateTextFromHTML: true,
        html:                 "
You successfully unsubscribed from the channel '" + channel + "'
"
    });
});

streamListener.on('tweet', function(tweet) {
    var hashtags = tweet.entities.hashtags;
    var user_mentions = tweet.entities.user_mentions;
    var subscribers = {};

    // Iterate over all the hashtags in the tweet
    for(var i = 0; i < hashtags.length; i++) {
        // The Twitter API strips the hash
        var tag = '#' + hashtags[i].text;
        // We're tracking this hashtag
        if(streamListener.subscriptions[tag]) {
            var emails = streamListener.subscriptions[tag];
            for(var j = 0; j < emails.length; j++) {
                var email = emails[j];
                if(!subscribers[email]) {
                    subscribers[email] = [];
                }
                subscribers[email].push("[" + tag + "]");
            }
        }
    }

    // Iterate over all the user_mentions in the tweet
    for(var i = 0; i < user_mentions.length; i++) {
        // The Twitter API strips the at-sign
        var user = '@' + user_mentions[i].screen_name;
        // We're tracking this user
        if(streamListener.subscriptions[user]) {
            var emails = streamListener.subscriptions[user];
            for(var j = 0; j < emails.length; j++) {
                var email = emails[j];
                if(!subscribers[email]) {
                    subscribers[email] = [];
                }
                subscribers[email].push("[" + user + "]");
            }
        }
    }

    for(var subscriber in subscribers) {
        mailTransport.sendMail({
            from:                 "twailer@twailer.mstaessen.be",
            to:                   subscriber,
            subject:              subscribers[subscriber].join(' '),
            generateTextFromHTML: true,
            html:                 '
'
                                + '
' + tweet.text + '
— ' + tweet.user.name + ' (@' + tweet.user.screen_name + ') '
                                + '' + tweet.created_at + ''
                                + '
'
                                + ''
        });
        console.log("Sent mail to " + subscriber);
    }
});

/************************
 ****  Redis Client  ****
 ************************/

var client = Redis.createClient();

client.on('connect', function() {
    console.log("Successfully connected to redis server!");
});

client.on('subscribe', function(channel, count) {
    console.log("Successfully subscribed to " + channel);
});

client.on('message', function(channel, message) {
    var msg = JSON.parse(message)
    switch(channel) {
        case 'twailer.subscribe':
            console.log("Received 'subscribe to " + msg.channel + " message' from " + msg.email);
            streamListener.subscribe(msg.email, msg.channel);
            break;
        case 'twailer.unsubscribe':
            console.log("Received 'ubsubscribe from " + msg.channel + " message' from " + msg.email);
            streamListener.unsubscribe(msg.email, msg.channel);
            break;
    }
});

client.subscribe('twailer.subscribe');
client.subscribe('twailer.unsubscribe');
<commit_msg>Don't seem to learn the anonymous function stuff :D<commit_after>var Util           = require('util')
  , Redis          = require('redis')
  , NodeMailer     = require('nodemailer')
  , StreamListener = require('./stream-listener')
  , Subscriptions  = require('./subscriptions');

/**************************
 ****  Mail Transport  ****
 **************************/

var mailTransport  = NodeMailer.createTransport("SMTP");

/**************************
 ****  StreamListener  ****
 **************************/

var streamListener = new StreamListener(Subscriptions.restore());

streamListener.on('subscribe', function(email, channel) {
    Subscriptions.backup(streamListener.subscriptions);
});

streamListener.on('unsubscribe', function(email, channel) {
    Subscriptions.backup(streamListener.subscriptions);
});

streamListener.on('subscribe', function(email, channel) {
    // TODO: elaborate, use rendering engine
    mailTransport.sendMail({
        from:                 "twailer@twailer.mstaessen.be",
        to:                   email,
        subject:              "[" + channel + "] Subscription confirmation",
        generateTextFromHTML: true,
        html:                 "
You successfully subscribed to the channel '" + channel + "'
"
    });
});

streamListener.on('unsubscribe', function(email, channel) {
    // TODO: elaborate, use rendering engine
    mailTransport.sendMail({
        from:                 "twailer@twailer.mstaessen.be",
        to:                   email,
        subject:              "[" + channel + "] Subscription removal confirmation",
        generateTextFromHTML: true,
        html:                 "
You successfully unsubscribed from the channel '" + channel + "'
"
    });
});

streamListener.on('tweet', function(tweet) {
    var hashtags = tweet.entities.hashtags;
    var user_mentions = tweet.entities.user_mentions;
    var subscribers = {};

    // Iterate over all the hashtags in the tweet
    for(var i = 0; i < hashtags.length; i++) {
        // The Twitter API strips the hash
        var tag = '#' + hashtags[i].text;
        // We're tracking this hashtag
        if(streamListener.subscriptions[tag]) {
            var emails = streamListener.subscriptions[tag];
            for(var j = 0; j < emails.length; j++) {
                var email = emails[j];
                if(!subscribers[email]) {
                    subscribers[email] = [];
                }
                subscribers[email].push("[" + tag + "]");
            }
        }
    }

    // Iterate over all the user_mentions in the tweet
    for(var i = 0; i < user_mentions.length; i++) {
        // The Twitter API strips the at-sign
        var user = '@' + user_mentions[i].screen_name;
        // We're tracking this user
        if(streamListener.subscriptions[user]) {
            var emails = streamListener.subscriptions[user];
            for(var j = 0; j < emails.length; j++) {
                var email = emails[j];
                if(!subscribers[email]) {
                    subscribers[email] = [];
                }
                subscribers[email].push("[" + user + "]");
            }
        }
    }

    for(var subscriber in subscribers) {
        mailTransport.sendMail({
            from:                 "twailer@twailer.mstaessen.be",
            to:                   subscriber,
            subject:              subscribers[subscriber].join(' '),
            generateTextFromHTML: true,
            html:                 '
'
                                + '
' + tweet.text + '
— ' + tweet.user.name + ' (@' + tweet.user.screen_name + ') '
                                + '' + tweet.created_at + ''
                                + '
'
                                + ''
        });
        console.log("Sent mail to " + subscriber);
    }
});

/************************
 ****  Redis Client  ****
 ************************/

var client = Redis.createClient();

client.on('connect', function() {
    console.log("Successfully connected to redis server!");
});

client.on('subscribe', function(channel, count) {
    console.log("Successfully subscribed to " + channel);
});

client.on('message', function(channel, message) {
    var msg = JSON.parse(message)
    switch(channel) {
        case 'twailer.subscribe':
            console.log("Received 'subscribe to " + msg.channel + " message' from " + msg.email);
            streamListener.subscribe(msg.email, msg.channel);
            break;
        case 'twailer.unsubscribe':
            console.log("Received 'ubsubscribe from " + msg.channel + " message' from " + msg.email);
            streamListener.unsubscribe(msg.email, msg.channel);
            break;
    }
});

client.subscribe('twailer.subscribe');
client.subscribe('twailer.unsubscribe');
<|endoftext|>


<commit_before>;(function () {
    // already loaded
    if(window.CryptoProCodeAsync) {
        return;
    }

    //~ Consts -----------------------------------------------------------------------------------------
    var CONSTS = I18N_ERROR_LOAD_CADESPLUGIN = "Плагин cadesplugin не доступен";
    UNDEFINED = -1;

    //~ Variable -----------------------------------------------------------------------------------------
    var variable = {
        cadespluginState: 0,                // Состояние загрузки cadesplugin
        certs: [],                          // Список сертификатов
        debug: false,                        // Режим расширенного логирования
        error: undefined,                   // Последняя ошибка
        queue: []							// Очередь функций на выполнение при готовности плагина
    };

    //~ Constrction -----------------------------------------------------------------------------------------
    construction = function() {
        //Нужно проверить совместимость с версией утилит
        if (!main || main.utils.varsionMajor != 1) {
            variable.error = {code: 601, message: "Не поддерживается данная версия классса утилит"};
            throw new Error(variable.error.message);
        }
        if (variable.debug) {
            cadesplugin.set_log_level(cadesplugin.LOG_LEVEL_DEBUG);
        } else {
        	cadesplugin.set_log_level(cadesplugin.LOG_LEVEL_INFO);
        }
    };

    //~ Private methods -------------------------------------------------------------------------------------
    var callCallBack = function(callback, args) {
    	if (callback instanceof Function) {
			callback.call(window, args);
    	}
    };

    //~ Public methods --------------------------------------------------------------------------------------
    publicMethod = {

		/**
         * Получить возможную причину отказа
         */
        setDebugEnable: function(debug) {
            variable.debug = debug;
            if (variable.debug) {
                cadesplugin.set_log_level(cadesplugin.LOG_LEVEL_DEBUG);
            }
        },

        /**
         * Получить версию плагина.
         *
         * @return Объект с данными о плагине
         */
        getVersion: async function(callback, versionInit) {
            if (variable.debug) {
                console.log("CryptoProCodeAsync: Вызыван getVersion");
            }
            var version = main.utils.copyProperty(versionInit, {});

            try {
            	var oAbout = await cadesplugin.CreateObjectAsync("CAdESCOM.About");
            	console.log(oAbout);
            	var oVersion = await oAbout.PluginVersion;

            	version.csp = await oVersion.toString();
			} catch (e) {
				version.csp = cryptoProAdapter.handlerException(e);
				if (variable.debug) {
	                console.log(e);
	            }
			}

			callCallBack(callback, version);
        },

        /**
         * Загрузить список сертификатов
         */
        loadCerts: async function(callback, storeUser, storeName, storeMaxAllowed) {
        	var certsList = [];
            var cert;
            var isPk;
            var pk;
            var certPrivate;

            var oStore = await cadesplugin.CreateObjectAsync("CAdESCOM.Store");
            await oStore.Open();

            var allCerts = await oStore.Certificates;
            var certCnt = await allCerts.Count;
            for (var i = 1; i <= certCnt; i++) {
                try {
                    cert = await allCerts.Item(i);
                    if (variable.debug) {
                        console.log("CryptoProCodeAsync: запрашиваем сертификат с номером " + i);
                        console.log(cert);
                    }
                    isPk = await cert.HasPrivateKey();
                    if (isPk == true) {
                    	pk = await cert.PrivateKey;
                    	try {
                    		certPrivate = {
                            		ProviderName: await pk.ProviderName,
                            		ProviderType: await pk.ProviderType
                        	};
						} catch (e) {
							certPrivate = {
                            		ProviderName: cryptoProAdapter.handlerException(e),
                            		ProviderType: cryptoProAdapter.handlerException(e)
                        	};
						}

						try {
                    		certPrivate = main.utils.mergeProperty(certPrivate, {
                        			ContainerName: await pk.ContainerName,
                            		UniqueContainerName: await pk.UniqueContainerName
                        	});
						} catch (e) {
							certPrivate = main.utils.mergeProperty(certPrivate, {
                        			ContainerName: cryptoProAdapter.handlerException(e),
                            		UniqueContainerName: cryptoProAdapter.handlerException(e)
                        	});
						}
                    } else {
                    	certPrivate = {};
                    }

                    var validator = await cert.IsValid();
                    var isValid = await validator.Result;
                    cert = cryptoProAdapter.processing({
                    	IssuerName: await cert.IssuerName,
                    	PrivateKey: await certPrivate,
                    	SerialNumber: await cert.SerialNumber,
                    	SubjectName: await cert.SubjectName,
                    	Thumbprint: await cert.Thumbprint,
                    	ValidFromDate: await cert.ValidFromDate,
                    	ValidToDate: await cert.ValidToDate,
                    	Version: await cert.Version,
                    	IsValid: isValid
                    });

                    if (variable.debug) {
                        console.log("CryptoProCodeAsync: " + JSON.stringify(cert));
                    }
                    certsList.push(cert);
                } catch (e) {
                    var err = "Ошибка при получении сертификата: " + cryptoProAdapter.handlerException(e);
                    certsList.push({id: UNDEFINED, name: err});
                }
            }
            await oStore.Close();
            callCallBack(callback, certsList);
        },

        /**
         * Создаем подпись данных
         */
        createSign: async function(callback, certThumbprint, data, params) {
            if (!params) {
                params = {};
            }
            var isAddTimeStamp = !!params.isAddTimeStamp;
            var isBinary = !!params.isBinary;
            var isDocName = !!params.docName;

            // Ищем подпись
            var oStore = await cadesplugin.CreateObjectAsync("CAdESCOM.Store");
            await oStore.Open(params.storeUser, params.storeName, params.storeMaxAllowed);
            var oCertificates = await oStore.Certificates;
            var oCertFined = await oCertificates.Find(cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH, certThumbprint);
            if (await oCertFined.Count == 0) {
            	callCallBack(callback, ["Не удалось найти сертификат с названием " + certThumbprint]);
            	return;
            } else if (await oCertificates.Count > 1) {
            	callCallBack(callback, ["Не уникальное название сертификата " + certThumbprint]);
            	return;
            }
            var oCertificate = await oCertificates.Item(1);

            // Создаем подписанное сообщение
            // Создаем объект CAdESCOM.CPSigner
            var oSigner = await cadesplugin.CreateObjectAsync("CAdESCOM.CPSigner");
            await oSigner.propset_Certificate(oCertificate);
            await oSigner.propset_TSAAddress("http://cryptopro.ru/tsp/");

            // Создаем объект CAdESCOM.CadesSignedData
            var oSignedData = await cadesplugin.CreateObjectAsync("CAdESCOM.CadesSignedData");
            // Значение свойства ContentEncoding должно быть задано до заполнения свойства Content
            if (isBinary) {
            	// Данные будут перекодированы из Base64 в бинарный массив.
            	//oSignedData.ContentEncoding = cadesplugin.CADESCOM_BASE64_TO_BINARY;
            	await oSignedData.propset_ContentEncoding(cadesplugin.CADESCOM_BASE64_TO_BINARY);
            }
            await oSignedData.propset_Content(data);

            if (isAddTimeStamp) {
            	// Добавление информации о времени создания подписи
            	var Attribute = await cadesplugin.CreateObjectAsync("CADESCOM.CPAttribute");
            	await Attribute.propset_Name(cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME);
            	var oTimeNow = new Date();
            	await Attribute.propset_Value(main.utils.convert.convertDate(oTimeNow));
            	var authAttr2 = await oSigner.AuthenticatedAttributes2;
            	await authAttr2.Add(Attribute);
            }

            // Вычисляем значение подписи, подпись будет перекодирована в BASE64
            var sSignedMessage;
            try {
            	await oSigner.propset_Options(cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN); //Сохраняет полную цепочку.
            	sSignedMessage = await oSignedData.SignCades(oSigner, params.signType, true, cadesplugin.CADESCOM_ENCODE_BASE64);
            } catch (e) {
            	sSignedMessage = "Failed to create signature. Error: " + cadesplugin.getLastError(e);
            }
            callCallBack(callback, [sSignedMessage]);
        }
    };

    // init
    construction();
    window.CryptoProCodeAsync = publicMethod;
}());
<commit_msg>Исправлено получение количества найденых сертификатов<commit_after>;(function () {
    // already loaded
    if(window.CryptoProCodeAsync) {
        return;
    }

    //~ Consts -----------------------------------------------------------------------------------------
    var CONSTS = I18N_ERROR_LOAD_CADESPLUGIN = "Плагин cadesplugin не доступен";
    UNDEFINED = -1;

    //~ Variable -----------------------------------------------------------------------------------------
    var variable = {
        cadespluginState: 0,                // Состояние загрузки cadesplugin
        certs: [],                          // Список сертификатов
        debug: false,                        // Режим расширенного логирования
        error: undefined,                   // Последняя ошибка
        queue: []							// Очередь функций на выполнение при готовности плагина
    };

    //~ Constrction -----------------------------------------------------------------------------------------
    construction = function() {
        //Нужно проверить совместимость с версией утилит
        if (!main || main.utils.varsionMajor != 1) {
            variable.error = {code: 601, message: "Не поддерживается данная версия классса утилит"};
            throw new Error(variable.error.message);
        }
        if (variable.debug) {
            cadesplugin.set_log_level(cadesplugin.LOG_LEVEL_DEBUG);
        } else {
        	cadesplugin.set_log_level(cadesplugin.LOG_LEVEL_INFO);
        }
    };

    //~ Private methods -------------------------------------------------------------------------------------
    var callCallBack = function(callback, args) {
    	if (callback instanceof Function) {
			callback.call(window, args);
    	}
    };

    //~ Public methods --------------------------------------------------------------------------------------
    publicMethod = {

		/**
         * Получить возможную причину отказа
         */
        setDebugEnable: function(debug) {
            variable.debug = debug;
            if (variable.debug) {
                cadesplugin.set_log_level(cadesplugin.LOG_LEVEL_DEBUG);
            }
        },

        /**
         * Получить версию плагина.
         *
         * @return Объект с данными о плагине
         */
        getVersion: async function(callback, versionInit) {
            if (variable.debug) {
                console.log("CryptoProCodeAsync: Вызыван getVersion");
            }
            var version = main.utils.copyProperty(versionInit, {});

            try {
            	var oAbout = await cadesplugin.CreateObjectAsync("CAdESCOM.About");
            	console.log(oAbout);
            	var oVersion = await oAbout.PluginVersion;

            	version.csp = await oVersion.toString();
			} catch (e) {
				version.csp = cryptoProAdapter.handlerException(e);
				if (variable.debug) {
	                console.log(e);
	            }
			}

			callCallBack(callback, version);
        },

        /**
         * Загрузить список сертификатов
         */
        loadCerts: async function(callback, storeUser, storeName, storeMaxAllowed) {
        	var certsList = [];
            var cert;
            var isPk;
            var pk;
            var certPrivate;

            var oStore = await cadesplugin.CreateObjectAsync("CAdESCOM.Store");
            await oStore.Open();

            var allCerts = await oStore.Certificates;
            var certCnt = await allCerts.Count;
            for (var i = 1; i <= certCnt; i++) {
                try {
                    cert = await allCerts.Item(i);
                    if (variable.debug) {
                        console.log("CryptoProCodeAsync: запрашиваем сертификат с номером " + i);
                        console.log(cert);
                    }
                    isPk = await cert.HasPrivateKey();
                    if (isPk == true) {
                    	pk = await cert.PrivateKey;
                    	try {
                    		certPrivate = {
                            		ProviderName: await pk.ProviderName,
                            		ProviderType: await pk.ProviderType
                        	};
						} catch (e) {
							certPrivate = {
                            		ProviderName: cryptoProAdapter.handlerException(e),
                            		ProviderType: cryptoProAdapter.handlerException(e)
                        	};
						}

						try {
                    		certPrivate = main.utils.mergeProperty(certPrivate, {
                        			ContainerName: await pk.ContainerName,
                            		UniqueContainerName: await pk.UniqueContainerName
                        	});
						} catch (e) {
							certPrivate = main.utils.mergeProperty(certPrivate, {
                        			ContainerName: cryptoProAdapter.handlerException(e),
                            		UniqueContainerName: cryptoProAdapter.handlerException(e)
                        	});
						}
                    } else {
                    	certPrivate = {};
                    }

                    var validator = await cert.IsValid();
                    var isValid = await validator.Result;
                    cert = cryptoProAdapter.processing({
                    	IssuerName: await cert.IssuerName,
                    	PrivateKey: await certPrivate,
                    	SerialNumber: await cert.SerialNumber,
                    	SubjectName: await cert.SubjectName,
                    	Thumbprint: await cert.Thumbprint,
                    	ValidFromDate: await cert.ValidFromDate,
                    	ValidToDate: await cert.ValidToDate,
                    	Version: await cert.Version,
                    	IsValid: isValid
                    });

                    if (variable.debug) {
                        console.log("CryptoProCodeAsync: " + JSON.stringify(cert));
                    }
                    certsList.push(cert);
                } catch (e) {
                    var err = "Ошибка при получении сертификата: " + cryptoProAdapter.handlerException(e);
                    certsList.push({id: UNDEFINED, name: err});
                }
            }
            await oStore.Close();
            callCallBack(callback, certsList);
        },

        /**
         * Создаем подпись данных
         */
        createSign: async function(callback, certThumbprint, data, params) {
            if (!params) {
                params = {};
            }
            var isAddTimeStamp = !!params.isAddTimeStamp;
            var isBinary = !!params.isBinary;
            var isDocName = !!params.docName;

            // Ищем подпись
            var oStore = await cadesplugin.CreateObjectAsync("CAdESCOM.Store");
            await oStore.Open(params.storeUser, params.storeName, params.storeMaxAllowed);
            var oCertificates = await oStore.Certificates;
            var oCertFined = await oCertificates.Find(cadesplugin.CAPICOM_CERTIFICATE_FIND_SHA1_HASH, certThumbprint);
            var oCertFinedCount = await oCertFined.Count;
            if (oCertFinedCount == 0) {
            	callCallBack(callback, ["Не удалось найти сертификат с названием " + certThumbprint]);
            	return;
            } else if (oCertFinedCount > 1) {
            	callCallBack(callback, ["Не уникальное название сертификата " + certThumbprint]);
            	return;
            }
            var oCertificate = await oCertificates.Item(1);

            // Создаем подписанное сообщение
            // Создаем объект CAdESCOM.CPSigner
            var oSigner = await cadesplugin.CreateObjectAsync("CAdESCOM.CPSigner");
            await oSigner.propset_Certificate(oCertificate);
            await oSigner.propset_TSAAddress("http://cryptopro.ru/tsp/");

            // Создаем объект CAdESCOM.CadesSignedData
            var oSignedData = await cadesplugin.CreateObjectAsync("CAdESCOM.CadesSignedData");
            // Значение свойства ContentEncoding должно быть задано до заполнения свойства Content
            if (isBinary) {
            	// Данные будут перекодированы из Base64 в бинарный массив.
            	//oSignedData.ContentEncoding = cadesplugin.CADESCOM_BASE64_TO_BINARY;
            	await oSignedData.propset_ContentEncoding(cadesplugin.CADESCOM_BASE64_TO_BINARY);
            }
            await oSignedData.propset_Content(data);

            if (isAddTimeStamp) {
            	// Добавление информации о времени создания подписи
            	var Attribute = await cadesplugin.CreateObjectAsync("CADESCOM.CPAttribute");
            	await Attribute.propset_Name(cadesplugin.CAPICOM_AUTHENTICATED_ATTRIBUTE_SIGNING_TIME);
            	var oTimeNow = new Date();
            	await Attribute.propset_Value(main.utils.convert.convertDate(oTimeNow));
            	var authAttr2 = await oSigner.AuthenticatedAttributes2;
            	await authAttr2.Add(Attribute);
            }

            // Вычисляем значение подписи, подпись будет перекодирована в BASE64
            var sSignedMessage;
            try {
            	await oSigner.propset_Options(cadesplugin.CAPICOM_CERTIFICATE_INCLUDE_WHOLE_CHAIN); //Сохраняет полную цепочку.
            	sSignedMessage = await oSignedData.SignCades(oSigner, params.signType, true, cadesplugin.CADESCOM_ENCODE_BASE64);
            } catch (e) {
            	sSignedMessage = "Failed to create signature. Error: " + cadesplugin.getLastError(e);
            }
            callCallBack(callback, [sSignedMessage]);
        }
    };

    // init
    construction();
    window.CryptoProCodeAsync = publicMethod;
}());
<|endoftext|>


<commit_before>/**
 * @author Eberhard Graether / http://egraether.com/
 */

THREE.TrackballControls = function ( object, domElement ) {

	var _this = this;
	var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM: 4, TOUCH_PAN: 5 };

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	this.enabled = true;

	this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
	this.radius = ( this.screen.width + this.screen.height ) / 4;

	this.rotateSpeed = 1.0;
	this.zoomSpeed = 1.2;
	this.panSpeed = 0.3;

	this.noRotate = false;
	this.noZoom = false;
	this.noPan = false;

	this.staticMoving = false;
	this.dynamicDampingFactor = 0.2;

	this.minDistance = 0;
	this.maxDistance = Infinity;

	this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];

	// internals

	this.target = new THREE.Vector3();

	var lastPosition = new THREE.Vector3();

	var _state = STATE.NONE,
	_prevState = STATE.NONE,

	_eye = new THREE.Vector3(),

	_rotateStart = new THREE.Vector3(),
	_rotateEnd = new THREE.Vector3(),

	_zoomStart = new THREE.Vector2(),
	_zoomEnd = new THREE.Vector2(),

	_touchZoomDistanceStart = 0,
	_touchZoomDistanceEnd = 0,

	_panStart = new THREE.Vector2(),
	_panEnd = new THREE.Vector2();

	// for reset

	this.target0 = this.target.clone();
	this.position0 = this.object.position.clone();
	this.up0 = this.object.up.clone();

	// events

	var changeEvent = { type: 'change' };

	// methods

	this.handleResize = function () {

		this.screen.width = window.innerWidth;
		this.screen.height = window.innerHeight;

		this.screen.offsetLeft = 0;
		this.screen.offsetTop = 0;

		this.radius = ( this.screen.width + this.screen.height ) / 4;

	};

	this.handleEvent = function ( event ) {

		if ( typeof this[ event.type ] == 'function' ) {

			this[ event.type ]( event );

		}

	};

	this.getMouseOnScreen = function ( clientX, clientY ) {

		return new THREE.Vector2(
			( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
			( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
		);

	};

	this.getMouseProjectionOnBall = function ( clientX, clientY ) {

		var mouseOnBall = new THREE.Vector3(
			( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
			( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
			0.0
		);

		var length = mouseOnBall.length();

		if ( length > 1.0 ) {

			mouseOnBall.normalize();

		} else {

			mouseOnBall.z = Math.sqrt( 1.0 - length * length );

		}

		_eye.copy( _this.object.position ).sub( _this.target );

		var projection = _this.object.up.clone().setLength( mouseOnBall.y );
		projection.add( _this.object.up.clone().cross( _eye ).setLength( mouseOnBall.x ) );
		projection.add( _eye.setLength( mouseOnBall.z ) );

		return projection;

	};

	this.rotateCamera = function () {

		var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );

		if ( angle ) {

			var axis = ( new THREE.Vector3() ).crossVectors( _rotateStart, _rotateEnd ).normalize(),
				quaternion = new THREE.Quaternion();

			angle *= _this.rotateSpeed;

			quaternion.setFromAxisAngle( axis, -angle );

			_eye.applyQuaternion( quaternion );
			_this.object.up.applyQuaternion( quaternion );

			_rotateEnd.applyQuaternion( quaternion );

			if ( _this.staticMoving ) {

				_rotateStart.copy( _rotateEnd );

			} else {

				quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
				_rotateStart.applyQuaternion( quaternion );

			}

		}

	};

	this.zoomCamera = function () {

		if ( _state === STATE.TOUCH_ZOOM ) {

			var factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
			_touchZoomDistanceStart = _touchZoomDistanceEnd;
			_eye.multiplyScalar( factor );

		} else {

			var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;

			if ( factor !== 1.0 && factor > 0.0 ) {

				_eye.multiplyScalar( factor );

				if ( _this.staticMoving ) {

					_zoomStart.copy( _zoomEnd );

				} else {

					_zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;

				}

			}

		}

	};

	this.panCamera = function () {

		var mouseChange = _panEnd.clone().sub( _panStart );

		if ( mouseChange.lengthSq() ) {

			mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );

			var pan = _eye.clone().cross( _this.object.up ).setLength( mouseChange.x );
			pan.add( _this.object.up.clone().setLength( mouseChange.y ) );

			_this.object.position.add( pan );
			_this.target.add( pan );

			if ( _this.staticMoving ) {

				_panStart = _panEnd;

			} else {

				_panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );

			}

		}

	};

	this.checkDistances = function () {

		if ( !_this.noZoom || !_this.noPan ) {

			if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {

				_this.object.position.setLength( _this.maxDistance );

			}

			if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {

				_this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) );

			}

		}

	};

	this.update = function () {

		_eye.subVectors( _this.object.position, _this.target );

		if ( !_this.noRotate ) {

			_this.rotateCamera();

		}

		if ( !_this.noZoom ) {

			_this.zoomCamera();

		}

		if ( !_this.noPan ) {

			_this.panCamera();

		}

		_this.object.position.addVectors( _this.target, _eye );

		_this.checkDistances();

		_this.object.lookAt( _this.target );

		if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {

			_this.dispatchEvent( changeEvent );

			lastPosition.copy( _this.object.position );

		}

	};

	this.reset = function () {

		_state = STATE.NONE;
		_prevState = STATE.NONE;

		_this.target.copy( _this.target0 );
		_this.object.position.copy( _this.position0 );
		_this.object.up.copy( _this.up0 );

		_eye.subVectors( _this.object.position, _this.target );

		_this.object.lookAt( _this.target );

		_this.dispatchEvent( changeEvent );

		lastPosition.copy( _this.object.position );

	};

	// listeners

	function keydown( event ) {

		if ( _this.enabled === false ) return;

		window.removeEventListener( 'keydown', keydown );

		_prevState = _state;

		if ( _state !== STATE.NONE ) {

			return;

		} else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {

			_state = STATE.ROTATE;

		} else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {

			_state = STATE.ZOOM;

		} else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {

			_state = STATE.PAN;

		}

	}

	function keyup( event ) {

		if ( _this.enabled === false ) return;

		_state = _prevState;

		window.addEventListener( 'keydown', keydown, false );

	}

	function mousedown( event ) {

		if ( _this.enabled === false ) return;

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

		if ( _state === STATE.NONE ) {

			_state = event.button;

		}

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		}

		document.addEventListener( 'mousemove', mousemove, false );
		document.addEventListener( 'mouseup', mouseup, false );

	}

	function mousemove( event ) {

		if ( _this.enabled === false ) return;

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

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		}

	}

	function mouseup( event ) {

		if ( _this.enabled === false ) return;

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

		_state = STATE.NONE;

		document.removeEventListener( 'mousemove', mousemove );
		document.removeEventListener( 'mouseup', mouseup );

	}

	function mousewheel( event ) {

		if ( _this.enabled === false ) return;

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

		var delta = 0;

		if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

			delta = event.wheelDelta / 40;

		} else if ( event.detail ) { // Firefox

			delta = - event.detail / 3;

		}

		_zoomStart.y += delta * 0.01;

	}

	function touchstart( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_state = STATE.TOUCH_ROTATE;
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_state = STATE.TOUCH_ZOOM;
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
				break;

			case 3:
				_state = STATE.TOUCH_PAN;
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchmove( event ) {

		if ( _this.enabled === false ) return;

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

		switch ( event.touches.length ) {

			case 1:
				_rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy )
				break;

			case 3:
				_panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchend( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
				break;

			case 3:
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

		}

		_state = STATE.NONE;

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	this.domElement.addEventListener( 'mousedown', mousedown, false );

	// this.domElement.addEventListener( 'mousewheel', mousewheel, false );
	// this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox

	this.domElement.addEventListener( 'touchstart', touchstart, false );
	this.domElement.addEventListener( 'touchend', touchend, false );
	this.domElement.addEventListener( 'touchmove', touchmove, false );

	window.addEventListener( 'keydown', keydown, false );
	window.addEventListener( 'keyup', keyup, false );

	this.handleResize();

};

THREE.TrackballControls.prototype = Object.create( THREE.EventDispatcher.prototype );
<commit_msg>re-enabled scrollwheel interaction<commit_after>/**
 * @author Eberhard Graether / http://egraether.com/
 */

THREE.TrackballControls = function ( object, domElement ) {

	var _this = this;
	var STATE = { NONE: -1, ROTATE: 0, ZOOM: 1, PAN: 2, TOUCH_ROTATE: 3, TOUCH_ZOOM: 4, TOUCH_PAN: 5 };

	this.object = object;
	this.domElement = ( domElement !== undefined ) ? domElement : document;

	// API

	this.enabled = true;

	this.screen = { width: 0, height: 0, offsetLeft: 0, offsetTop: 0 };
	this.radius = ( this.screen.width + this.screen.height ) / 4;

	this.rotateSpeed = 1.0;
	this.zoomSpeed = 1.2;
	this.panSpeed = 0.3;

	this.noRotate = false;
	this.noZoom = false;
	this.noPan = false;

	this.staticMoving = false;
	this.dynamicDampingFactor = 0.2;

	this.minDistance = 0;
	this.maxDistance = Infinity;

	this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];

	// internals

	this.target = new THREE.Vector3();

	var lastPosition = new THREE.Vector3();

	var _state = STATE.NONE,
	_prevState = STATE.NONE,

	_eye = new THREE.Vector3(),

	_rotateStart = new THREE.Vector3(),
	_rotateEnd = new THREE.Vector3(),

	_zoomStart = new THREE.Vector2(),
	_zoomEnd = new THREE.Vector2(),

	_touchZoomDistanceStart = 0,
	_touchZoomDistanceEnd = 0,

	_panStart = new THREE.Vector2(),
	_panEnd = new THREE.Vector2();

	// for reset

	this.target0 = this.target.clone();
	this.position0 = this.object.position.clone();
	this.up0 = this.object.up.clone();

	// events

	var changeEvent = { type: 'change' };

	// methods

	this.handleResize = function () {

		this.screen.width = window.innerWidth;
		this.screen.height = window.innerHeight;

		this.screen.offsetLeft = 0;
		this.screen.offsetTop = 0;

		this.radius = ( this.screen.width + this.screen.height ) / 4;

	};

	this.handleEvent = function ( event ) {

		if ( typeof this[ event.type ] == 'function' ) {

			this[ event.type ]( event );

		}

	};

	this.getMouseOnScreen = function ( clientX, clientY ) {

		return new THREE.Vector2(
			( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
			( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
		);

	};

	this.getMouseProjectionOnBall = function ( clientX, clientY ) {

		var mouseOnBall = new THREE.Vector3(
			( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
			( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
			0.0
		);

		var length = mouseOnBall.length();

		if ( length > 1.0 ) {

			mouseOnBall.normalize();

		} else {

			mouseOnBall.z = Math.sqrt( 1.0 - length * length );

		}

		_eye.copy( _this.object.position ).sub( _this.target );

		var projection = _this.object.up.clone().setLength( mouseOnBall.y );
		projection.add( _this.object.up.clone().cross( _eye ).setLength( mouseOnBall.x ) );
		projection.add( _eye.setLength( mouseOnBall.z ) );

		return projection;

	};

	this.rotateCamera = function () {

		var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );

		if ( angle ) {

			var axis = ( new THREE.Vector3() ).crossVectors( _rotateStart, _rotateEnd ).normalize(),
				quaternion = new THREE.Quaternion();

			angle *= _this.rotateSpeed;

			quaternion.setFromAxisAngle( axis, -angle );

			_eye.applyQuaternion( quaternion );
			_this.object.up.applyQuaternion( quaternion );

			_rotateEnd.applyQuaternion( quaternion );

			if ( _this.staticMoving ) {

				_rotateStart.copy( _rotateEnd );

			} else {

				quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
				_rotateStart.applyQuaternion( quaternion );

			}

		}

	};

	this.zoomCamera = function () {

		if ( _state === STATE.TOUCH_ZOOM ) {

			var factor = _touchZoomDistanceStart / _touchZoomDistanceEnd;
			_touchZoomDistanceStart = _touchZoomDistanceEnd;
			_eye.multiplyScalar( factor );

		} else {

			var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;

			if ( factor !== 1.0 && factor > 0.0 ) {

				_eye.multiplyScalar( factor );

				if ( _this.staticMoving ) {

					_zoomStart.copy( _zoomEnd );

				} else {

					_zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;

				}

			}

		}

	};

	this.panCamera = function () {

		var mouseChange = _panEnd.clone().sub( _panStart );

		if ( mouseChange.lengthSq() ) {

			mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );

			var pan = _eye.clone().cross( _this.object.up ).setLength( mouseChange.x );
			pan.add( _this.object.up.clone().setLength( mouseChange.y ) );

			_this.object.position.add( pan );
			_this.target.add( pan );

			if ( _this.staticMoving ) {

				_panStart = _panEnd;

			} else {

				_panStart.add( mouseChange.subVectors( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );

			}

		}

	};

	this.checkDistances = function () {

		if ( !_this.noZoom || !_this.noPan ) {

			if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {

				_this.object.position.setLength( _this.maxDistance );

			}

			if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {

				_this.object.position.addVectors( _this.target, _eye.setLength( _this.minDistance ) );

			}

		}

	};

	this.update = function () {

		_eye.subVectors( _this.object.position, _this.target );

		if ( !_this.noRotate ) {

			_this.rotateCamera();

		}

		if ( !_this.noZoom ) {

			_this.zoomCamera();

		}

		if ( !_this.noPan ) {

			_this.panCamera();

		}

		_this.object.position.addVectors( _this.target, _eye );

		_this.checkDistances();

		_this.object.lookAt( _this.target );

		if ( lastPosition.distanceToSquared( _this.object.position ) > 0 ) {

			_this.dispatchEvent( changeEvent );

			lastPosition.copy( _this.object.position );

		}

	};

	this.reset = function () {

		_state = STATE.NONE;
		_prevState = STATE.NONE;

		_this.target.copy( _this.target0 );
		_this.object.position.copy( _this.position0 );
		_this.object.up.copy( _this.up0 );

		_eye.subVectors( _this.object.position, _this.target );

		_this.object.lookAt( _this.target );

		_this.dispatchEvent( changeEvent );

		lastPosition.copy( _this.object.position );

	};

	// listeners

	function keydown( event ) {

		if ( _this.enabled === false ) return;

		window.removeEventListener( 'keydown', keydown );

		_prevState = _state;

		if ( _state !== STATE.NONE ) {

			return;

		} else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {

			_state = STATE.ROTATE;

		} else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {

			_state = STATE.ZOOM;

		} else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {

			_state = STATE.PAN;

		}

	}

	function keyup( event ) {

		if ( _this.enabled === false ) return;

		_state = _prevState;

		window.addEventListener( 'keydown', keydown, false );

	}

	function mousedown( event ) {

		if ( _this.enabled === false ) return;

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

		if ( _state === STATE.NONE ) {

			_state = event.button;

		}

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		}

		document.addEventListener( 'mousemove', mousemove, false );
		document.addEventListener( 'mouseup', mouseup, false );

	}

	function mousemove( event ) {

		if ( _this.enabled === false ) return;

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

		if ( _state === STATE.ROTATE && !_this.noRotate ) {

			_rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );

		} else if ( _state === STATE.ZOOM && !_this.noZoom ) {

			_zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		} else if ( _state === STATE.PAN && !_this.noPan ) {

			_panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );

		}

	}

	function mouseup( event ) {

		if ( _this.enabled === false ) return;

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

		_state = STATE.NONE;

		document.removeEventListener( 'mousemove', mousemove );
		document.removeEventListener( 'mouseup', mouseup );

	}

	function mousewheel( event ) {

		if ( _this.enabled === false ) return;

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

		var delta = 0;

		if ( event.wheelDelta ) { // WebKit / Opera / Explorer 9

			delta = event.wheelDelta / 40;

		} else if ( event.detail ) { // Firefox

			delta = - event.detail / 3;

		}

		_zoomStart.y += delta * 0.01;

	}

	function touchstart( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_state = STATE.TOUCH_ROTATE;
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_state = STATE.TOUCH_ZOOM;
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = _touchZoomDistanceStart = Math.sqrt( dx * dx + dy * dy );
				break;

			case 3:
				_state = STATE.TOUCH_PAN;
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchmove( event ) {

		if ( _this.enabled === false ) return;

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

		switch ( event.touches.length ) {

			case 1:
				_rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				var dx = event.touches[ 0 ].pageX - event.touches[ 1 ].pageX;
				var dy = event.touches[ 0 ].pageY - event.touches[ 1 ].pageY;
				_touchZoomDistanceEnd = Math.sqrt( dx * dx + dy * dy )
				break;

			case 3:
				_panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			default:
				_state = STATE.NONE;

		}

	}

	function touchend( event ) {

		if ( _this.enabled === false ) return;

		switch ( event.touches.length ) {

			case 1:
				_rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

			case 2:
				_touchZoomDistanceStart = _touchZoomDistanceEnd = 0;
				break;

			case 3:
				_panStart = _panEnd = _this.getMouseOnScreen( event.touches[ 0 ].pageX, event.touches[ 0 ].pageY );
				break;

		}

		_state = STATE.NONE;

	}

	this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );

	this.domElement.addEventListener( 'mousedown', mousedown, false );

	this.domElement.addEventListener( 'mousewheel', mousewheel, false );
	this.domElement.addEventListener( 'DOMMouseScroll', mousewheel, false ); // firefox

	this.domElement.addEventListener( 'touchstart', touchstart, false );
	this.domElement.addEventListener( 'touchend', touchend, false );
	this.domElement.addEventListener( 'touchmove', touchmove, false );

	window.addEventListener( 'keydown', keydown, false );
	window.addEventListener( 'keyup', keyup, false );

	this.handleResize();

};

THREE.TrackballControls.prototype = Object.create( THREE.EventDispatcher.prototype );
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.currentUserRole = ko.observable();
    gvm.oldUserRole = ko.observable();
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);

    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

    getUserPermission();
}

function getUserPermission(){
    $.ajax({
        type: "POST",
        url: "/api/getUserRolesById/" + viewModel.edituserid,
        success: function(data) {
            if(data == null){
                viewModel.oldUserRole == "GUEST null";
            }

            if (data[0] == "GUEST" && data[0] != null){
                viewModel.oldUserRole == "GUEST 0";
            }
            if (data[4] == "STUDENT" && data[4] != null){
                viewModel.oldUserRole == "STUDENT";
            }
            if (data[3] == "USER" && data[3] != null){
                viewModel.oldUserRole == "USER";
            }
            if (data[2] == "SUPERUSER" && data[2] != null){
                viewModel.oldUserRole == "SUPERUSER";
            }

            alert(viewModel.oldUserRole());
            return data;
        },
        error: function() {
            alert("Error while getting user info, please contact your administrator");
        }
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    var role = viewModel.currentUserRole();
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function User(id, username, firstname, lastname, status, permissions) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observableArray(permissions),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<commit_msg>Load current permission user edit<commit_after>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.currentUserRole = ko.observable();
    gvm.oldUserRole = ko.observable();
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);

    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

    getUserPermission();
}

function getUserPermission(){
    $.ajax({
        type: "POST",
        url: "/api/getUserRolesById/" + viewModel.edituserid,
        success: function(data) {
            if(data == null){
                viewModel.oldUserRole == "GUEST null";
            }

            if (data[0] == "GUEST" && data[0] != null){
                viewModel.oldUserRole == "GUEST 0";
            }
            if (data[4] == "STUDENT" && data[4] != null){
                viewModel.oldUserRole == "STUDENT";
            }
            if (data[3] == "USER" && data[3] != null){
                viewModel.oldUserRole == "USER";
            }
            if (data[2] == "SUPERUSER" && data[2] != null){
                viewModel.oldUserRole == "SUPERUSER";
            }

            alert(viewModel.oldUserRole);
            return data;
        },
        error: function() {
            alert("Error while getting user info, please contact your administrator");
        }
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    var role = viewModel.currentUserRole();
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function User(id, username, firstname, lastname, status, permissions) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observableArray(permissions),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.selectedPermission = ko.observable();
    gvm.currentUserRole = ko.observable();
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);

    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

    $(document).ready(
        function(){
            var theValue = getUserPermission();
            console.log(theValue);
            theValue.each(function(item){
               if(item == "GUEST"){
                   $('option[value=' + theValue + ']')
                       .attr('selected',true);
               }
            });

            if(theValue[0] == "GUEST"){

            }
        });
}

function getUserPermission(){
    $.ajax({
        type: "POST",
        url: "/api/getUserRolesById/" + viewModel.edituserid,
        success: function(data) {

            viewModel.currentUserRole = data;
            return data;
        },
        error: function() {
            alert("Error while getting user info, please contact your administrator");
        }
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    var role = viewModel.selectedPermission();
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });

        GetPermission();
    });
}

function User(id, username, firstname, lastname, status, permissions) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observableArray(permissions),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<commit_msg>Load current permission user edit<commit_after>function pageViewModel(gvm) {
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("AdminEditPage");}, gvm);
    gvm.pageHeaderEditUser = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserEditTitle");}, gvm);

    gvm.edituserid = $("#usereditHeader").data('value');

    gvm.loggedinuser = ko.observable();

    getLoggedInUser();

    gvm.userName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserName");}, gvm);
    gvm.firstName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Firstname");}, gvm);
    gvm.lastName = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Lastname");}, gvm);
    gvm.userStatus = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("UserStatus");}, gvm);

    gvm.permissionRole = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionRole");}, gvm);
    gvm.permissionDescription = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("PermissionDescription");}, gvm);

    gvm.selectedPermission = ko.observable();
    gvm.currentUserRole = ko.observable();
    gvm.availablePermissions = ko.observableArray(['GUEST', 'STUDENT', 'USER', 'SUPERUSER']);

    gvm.rights = ko.observableArray([]);
    gvm.allRights = ko.observableArray([]);
    gvm.userRights = ko.observableArray([]);
    gvm.user = ko.observableArray([]);

    gvm.updateUser = function(user)
    {
        gvm.user.push(user);
    },

    gvm.updatePermissions = function(permission)
    {
        gvm.rights.push(permission);
    },

    gvm.updateAllPermissions = function(permission)
    {
        gvm.allRights.push(permission);
    },

    gvm.removeUser = function(user) {
        gvm.user.remove(user);
        removeUser(user);
    },

    gvm.clearStructure = function() {
        gvm.rights.destroyAll();
        gvm.user.destroyAll();
    }
}

function initPage() {
    getAllUserDataById(viewModel.edituserid);

    $('#userEditForm').on('submit', function(e)
    {
        e.preventDefault();

        if(viewModel.loggedinuser != viewModel.edituserid)
        {
            saveChanges();
            saveUserPermissions();
        } else {
            saveChanges();
        }
    });

    $(document).ready(
        function(){
            var theValue = getUserPermission();
            console.log(theValue);
            theValue.each(function(item){
               if(item == "GUEST"){
                   $('option[value=' + theValue + ']')
                       .attr('selected',true);
               }
            });

            if(theValue[0] == "GUEST"){

            }
        });
}

function getUserPermission(){
    $.ajax({
        type: "POST",
        url: "/api/getUserRolesById/" + viewModel.edituserid,
        success: function(data) {

            viewModel.currentUserRole = data;
            return data;
        },
        error: function() {
            alert("Error while getting user info, please contact your administrator");
        }
    });
}

function getLoggedInUser(){
    $.getJSON("/api/loggedinuser", function(data){
        viewModel.loggedinuser = data;
    });
}

function saveChanges(){
    saveUserEdits(viewModel.edituserid);
}

function saveUserEdits(id){
    $.ajax({
        type: "POST",
        url: "/api/saveedit/" + id,
        data: $('#userEditForm').serialize(),
        success: function() {
        },
        error: function() {
            console.log("Error saving user changes");
        }
    });
}

function saveUserPermissions(){
    var role = viewModel.selectedPermission();
    var permissions = "GUEST ";

    if(role == 'STUDENT' || role == 'USER' || role == 'SUPERUSER'){
        permissions += "STUDENT ";
        if(role == 'USER' || role == 'SUPERUSER'){
            permissions += "USER ";
            if(role == 'SUPERUSER'){
                permissions += "SUPERUSER";
            }
        }
    }

    //SAVE NEW PERMISSIONS
    $.ajax({
        type: "POST",
        url: "/api/addrole/" + viewModel.edituserid,
        data: { 'permissions': permissions },
        success: function() {
            alert('Changes saved correctly');
        },
        error: function() {
            alert('Error saving user. Please contact the Administrator');
        }
    });
}

function getAllUserDataById(edituserid){
    $.getJSON("/api/edituser/" + edituserid, function(data)
    {
        var addedUsername = "";
        $.each(data, function(i, item){
            var current = item.username;

            $.each(data, function(i, item)
            {
                if(item.username == current && addedUsername != current){
                    viewModel.updatePermissions(item.role)
                }
            });

            if (addedUsername != current) {
                addedUsername = current;
                viewModel.updateUser(new User(item.userid, item.username, item.firstname, item.lastname, item.status, viewModel.rights()));
            }
        });
    });
}

function User(id, username, firstname, lastname, status, permissions) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        firstname: ko.observable(firstname),
        lastname: ko.observable(lastname),
        status: ko.observable(status),
        permissions: ko.observableArray(permissions),
        userStatuses: ko.observableArray(['ACTIVE', 'DISABLED']),

        removeThisUser: function() {
            if(confirm('Are you sure you want to remove this user?'))
            {
                viewModel.removeUser(this);
            }
        },

        changeStatus: function() {
            if (this.status() == "ACTIVE"){
                this.status("DISABLED");
            } else if (this.status() == "DISABLED") {
                this.status("ACTIVE");
            } else if (this.status() == "WAIT_ACTIVATION") {
                this.status("ACTIVE");
            }
            updateUserStatus(this);
        }
    };
}<|endoftext|>


<commit_before>var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('angularjs homepage todo list', function() {
  it('should add a todo', function() {
    browser.get('http://localhost:1234');
  });
});
<commit_msg>Added useless (but basic) test<commit_after>var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');

chai.use(chaiAsPromised);
var expect = chai.expect;

describe('polls CRUD cycle', function() {
  describe('If I go to home page', function() {
    browser.get('http://localhost:1234');
  });

  describe('And I create a new poll', function() {
    values = ['Cat', 'Dog', 'Elephant', 'Crocodile']
    element(by.model('ctrl.text')).sendKeys('What is your favourite pet?');

    for (var i = 0; i < values.length; i++)
    {
      element.all(by.model('ctrl.choices[$index]')).get(i).sendKeys(values[i]);
      element.all(by.css('.form-group .choiceLine .btn')).get(i).click();
    }

    element(by.buttonText('Create')).click();
  });

  it('Should have a nasino', function(){
    expect(true).toBe(true);
  });
});
<|endoftext|>


<commit_before>/* TINY SORT */
(function (e) { var a = false, g = null, f = parseFloat, b = /(\d+\.?\d*)$/g; e.tinysort = { id: "TinySort", version: "1.2.18", copyright: "Copyright (c) 2008-2012 Ron Valstar", uri: "http://tinysort.sjeiti.com/", licenced: { MIT: "http://www.opensource.org/licenses/mit-license.php", GPL: "http://www.gnu.org/licenses/gpl.html" }, defaults: { order: "asc", attr: g, data: g, useVal: a, place: "start", returns: a, cases: a, forceStrings: a, sortFunction: g } }; e.fn.extend({ tinysort: function (m, h) { if (m && typeof (m) != "string") { h = m; m = g } var n = e.extend({}, e.tinysort.defaults, h), s, B = this, x = e(this).length, C = {}, p = !(!m || m == ""), q = !(n.attr === g || n.attr == ""), w = n.data !== g, j = p && m[0] == ":", k = j ? B.filter(m) : B, r = n.sortFunction, v = n.order == "asc" ? 1 : -1, l = []; if (!r) { r = n.order == "rand" ? function () { return Math.random() < 0.5 ? 1 : -1 } : function (F, E) { var i = !n.cases ? d(F.s) : F.s, K = !n.cases ? d(E.s) : E.s; if (!n.forceStrings) { var H = i.match(b), G = K.match(b); if (H && G) { var J = i.substr(0, i.length - H[0].length), I = K.substr(0, K.length - G[0].length); if (J == I) { i = f(H[0]); K = f(G[0]) } } } return v * (i < K ? -1 : (i > K ? 1 : 0)) } } B.each(function (G, H) { var I = e(H), E = p ? (j ? k.filter(H) : I.find(m)) : I, J = w ? E.data(n.data) : (q ? E.attr(n.attr) : (n.useVal ? E.val() : E.text())), F = I.parent(); if (!C[F]) { C[F] = { s: [], n: [] } } if (E.length > 0) { C[F].s.push({ s: J, e: I, n: G }) } else { C[F].n.push({ e: I, n: G }) } }); for (s in C) { C[s].s.sort(r) } for (s in C) { var y = C[s], A = [], D = x, u = [0, 0], z; switch (n.place) { case "first": e.each(y.s, function (E, F) { D = Math.min(D, F.n) }); break; case "org": e.each(y.s, function (E, F) { A.push(F.n) }); break; case "end": D = y.n.length; break; default: D = 0 } for (z = 0; z < x; z++) { var o = c(A, z) ? !a : z >= D && z < D + y.s.length, t = (o ? y.s : y.n)[u[o ? 0 : 1]].e; t.parent().append(t); if (o || !n.returns) { l.push(t.get(0)) } u[o ? 0 : 1]++ } } return B.pushStack(l) } }); function d(h) { return h && h.toLowerCase ? h.toLowerCase() : h } function c(j, m) { for (var k = 0, h = j.length; k < h; k++) { if (j[k] == m) { return !a } } return a } e.fn.TinySort = e.fn.Tinysort = e.fn.tsort = e.fn.tinysort })(jQuery);

(function ($) {

  var $document = $(document),
      bsSort = [];

  $.bootstrapSortable = function () {
    // set attributes needed for sorting
    $('table.sortable').each(function () {
      var $this = $(this);
      $this.find('thead th').each(function (index) { $(this).attr('data-sortkey', index); });
      $this.find('th,td').each(function () { var $this = $(this); $this.attr('data-value', $this.text()); });
    });
  };

  // add click event to table header
  $document.on('click', 'table.sortable thead th', function (e) {
    var $this = $(this), $table = $this.parents('table.sortable');

    // update arrow icon
    $table.find('span.arrow').remove();
    $this.append('');

    // sort direction
    var nr = $this.attr('data-sortkey');
    bsSort[nr] = bsSort[nr] == 'asc' ? 'desc' : 'asc';
    if (bsSort[nr] == 'desc') { $this.find('span.arrow').addClass('up'); }

    // sort rows
    var rows = $table.find('tbody tr');
    rows.tsort('td:eq(' + nr + ')', { order: bsSort[nr], attr: 'data-value' });
  });

  // Initialise on DOM ready
  $($.bootstrapSortable);

}(jQuery));
<commit_msg>Fixed issue with sorting numbers<commit_after>/* TINY SORT modified according to this https://github.com/Sjeiti/TinySort/pull/51*/
(function (e, t) { function h(e) { return e && e.toLowerCase ? e.toLowerCase() : e } function p(e, t) { for (var r = 0, i = e.length; r < i; r++) if (e[r] == t) return !n; return n } var n = !1, r = null, i = parseFloat, s = Math.min, o = /(-?\d+\.?\d*)$/g, u = /(\d+\.?\d*)$/g, a = [], f = [], l = function (e) { return typeof e == "string" }, c = Array.prototype.indexOf || function (e) { var t = this.length, n = Number(arguments[1]) || 0; n = n < 0 ? Math.ceil(n) : Math.floor(n); if (n < 0) n += t; for (; n < t; n++) { if (n in this && this[n] === e) return n } return -1 }; e.tinysort = { id: "TinySort", version: "1.5.2", copyright: "Copyright (c) 2008-2013 Ron Valstar", uri: "http://tinysort.sjeiti.com/", licensed: { MIT: "http://www.opensource.org/licenses/mit-license.php", GPL: "http://www.gnu.org/licenses/gpl.html" }, plugin: function () { var e = function (e, t) { a.push(e); f.push(t) }; e.indexOf = c; return e } (), defaults: { order: "asc", attr: r, data: r, useVal: n, place: "start", returns: n, cases: n, forceStrings: n, ignoreDashes: n, sortFunction: r} }; e.fn.extend({ tinysort: function () { var d, v, m = this, g = [], y = [], b = [], w = [], E = 0, S, x = [], T = [], N = function (t) { e.each(a, function (e, n) { n.call(n, t) }) }, C = function (t, r) { var s = 0; if (E !== 0) E = 0; while (s === 0 && E < S) { var a = w[E], c = a.oSettings, p = c.ignoreDashes ? u : o; N(c); if (c.sortFunction) { s = c.sortFunction(t, r) } else if (c.order == "rand") { s = Math.random() < .5 ? 1 : -1 } else { var d = n, v = !c.cases ? h(t.s[E]) : t.s[E], m = !c.cases ? h(r.s[E]) : r.s[E]; v = v.replace(/^\s*/i, "").replace(/\s*$/i, ""); m = m.replace(/^\s*/i, "").replace(/\s*$/i, ""); if (!A.forceStrings) { var g = l(v) ? v && v.match(p) : n, y = l(m) ? m && m.match(p) : n; if (g && y) { var b = v.substr(0, v.length - g[0].length), x = m.substr(0, m.length - y[0].length); if (b == x) { d = !n; v = i(g[0]); m = i(y[0]) } } } s = a.iAsc * (v < m ? -1 : v > m ? 1 : 0) } e.each(f, function (e, t) { s = t.call(t, d, v, m, s) }); if (s === 0) E++ } return s }; for (d = 0, v = arguments.length; d < v; d++) { var k = arguments[d]; if (l(k)) { if (x.push(k) - 1 > T.length) T.length = x.length - 1 } else { if (T.push(k) > x.length) x.length = T.length } } if (x.length > T.length) T.length = x.length; S = x.length; if (S === 0) { S = x.length = 1; T.push({}) } for (d = 0, v = S; d < v; d++) { var L = x[d], A = e.extend({}, e.tinysort.defaults, T[d]), O = !(!L || L == ""), M = O && L[0] == ":"; w.push({ sFind: L, oSettings: A, bFind: O, bAttr: !(A.attr === r || A.attr == ""), bData: A.data !== r, bFilter: M, $Filter: M ? m.filter(L) : m, fnSort: A.sortFunction, iAsc: A.order == "asc" ? 1 : -1 }) } m.each(function (n, r) { var i = e(r), s = i.parent().get(0), o, u = []; for (j = 0; j < S; j++) { var a = w[j], f = a.bFind ? a.bFilter ? a.$Filter.filter(r) : i.find(a.sFind) : i; u.push(a.bData ? f.data(a.oSettings.data) : a.bAttr ? f.attr(a.oSettings.attr) : a.oSettings.useVal ? f.val() : f.text()); if (o === t) o = f } var l = c.call(b, s); if (l < 0) { l = b.push(s) - 1; y[l] = { s: [], n: []} } if (o.length > 0) y[l].s.push({ s: u, e: i, n: n }); else y[l].n.push({ e: i, n: n }) }); e.each(y, function (e, t) { t.s.sort(C) }); e.each(y, function (t, r) { var i = r.s.length, o = [], u = i, a = [0, 0]; switch (A.place) { case "first": e.each(r.s, function (e, t) { u = s(u, t.n) }); break; case "org": e.each(r.s, function (e, t) { o.push(t.n) }); break; case "end": u = r.n.length; break; default: u = 0 } for (d = 0; d = u && d < u + r.s.length, l = (f ? r.s : r.n)[a[f ? 0 : 1]].e; l.parent().append(l); if (f || !A.returns) g.push(l.get(0)); a[f ? 0 : 1]++ } }); m.length = 0; Array.prototype.push.apply(m, g); return m } }); e.fn.TinySort = e.fn.Tinysort = e.fn.tsort = e.fn.tinysort })(jQuery)

(function ($) {

  var $document = $(document),
      bsSort = [];

  $.bootstrapSortable = function () {
    // set attributes needed for sorting
    $('table.sortable').each(function () {
      var $this = $(this);
      $this.find('thead th').each(function (index) { $(this).attr('data-sortkey', index); });
      $this.find('th,td').each(function () { var $this = $(this); $this.attr('data-value', $this.text()); });
    });
  };

  // add click event to table header
  $document.on('click', 'table.sortable thead th', function (e) {
    var $this = $(this), $table = $this.parents('table.sortable');

    // update arrow icon
    $table.find('span.arrow').remove();
    $this.append('');

    // sort direction
    var nr = $this.attr('data-sortkey');
    bsSort[nr] = bsSort[nr] == 'asc' ? 'desc' : 'asc';
    if (bsSort[nr] == 'desc') { $this.find('span.arrow').addClass('up'); }

    // sort rows
    var rows = $table.find('tbody tr');
    rows.tsort('td:eq(' + nr + ')', { order: bsSort[nr], attr: 'data-value' });
  });

  // Initialise on DOM ready
  $($.bootstrapSortable);

}(jQuery));
<|endoftext|>