<commit_before>THREE.TRKLoader = function() {};

Object.assign( THREE.TRKLoader.prototype, THREE.EventDispatcher.prototype, {

    load: function(url, onLoad, onProgress, onError) {
        window.console.log(url, onLoad, onProgress, onError);

        var scope = this;
        var xhr = new XMLHttpRequest();

        function onloaded(event) {
            if (event.target.status === 200 || event.target.status === 0) {
                var geometry = scope.parse(event.target.response || event.target.responseText);
                scope.dispatchEvent({
                    type: 'load',
                    content: geometry,
                });
                if (onLoad) {
                    onLoad(geometry);
                }
            } else {
                scope.dispatchEvent({
                    type: 'error',
                    message: 'Couldn\'t load URL [' + url + ']',
                    response: event.target.statusText,
                });
            }
        }

        xhr.addEventListener('load', onloaded, false);

        xhr.addEventListener('progress', function(event) {
            scope.dispatchEvent({
                type: 'progress',
                loaded: event.loaded,
                total: event.total,
            });
        }, false);

        xhr.addEventListener('error', function() {
            scope.dispatchEvent({
                type: 'error',
                message: 'Couldn\'t load URL [' + url + ']',
            });
        }, false);

        if (xhr.overrideMimeType) {
            xhr.overrideMimeType('text/plain; charset=x-user-defined');
        }

        xhr.open('GET', url, true);

        xhr.responseType = 'arraybuffer';

        xhr.send(null);
    },

    littleEndian: function() {
        var buffer = new ArrayBuffer(2);
        new DataView(buffer).setInt16(0, 256, true);

        return new Int16Array(buffer)[0] === 256;
    },

    scan: function(type, chunks, offset, data) {
        window.console.log(type, chunks, offset, data);
    },

    parse: function(data) {
        var littleEndian = this.littleEndian();
        var reader = new DataView(data);

        // String.fromCharCode
        // str.charCodeAt(position)

        // ////////////////////////////////////////////
        //
        // parse all trk header
        // http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
        //
        // ////////////////////////////////////////////

        var offset = 0;
        var header = {};

        // id_string[6]
        // char
        // 6
        // ID string for track file. The first 5 characters must be "TRACK".
        header.ID_STRING = [];
        for (var i = 0; i < 6; i++) {
            header.ID_STRING.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // dim[3]
        // short int
        // 6
        // Dimension of the image volume.
        header.dim = [];
        for (var q = 0; q < 3; q++) {
            header.dim.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        // voxel_size[3]
        // float
        // 12
        // Voxel size of the image volume.
        header.VOXEL_SIZE = [];
        for (var r = 0; r < 3; r++) {
            header.VOXEL_SIZE.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }
        // origin[3]
        // float
        // 12
        // Origin of the image volume. This field is not yet being used by TrackVis. That means the origin is always (0, 0, 0).
        header.origin = [];
        for (var s = 0; s < 3; s++) {
            header.origin.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // n_scalars
        // short int
        // 2
        // Number of scalars saved at each track point (besides x, y and z coordinates).
        header.N_SCALARS = [];
        for (var t = 0; t < 1; t++) {
            header.N_SCALARS.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.SCALAR_NAME = [];
        for (var u = 0; u < 10; u++) {
            header.SCALAR_NAME.push([]);
            for (var v = 0; v < 20; v++) {
                header.SCALAR_NAME[u].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // n_propertiess
        // short int
        // 2
        // Number of properties saved at each track.
        header.N_PROPERTIES = [];
        for (var x = 0; x < 1; x++) {
            header.N_PROPERTIES.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.PROPERTY_NAME = [];
        for (var y = 0; y < 10; y++) {
            header.PROPERTY_NAME.push([]);
            for (var z = 0; z < 20; z++) {
                header.PROPERTY_NAME[y].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // vox_to_ras[4][4]
        // float
        // 64
        // 4x4 matrix for voxel to RAS (crs to xyz) transformation. If vox_to_ras[3][3] is 0, it means the matrix is not recorded. This field is added from version 2.
        header.VOX_TO_RAS = [];
        for (var a = 0; a < 4; a++) {
            header.VOX_TO_RAS.push([]);
            for (var b = 0; b < 4; b++) {
                header.VOX_TO_RAS[a].push(reader.getFloat32(offset));
                offset += 4;
            }
        }

        // reserved[444]
        // char
        // 444
        // Reserved space for future version.
        offset += 444;

        // voxel_order[4]
        // char
        // 4
        // Storing order of the original image data.
        header.VOXEL_ORDER = [];
        for (var c = 0; c < 4; c++) {
            header.VOXEL_ORDER.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // pad2[4]
        // char
        // 4
        // Paddings.
        header.pad2 = [];
        for (var d = 0; d < 4; d++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // image_orientation_patient[6]
        // float
        // 24
        // Image orientation of the original image. As defined in the DICOM header.
        header.IMAGE_ORIENTATION_PATIENT = [];
        for (var e = 0; e < 6; e++) {
            header.IMAGE_ORIENTATION_PATIENT.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // pad1[2]
        // char
        // 2
        // Paddings.
        header.pad1 = [];
        for (var f = 0; f < 2; f++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // invert_x, invert_y, invert_z, swap_xy, swap_yz, swap_zx
        // unsigned_char
        // 1
        // Inversion/rotation flags used to generate this track file. For internal use only.
        header.INVERT_X = [];
        for (var g = 0; g < 1; g++) {
            header.INVERT_X.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Y = [];
        for (var h = 0; h < 1; h++) {
            header.INVERT_Y.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Z = [];
        for (var ii = 0; ii < 1; ii++) {
            header.INVERT_Z.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_XY = [];
        for (var ij = 0; ij < 1; ij++) {
            header.SWAP_XY.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_YZ = [];
        for (var ik = 0; ik < 1; ik++) {
            header.SWAP_YZ.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_ZX = [];
        for (var il = 0; il < 1; il++) {
            header.SWAP_ZX.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // n_count
        // int
        // 4
        // Number of tracks stored in this track file. 0 means the number was NOT stored.
        header.N_COUNT = [];
        for (var im = 0; im < 1; im++) {
            header.N_COUNT.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // version
        // int
        // 4
        // Version number. Current version is 2.
        header.version = [];
        for (var io = 0; io < 1; io++) {
            header.version.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // hdr_size
        // int
        // 4
        // Size of the header. Used to determine byte swap. Should be 1000.
        header.HDR_SIZE = [];
        for (var ip = 0; ip < 1; ip++) {
            header.HDR_SIZE.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        window.console.log(header);

        // /////////////////////////////////////
        //
        // parse the tracts now...!
        //
        // ////////////////////////////////////

        // we should also store each track length

        // get the number of points in this track
        var tracks = [];

        while (offset < reader.byteLength) {
            var nbPoints = -1;
            nbPoints = reader.getUint32(offset, littleEndian);
            offset += 4;

            var track = {
                'points': [],
                'scalars': [],
                'properties': [],
                'geometry': new THREE.Geometry(),
                'xProperties': {},
            };

            var length = 0;

            for (var k = 0; k < nbPoints; k++) {
                // first 3 floats are the coordinates
                track.points[k] = [];
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;

                // add geometry
                //
                track.geometry.vertices.push(new THREE.Vector3(track.points[k][0], track.points[k][1], track.points[k][2]));

                // then the scalars
                track.scalars[k] = [];
                for (var l = 0; l < header.N_SCALARS[0]; l++) {
                    track.scalars[k][l] = [];
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                }

                if (k !== 0) {
                    // get previous and current points
                    var prev = track.points[k - 1];
                    var cur = track.points[k];
                    var xDist = cur[0] - prev[0];
                    var yDist = cur[1] - prev[1];
                    var zDist = cur[2] - prev[2];
                    // get distance
                    var distance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2) + Math.pow(zDist, 2));
                    // add add to length
                    length += distance;
                }
            }

            track.xProperties.length = length;

            for (var p = 0; p < nbPoints; p++) {
                // get previous point if any
                var first = track.points[0];
                if (p > 1) {
                    first = track.points[p - 1];
                }

                // get next point if any
                var last = track.points[nbPoints - 1];
                if (p < nbPoints - 2) {
                    last = track.points[p + 1];
                }

                var diff = [Math.abs(last[0] - first[0]),
                    Math.abs(last[1] - first[1]),
                    Math.abs(last[2] - first[2]),
                ];

                var colordistance = Math.sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
                diff[0] /= colordistance;
                diff[1] /= colordistance;
                diff[2] /= colordistance;

                track.geometry.colors.push(new THREE.Color(diff[0], diff[1], diff[2]));
            }

            // get the property of this track
            for (var o = 0; o < header.N_PROPERTIES[0]; o++) {
                track.properties[o] = [];
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
            }

            tracks.push(track);
        }

        return tracks;
    }
};
<commit_msg>Update loaders.trk.js<commit_after>THREE.TRKLoader = function() {};

Object.assign( THREE.TRKLoader.prototype, THREE.EventDispatcher.prototype, {

    load: function(url, onLoad, onProgress, onError) {
        window.console.log(url, onLoad, onProgress, onError);

        var scope = this;
        var xhr = new XMLHttpRequest();

        function onloaded(event) {
            if (event.target.status === 200 || event.target.status === 0) {
                var geometry = scope.parse(event.target.response || event.target.responseText);
                scope.dispatchEvent({
                    type: 'load',
                    content: geometry,
                });
                if (onLoad) {
                    onLoad(geometry);
                }
            } else {
                scope.dispatchEvent({
                    type: 'error',
                    message: 'Couldn\'t load URL [' + url + ']',
                    response: event.target.statusText,
                });
            }
        }

        xhr.addEventListener('load', onloaded, false);

        xhr.addEventListener('progress', function(event) {
            scope.dispatchEvent({
                type: 'progress',
                loaded: event.loaded,
                total: event.total,
            });
        }, false);

        xhr.addEventListener('error', function() {
            scope.dispatchEvent({
                type: 'error',
                message: 'Couldn\'t load URL [' + url + ']',
            });
        }, false);

        if (xhr.overrideMimeType) {
            xhr.overrideMimeType('text/plain; charset=x-user-defined');
        }

        xhr.open('GET', url, true);

        xhr.responseType = 'arraybuffer';

        xhr.send(null);
    },

    littleEndian: function() {
        var buffer = new ArrayBuffer(2);
        new DataView(buffer).setInt16(0, 256, true);

        return new Int16Array(buffer)[0] === 256;
    },

    scan: function(type, chunks, offset, data) {
        window.console.log(type, chunks, offset, data);
    },

    parse: function(data) {
        var littleEndian = this.littleEndian();
        var reader = new DataView(data);

        // String.fromCharCode
        // str.charCodeAt(position)

        // ////////////////////////////////////////////
        //
        // parse all trk header
        // http://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
        //
        // ////////////////////////////////////////////

        var offset = 0;
        var header = {};

        // id_string[6]
        // char
        // 6
        // ID string for track file. The first 5 characters must be "TRACK".
        header.ID_STRING = [];
        for (var i = 0; i < 6; i++) {
            header.ID_STRING.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // dim[3]
        // short int
        // 6
        // Dimension of the image volume.
        header.dim = [];
        for (var q = 0; q < 3; q++) {
            header.dim.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        // voxel_size[3]
        // float
        // 12
        // Voxel size of the image volume.
        header.VOXEL_SIZE = [];
        for (var r = 0; r < 3; r++) {
            header.VOXEL_SIZE.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }
        // origin[3]
        // float
        // 12
        // Origin of the image volume. This field is not yet being used by TrackVis. That means the origin is always (0, 0, 0).
        header.origin = [];
        for (var s = 0; s < 3; s++) {
            header.origin.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // n_scalars
        // short int
        // 2
        // Number of scalars saved at each track point (besides x, y and z coordinates).
        header.N_SCALARS = [];
        for (var t = 0; t < 1; t++) {
            header.N_SCALARS.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.SCALAR_NAME = [];
        for (var u = 0; u < 10; u++) {
            header.SCALAR_NAME.push([]);
            for (var v = 0; v < 20; v++) {
                header.SCALAR_NAME[u].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // n_propertiess
        // short int
        // 2
        // Number of properties saved at each track.
        header.N_PROPERTIES = [];
        for (var x = 0; x < 1; x++) {
            header.N_PROPERTIES.push(reader.getInt16(offset, littleEndian));
            offset += 2;
        }

        //  scalar_name[10][20]
        //  char
        //  200
        //  Name of each scalar. Can not be longer than 20 characters each. Can only store up to 10 names.
        header.PROPERTY_NAME = [];
        for (var y = 0; y < 10; y++) {
            header.PROPERTY_NAME.push([]);
            for (var z = 0; z < 20; z++) {
                header.PROPERTY_NAME[y].push(String.fromCharCode(reader.getUint8(offset)));
                offset++;
            }
        }

        // vox_to_ras[4][4]
        // float
        // 64
        // 4x4 matrix for voxel to RAS (crs to xyz) transformation. If vox_to_ras[3][3] is 0, it means the matrix is not recorded. This field is added from version 2.
        header.VOX_TO_RAS = [];
        for (var a = 0; a < 4; a++) {
            header.VOX_TO_RAS.push([]);
            for (var b = 0; b < 4; b++) {
                header.VOX_TO_RAS[a].push(reader.getFloat32(offset));
                offset += 4;
            }
        }

        // reserved[444]
        // char
        // 444
        // Reserved space for future version.
        offset += 444;

        // voxel_order[4]
        // char
        // 4
        // Storing order of the original image data.
        header.VOXEL_ORDER = [];
        for (var c = 0; c < 4; c++) {
            header.VOXEL_ORDER.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // pad2[4]
        // char
        // 4
        // Paddings.
        header.pad2 = [];
        for (var d = 0; d < 4; d++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // image_orientation_patient[6]
        // float
        // 24
        // Image orientation of the original image. As defined in the DICOM header.
        header.IMAGE_ORIENTATION_PATIENT = [];
        for (var e = 0; e < 6; e++) {
            header.IMAGE_ORIENTATION_PATIENT.push(reader.getFloat32(offset, littleEndian));
            offset += 4;
        }

        // pad1[2]
        // char
        // 2
        // Paddings.
        header.pad1 = [];
        for (var f = 0; f < 2; f++) {
            header.pad2.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // invert_x, invert_y, invert_z, swap_xy, swap_yz, swap_zx
        // unsigned_char
        // 1
        // Inversion/rotation flags used to generate this track file. For internal use only.
        header.INVERT_X = [];
        for (var g = 0; g < 1; g++) {
            header.INVERT_X.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Y = [];
        for (var h = 0; h < 1; h++) {
            header.INVERT_Y.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.INVERT_Z = [];
        for (var ii = 0; ii < 1; ii++) {
            header.INVERT_Z.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_XY = [];
        for (var ij = 0; ij < 1; ij++) {
            header.SWAP_XY.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_YZ = [];
        for (var ik = 0; ik < 1; ik++) {
            header.SWAP_YZ.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }
        header.SWAP_ZX = [];
        for (var il = 0; il < 1; il++) {
            header.SWAP_ZX.push(String.fromCharCode(reader.getUint8(offset)));
            offset++;
        }

        // n_count
        // int
        // 4
        // Number of tracks stored in this track file. 0 means the number was NOT stored.
        header.N_COUNT = [];
        for (var im = 0; im < 1; im++) {
            header.N_COUNT.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // version
        // int
        // 4
        // Version number. Current version is 2.
        header.version = [];
        for (var io = 0; io < 1; io++) {
            header.version.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        // hdr_size
        // int
        // 4
        // Size of the header. Used to determine byte swap. Should be 1000.
        header.HDR_SIZE = [];
        for (var ip = 0; ip < 1; ip++) {
            header.HDR_SIZE.push(reader.getUint32(offset, littleEndian));
            offset += 4;
        }

        window.console.log(header);

        // /////////////////////////////////////
        //
        // parse the tracts now...!
        //
        // ////////////////////////////////////

        // we should also store each track length

        // get the number of points in this track
        var tracks = [];

        while (offset < reader.byteLength) {
            var nbPoints = -1;
            nbPoints = reader.getUint32(offset, littleEndian);
            offset += 4;

            var track = {
                'points': [],
                'scalars': [],
                'properties': [],
                'geometry': new THREE.Geometry(),
                'xProperties': {},
            };

            var length = 0;

            for (var k = 0; k < nbPoints; k++) {
                // first 3 floats are the coordinates
                track.points[k] = [];
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.points[k].push(reader.getFloat32(offset, littleEndian));
                offset += 4;

                // add geometry
                //
                track.geometry.vertices.push(new THREE.Vector3(track.points[k][0], track.points[k][1], track.points[k][2]));

                // then the scalars
                track.scalars[k] = [];
                for (var l = 0; l < header.N_SCALARS[0]; l++) {
                    track.scalars[k][l] = [];
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                    track.scalars[k][l].push(reader.getFloat32(offset, littleEndian));
                    offset += 4;
                }

                if (k !== 0) {
                    // get previous and current points
                    var prev = track.points[k - 1];
                    var cur = track.points[k];
                    var xDist = cur[0] - prev[0];
                    var yDist = cur[1] - prev[1];
                    var zDist = cur[2] - prev[2];
                    // get distance
                    var distance = Math.sqrt(Math.pow(xDist, 2) + Math.pow(yDist, 2) + Math.pow(zDist, 2));
                    // add add to length
                    length += distance;
                }
            }

            track.xProperties.length = length;

            for (var p = 0; p < nbPoints; p++) {
                // get previous point if any
                var first = track.points[0];
                if (p > 1) {
                    first = track.points[p - 1];
                }

                // get next point if any
                var last = track.points[nbPoints - 1];
                if (p < nbPoints - 2) {
                    last = track.points[p + 1];
                }

                var diff = [Math.abs(last[0] - first[0]),
                    Math.abs(last[1] - first[1]),
                    Math.abs(last[2] - first[2]),
                ];

                var colordistance = Math.sqrt(diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);
                diff[0] /= colordistance;
                diff[1] /= colordistance;
                diff[2] /= colordistance;

                track.geometry.colors.push(new THREE.Color(diff[0], diff[1], diff[2]));
            }

            // get the property of this track
            for (var o = 0; o < header.N_PROPERTIES[0]; o++) {
                track.properties[o] = [];
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
                track.properties[o].push(reader.getFloat32(offset, littleEndian));
                offset += 4;
            }

            tracks.push(track);
        }

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


<commit_before>"use strict";

$('tr').click(function()
{
    //Clicking anywhere in a row highlights that row's input
    $('textarea', this).focus();
});

function doConversions(value, base)
{
    //If value is blank, just clear everything
    if(value=="")
    {
        $('#bin, #hex, #dec, #octal').val('').css({'height':'auto'});
        return;
    }

    var bi=bigInt(value, base);

    //Binary
    if(base!=2)
    {
        $('#bin').val(formatBin(bi.toString(2)));
        resizeTextarea($('#bin'));
    }

    //Hexadecimal
    if(base!=16)
    {
        $('#hex').val(formatHex(bi.toString(16)));
        resizeTextarea($('#hex'));
    }

    //Decimal
    if(base!=10)
    {
        $('#dec').val(formatDec(bi.toString(10)));
        resizeTextarea($('#dec'));
    }

    //Octal
    if(base!=8)
    {
        $('#octal').val(formatOctal(bi.toString(8)));
        resizeTextarea($('#octal'));
    }
}

function formatBin(bin)
{
    return bin.replace(/(.)(?=(.{8})+$)/g, '$1 ');;
}

function formatHex(hex)
{
    return hex.replace(/(.)(?=(.{2})+$)/g, '$1 ');;
}

function formatDec(dec)
{
    return dec.replace(/(.)(?=(.{3})+$)/g, '$1,');
}

function formatOctal(octal)
{
    return octal;
}

function resizeTextarea(textarea)
{
    textarea.css({'height':'auto'}).height(textarea.get(0).scrollHeight);
}

//Handle binary input
$('#bin').on('input', function()
{
    //Remove non-binary characters
    var text=$(this).val().replace(/[^0-1]/g,'');

    doConversions(text, 2);
    $(this).val(formatBin(text));
    resizeTextarea($(this));
});

//Handle hexadecimal input
$('#hex').on('input', function()
{
    //Remove non-hexadecimal characters
    var text=$(this).val().replace(/[^0-9a-fA-F]/g,'');

    doConversions(text, 16);
    $(this).val(formatHex(text));
    resizeTextarea($(this));
});

//Handle decimal input
$('#dec').on('input', function()
{
    //Remove non-decimal characters
    var text=$(this).val().replace(/[^0-9]/g,'');

    doConversions(text, 10);
    $(this).val(formatDec(text));
    resizeTextarea($(this));
});

//Handle octal input
$('#octal').on('input', function()
{
    //Remove non-octal characters
    var text=$(this).val().replace(/[^0-7]/g,'');

    doConversions(text, 8);
    $(this).val(formatOctal(text));
    resizeTextarea($(this));
});

//Auto-focus binary field
$('#bin').focus();
<commit_msg>Various JavaScript improvments<commit_after>'use strict';

$('tr').click(function()
{
    //Clicking anywhere in a row highlights that row's input
    $('textarea', this).focus();
});

function doConversions(value, base)
{
    //If value is blank, just clear everything
    if(value==='')
    {
        $('#bin, #hex, #dec, #octal').val('').css({'height':'auto'});
        return;
    }

    var bi=bigInt(value, base);

    //Binary
    if(base!=2)
    {
        $('#bin').val(formatBin(bi.toString(2)));
        resizeTextarea($('#bin'));
    }

    //Hexadecimal
    if(base!=16)
    {
        $('#hex').val(formatHex(bi.toString(16)));
        resizeTextarea($('#hex'));
    }

    //Decimal
    if(base!=10)
    {
        $('#dec').val(formatDec(bi.toString(10)));
        resizeTextarea($('#dec'));
    }

    //Octal
    if(base!=8)
    {
        $('#octal').val(formatOctal(bi.toString(8)));
        resizeTextarea($('#octal'));
    }
}

function formatBin(bin)
{
    return bin.replace(/(.)(?=(.{8})+$)/g, '$1 ');
}

function formatHex(hex)
{
    return hex.replace(/(.)(?=(.{2})+$)/g, '$1 ');
}

function formatDec(dec)
{
    return dec.replace(/(.)(?=(.{3})+$)/g, '$1,');
}

function formatOctal(octal)
{
    return octal;
}

function resizeTextarea(textarea)
{
    textarea.css({'height':'auto'}).height(textarea.get(0).scrollHeight);
}

//Handle binary input
$('#bin').on('input', function()
{
    //Remove non-binary characters
    var text=$(this).val().replace(/[^0-1]/g,'');

    doConversions(text, 2);
    $(this).val(formatBin(text));
    resizeTextarea($(this));
});

//Handle hexadecimal input
$('#hex').on('input', function()
{
    //Remove non-hexadecimal characters
    var text=$(this).val().replace(/[^0-9a-fA-F]/g,'');

    doConversions(text, 16);
    $(this).val(formatHex(text));
    resizeTextarea($(this));
});

//Handle decimal input
$('#dec').on('input', function()
{
    //Remove non-decimal characters
    var text=$(this).val().replace(/[^0-9]/g,'');

    doConversions(text, 10);
    $(this).val(formatDec(text));
    resizeTextarea($(this));
});

//Handle octal input
$('#octal').on('input', function()
{
    //Remove non-octal characters
    var text=$(this).val().replace(/[^0-7]/g,'');

    doConversions(text, 8);
    $(this).val(formatOctal(text));
    resizeTextarea($(this));
});

//Auto-focus binary field
$('#bin').focus();
<|endoftext|>


<commit_before>/* queue.js
 * Logic functions relating to a user's queued songs.
 */

var winston = require('winston');
var queued_song_model = require('./models/queued_song');

exports.addSongToQueue = function(song, user, callback) {
  var queuedSong = new queued_song_model.QueuedSong({
    song: song,
    user: user,
    order: -1
  });

  queuedSong.save(function(err) {
    if (err) {
      callback({ error: err });
    } else {
      winston.info(
        'Added song "' + song.getLogName() + " to queue of user: " +
        user.getLogName());
      exports.reorderQueue(user, function(err) {
        if (err)
          callback({ error: err });
        else
          callback({ queuedSong: queuedSong });
      });
    }
  });
};

exports.reorderQueue = function(user, callback) {
  var index = 1;

  var queuedSongs = queued_song_model.QueuedSong.find({
    user: user
  }).orderRaw('?? ASC', ['order']).each().forEach(function(ent) {
    ent.order = index++;
  }).save(function(err) {
    if (err) {
      winston.error(
        'Failed to reorder queue for "' + user.getLogName() + '": ' +
        err.message);
      callback(err);
    } else {
      winston.info('Reordered queue for: ' + user.getLogName());
      callback();
    }
  });
};

<commit_msg>Fixed forgotten closing quote in log message.<commit_after>/* queue.js
 * Logic functions relating to a user's queued songs.
 */

var winston = require('winston');
var queued_song_model = require('./models/queued_song');

exports.addSongToQueue = function(song, user, callback) {
  var queuedSong = new queued_song_model.QueuedSong({
    song: song,
    user: user,
    order: -1
  });

  queuedSong.save(function(err) {
    if (err) {
      callback({ error: err });
    } else {
      winston.info(
        'Added song "' + song.getLogName() + '" to queue of user: ' +
        user.getLogName());
      exports.reorderQueue(user, function(err) {
        if (err)
          callback({ error: err });
        else
          callback({ queuedSong: queuedSong });
      });
    }
  });
};

exports.reorderQueue = function(user, callback) {
  var index = 1;

  var queuedSongs = queued_song_model.QueuedSong.find({
    user: user
  }).orderRaw('?? ASC', ['order']).each().forEach(function(ent) {
    ent.order = index++;
  }).save(function(err) {
    if (err) {
      winston.error(
        'Failed to reorder queue for "' + user.getLogName() + '": ' +
        err.message);
      callback(err);
    } else {
      winston.info('Reordered queue for: ' + user.getLogName());
      callback();
    }
  });
};

<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
*/
(function() {
    'use strict';
    myApp.factory('Reporter', ['$location', '$rootScope', '$q', function($location, $rootScope, $q) {
        // Common parameters.
        var v = 1;
        var tid = 'UA-52080037-1';
        var cid = 'user-id'; // TODO(maxw): We need to maintain privacy.

        // URL base, based on the above parameters.
        var URL_BASE = 'http://www.google-analytics.com/collect?';
        URL_BASE += 'v=' + v;
        URL_BASE += '&tid=' + tid;
        URL_BASE += '&cid=' + cid;

        function fetchPermission() {
            if ($rootScope.reportingPermission === undefined) {
                // We don't have reporting permission in memory, so check storage.
                var reportingPermissionDefault = { reportingPermission: 'empty' };
                var getReportingPermissionCallback = function(data) {
                    if (data.reportingPermission === 'empty') {
                        // Permission hasn't previously been granted or denied.  Ask for permission.
                        $location.path('/permission');
                    } else {
                        // Permission has previously been granted or denied.  Set it globally.
                        $rootScope.reportingPermission = data.reportingPermission;
                    }
                };
                // Check local storage for reporting permission.
                chrome.storage.local.get(reportingPermissionDefault, getReportingPermissionCallback);
            }
        }

        // This helper function sends a measurement to the given URL.
        function sendMeasurement(url) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, false);
            xhr.send(null);
        }

        return {
            fetchPermission: fetchPermission,

            sendEvent: function(eventAction) {
                if ($rootScope.reportingPermission) {
                    var url = URL_BASE;
                    url += '&t=event';
                    url += '&av=0.0.0'; // TODO(maxw): Make this accurate.
                    url += '&ea=' + eventAction;

                    sendMeasurement(url);
                }
            }
        };
    }]);
})();
<commit_msg>Made measurement sending asynchronous.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
*/
(function() {
    'use strict';
    myApp.factory('Reporter', ['$location', '$rootScope', '$q', function($location, $rootScope, $q) {
        // Common parameters.
        var v = 1;
        var tid = 'UA-52080037-1';
        var cid = 'user-id'; // TODO(maxw): We need to maintain privacy.

        // URL base, based on the above parameters.
        var URL_BASE = 'http://www.google-analytics.com/collect?';
        URL_BASE += 'v=' + v;
        URL_BASE += '&tid=' + tid;
        URL_BASE += '&cid=' + cid;

        function fetchPermission() {
            if ($rootScope.reportingPermission === undefined) {
                // We don't have reporting permission in memory, so check storage.
                var reportingPermissionDefault = { reportingPermission: 'empty' };
                var getReportingPermissionCallback = function(data) {
                    if (data.reportingPermission === 'empty') {
                        // Permission hasn't previously been granted or denied.  Ask for permission.
                        $location.path('/permission');
                    } else {
                        // Permission has previously been granted or denied.  Set it globally.
                        $rootScope.reportingPermission = data.reportingPermission;
                    }
                };
                // Check local storage for reporting permission.
                chrome.storage.local.get(reportingPermissionDefault, getReportingPermissionCallback);
            }
        }

        // This helper function sends a measurement to the given URL.
        function sendMeasurement(url) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url);
            xhr.send(null);
        }

        return {
            fetchPermission: fetchPermission,

            sendEvent: function(eventAction) {
                if ($rootScope.reportingPermission) {
                    var url = URL_BASE;
                    url += '&t=event';
                    url += '&av=0.0.0'; // TODO(maxw): Make this accurate.
                    url += '&ea=' + eventAction;

                    sendMeasurement(url);
                }
            }
        };
    }]);
})();
<|endoftext|>


<commit_before>(function(exports, requirejs, define, document, XMLHttpRequest){

    /** ECMA SCRIPT COMPLIANT**/
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    var underscore;

    /***
     * marks a function to be executed asycn
     * @return {*}
     */
    Function.prototype.async = function () {
        this._async = true;
        return this;
    };

    var xamlApplication = /^(xaml!)?(.+?)(\.xml)?$/;

    var Rewrite = function (from, to) {
            this.$from = from;
            this.$to = to;
        },
        defaultNamespaceMap = {
            "http://www.w3.org/1999/xhtml": "js.html"
        },
        defaultRewriteMap = [
            new Rewrite(/^js\/html\/(a)$/, "js/html/a"),
            new Rewrite(/^js\/html\/(input)$/, "js/html/Input"),
            new Rewrite(/^js\/html\/(select)$/, "js/html/Select"),
            new Rewrite(/^js\/html\/(textarea)$/, "js/html/TextArea"),
            new Rewrite(/^js\/html\/(option)$/, "js/html/Option"),
            new Rewrite(/^js\/html\/(.+)$/, "js/html/DomElement")
        ];

    var rAppid = {

        createApplicationContext: function (mainClass, config, callback) {

            config = config || {};

            var internalCreateApplicationContext = function (config) {

                config.xamlClasses = config.xamlClasses || [];
                config.namespaceMap = config.namespaceMap || defaultNamespaceMap;
                config.rewriteMap = config.rewriteMap || defaultRewriteMap;

                var requirejsContext = requirejs.config(config),
                    applicationContext = new ApplicationContext(requirejsContext, config);

                define("rAppid", function () {
                    return applicationContext;
                });

                requirejsContext(["inherit", "underscore"], function (inherit, _) {
                    // we have to load inherit.js in order that inheritance is working
                    underscore = _;

                    if (inherit && _) {

                        if (mainClass) {
                            //TODO: have a look at xamlClasses
                            var parts = xamlApplication.exec(mainClass);
                            if (parts) {
                                // mainClass is xaml
                                mainClass = "xaml!" + parts[2];
                            } else {
                                // mainClass is javascript factory
                                mainClass = mainClass.replace(/\./g, "/");
                            }

                            requirejsContext([mainClass], function (applicationFactory) {
                                applicationContext.$applicationFactory = applicationFactory;
                                callback(null, applicationContext);
                            });
                        } else {
                            callback(null, applicationContext);
                        }

                    } else {
                        callback("inherit or underscore missing");
                    }
                });

            };

            if (Object.prototype.toString.call(config) == '[object String]') {
                requirejs(["js/plugins/json!" + config], function (config) {
                    internalCreateApplicationContext(config);
                });
            } else {
                internalCreateApplicationContext(config);
            }

        },

        bootStrap: function (mainClass, config, callback) {
            rAppid.createApplicationContext(mainClass, config, function (err, applicationContext) {
                if (err || !document) {
                    callback(err || "target document missing");
                } else {
                    applicationContext.createApplicationInstance(document, callback);
                }
            })
        },

        rewriteMapEntry: Rewrite,

        createQueryString: function (parameter) {
            var ret = [];

            for (var key in parameter) {
                if (parameter.hasOwnProperty(key)) {
                    ret.push(encodeURIComponent(key) + "=" + encodeURIComponent(parameter[key]));
                }
            }

            return ret.join("&");
        },

        ajax: function (url, options, callback) {

            var s = {
                url: url
            };

            underscore.extend(s, rAppid.ajaxSettings, options);

            if (s.data && !underscore.isString(s.data)) {
                throw "data must be a string";
            }

            s.hasContent = !/^(?:GET|HEAD)$/.test(s.type);

            if (s.queryParameter && underscore.keys(s.queryParameter).length > 0) {
                // append query parameter to url
                s.url += /\?/.test(s.url) ? "&" : "?" + this.createQueryString(s.queryParameter);
            }

            // create new xhr
            var xhr = s.xhr();
            xhr.open(s.type, s.url, s.async);

            if (s.hasContent && s.contentType !== false) {
                xhr.setRequestHeader("Content-Type", s.contentType);
                xhr.setRequestHeader("Content-Length", s.data ? s.data.length.toString() : "0");
            }

            try {
                for (var header in s.headers) {
                    if (s.headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header, s.headers[header]);
                    }
                }
            } catch (e) {
            } // FF3

            xhr.send(s.data);

            var xhrCallback = function (_, isAbort) {

                var wrappedXhr;

                if (xhrCallback && (isAbort || xhr.readyState === 4)) {
                    xhrCallback = undefined;

                    if (isAbort) {
                        // Abort it manually if needed
                        if (xhr.readyState !== 4) {
                            xhr.abort();
                        }
                    } else {
                        wrappedXhr = new rAppidXhr(xhr);
                    }

                    if (callback) {
                        callback(isAbort, wrappedXhr)
                    }
                }
            };

            if (!s.async || xhr.readyState === 4) {
                xhrCallback();
            } else {
                xhr.onreadystatechange = xhrCallback
            }

            return xhr;
        }
    };

    var rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg; // IE leaves an \r character at EOL

    var rAppidXhr = function (xhr) {
        this.xhr = xhr;
        this.status = xhr.status;
        this.$nativeResponseHeaders = xhr.getAllResponseHeaders();
        this.responses = {};

        var xml = xhr.responseXML;

        // Construct response list
        if (xml && xml.documentElement) {
            this.responses.xml = xml;
        }
        this.responses.text = xhr.responseText;

        try {
            this.statusText = xhr.statusText;
        } catch (e) {
            this.statusText = "";
        }
    };

    rAppidXhr.prototype.getResponseHeader = function (key) {
        var match;
        if (!this.$responseHeaders) {
            this.$responseHeaders = {};
            while (( match = rheaders.exec(this.$nativeResponseHeaders) )) {
                this.$responseHeaders[match[1].toLowerCase()] = match[2];
            }
        }
        return this.$responseHeaders[key.toLowerCase()];
    };

    rAppid.ajaxSettings = {
        type: "GET",
        contentType: "application/x-www-form-urlencoded",
        async: true,
        xhr: function () {
            return new XMLHttpRequest();
        },
        headers: {
        },
        data: null
    };

    function inherit(o) {
        function F() {} // Dummy constructor
        F.prototype = o;
        return new F();
    }

    var SystemManager = function (requirejsContext, applicationContext, document) {
        this.$requirejsContext = requirejsContext;
        this.$applicationContext = applicationContext;
        this.$applicationFactory = null;
        this.$document = document;
    };

    var ApplicationContext = function (requirejsContext, config) {
        SystemManager.call(this, requirejsContext);

        this.$config = config;
        this.$applicationContext = this;
    };

    ApplicationContext.prototype = inherit(SystemManager.prototype);
    ApplicationContext.prototype.constructor = ApplicationContext;

    ApplicationContext.prototype.createApplicationInstance = function (document, callback) {
            // create instance
            var applicationFactory = this.$applicationFactory;

            var systemManager = new SystemManager(this.$requirejsContext, this, document);

            this.$requirejsContext(["js/core/Application"], function (Application) {

                var application = new applicationFactory(null, false, systemManager, null, null);

                if (application instanceof Application) {

                    systemManager.$application = application;

                    application._initialize("auto");

                    // return rAppid instance
                    if (callback) {
                        callback(null, systemManager, application);
                    }

                } else {
                    var errMessage = "mainClass isn't an instance of js.core.Application";
                    if (callback) {
                        callback(errMessage);
                    } else {
                        throw(errMessage);
                    }
                }
            });

        };

    ApplicationContext.prototype.getFqClassName = function (namespace, className, useRewriteMap) {
            if (useRewriteMap == undefined || useRewriteMap == null) {
                useRewriteMap = true;
            }

            if (namespace && className) {
                namespace = (this.$config.namespaceMap[namespace] || namespace).replace(/\./g, '/');
                var fqClassName = [namespace, className].join("/");
            } else {
                fqClassName = (namespace || className).replace(/\./g, '/');
            }

            if (underscore.indexOf(this.$config.xamlClasses, fqClassName) !== -1) {
                fqClassName = 'xaml!' + fqClassName;
            }

            if (useRewriteMap) {
                for (var i = 0; i < this.$config.rewriteMap.length; i++) {
                    var entry = this.$config.rewriteMap[i];
                    if (entry instanceof rAppid.rewriteMapEntry) {
                        if (entry.$from.test(fqClassName)) {
                            return fqClassName.replace(entry.$from, entry.$to);
                        }
                    }
                }
            }

            return fqClassName;
        };

    ApplicationContext.prototype.createInstance = function (fqClassName, args, className) {
            className = className || fqClassName;
            args = args || [];

            fqClassName = fqClassName.replace(/\./g, "/");

            var classDefinition = this.$requirejsContext(fqClassName);

            function construct(constructor, args) {
                function F() {
                    return constructor.apply(this, args);
                }

                F.prototype = constructor.prototype;
                return new F();
            }

            var ret;
            try {
                ret = construct(classDefinition, args);
                ret.className = className;
            } catch (e) {
                console.log("Cannot create instance of '" + fqClassName + "'");
            }

            return ret;
        };

    ApplicationContext.prototype.ajax = function (url, options, callback) {

        if (!(/^http.*$/.test(url)) && this.$config.applicationUrl) {
            url = this.$config.applicationUrl + '/' + url;
        }

        rAppid.ajax(url, options, callback);
    };

    rAppid.defaultNamespaceMap = defaultNamespaceMap;
    rAppid.defaultRewriteMap = defaultRewriteMap;
    rAppid.SystemManager = SystemManager;
    rAppid.ApplicationContext = ApplicationContext;
    rAppid.Rewrite = Rewrite;

    exports.rAppid = rAppid;

}(  typeof exports !== "undefined" ? exports : window,
    typeof requirejs !== "undefined" ? requirejs : require('requirejs'),
    typeof requirejs !== "undefined" ? define : require('requirejs').define,
    typeof window !== "undefined" ? window.document : null,
    typeof window !== "undefined" ? window.XMLHttpRequest : require('xmlhttprequest').XMLHttpRequest));
<commit_msg>added native JSON support or fallback to json2<commit_after>(function(exports, requirejs, define, document, XMLHttpRequest){

    /** ECMA SCRIPT COMPLIANT**/
    if (!String.prototype.trim) {
        String.prototype.trim = function () {
            return this.replace(/^\s+|\s+$/g, '');
        };
    }

    var underscore;

    /***
     * marks a function to be executed asycn
     * @return {*}
     */
    Function.prototype.async = function () {
        this._async = true;
        return this;
    };

    var xamlApplication = /^(xaml!)?(.+?)(\.xml)?$/;

    var Rewrite = function (from, to) {
            this.$from = from;
            this.$to = to;
        },
        defaultNamespaceMap = {
            "http://www.w3.org/1999/xhtml": "js.html",
            "http://www.w3.org/2000/svg": "js.svg"
        },
        defaultRewriteMap = [
            new Rewrite(/^js\/html\/(a)$/, "js/html/a"),
            new Rewrite(/^js\/html\/(input)$/, "js/html/Input"),
            new Rewrite(/^js\/html\/(select)$/, "js/html/Select"),
            new Rewrite(/^js\/html\/(textarea)$/, "js/html/TextArea"),
            new Rewrite(/^js\/html\/(option)$/, "js/html/Option"),
            new Rewrite(/^js\/html\/(.+)$/, "js/html/HtmlElement"),
            new Rewrite(/^js\/svg\/(.+)$/, "js/svg/SvgElement")
        ];

    if (typeof JSON !== "undefined") {
        define("JSON", function () {
            return JSON;
        });
    } else {
        requirejs.config({
            paths: {
                JSON: "js/lib/json2"
            },
            shim: {
                JSON: {
                    exports: "JSON"
                }
            }
        });
    }

    var rAppid = {

        createApplicationContext: function (mainClass, config, callback) {

            config = config || {};

            var internalCreateApplicationContext = function (config) {

                config.xamlClasses = config.xamlClasses || [];
                config.namespaceMap = config.namespaceMap || defaultNamespaceMap;
                config.rewriteMap = config.rewriteMap || defaultRewriteMap;

                var requirejsContext = requirejs.config(config),
                    applicationContext = new ApplicationContext(requirejsContext, config);

                define("rAppid", function () {
                    return applicationContext;
                });

                if (typeof JSON !== "undefined") {
                    define("JSON", function() {
                        return JSON;
                    });
                }

                requirejsContext(["inherit", "underscore"], function (inherit, _) {
                    // we have to load inherit.js in order that inheritance is working
                    underscore = _;

                    if (inherit && _) {

                        if (mainClass) {
                            //TODO: have a look at xamlClasses
                            var parts = xamlApplication.exec(mainClass);
                            if (parts) {
                                // mainClass is xaml
                                mainClass = "xaml!" + parts[2];
                            } else {
                                // mainClass is javascript factory
                                mainClass = mainClass.replace(/\./g, "/");
                            }

                            requirejsContext([mainClass], function (applicationFactory) {
                                applicationContext.$applicationFactory = applicationFactory;
                                callback(null, applicationContext);
                            }, function(err) {
                                callback(err);
                            });
                        } else {
                            callback(null, applicationContext);
                        }

                    } else {
                        callback("inherit or underscore missing");
                    }
                });

            };

            if (Object.prototype.toString.call(config) == '[object String]') {
                requirejs(["js/plugins/json!" + config], function (config) {
                    internalCreateApplicationContext(config);
                });
            } else {
                internalCreateApplicationContext(config);
            }

        },

        bootStrap: function (mainClass, config, callback) {
            rAppid.createApplicationContext(mainClass, config, function (err, applicationContext) {
                if (err || !document) {
                    callback(err || "target document missing");
                } else {
                    applicationContext.createApplicationInstance(document, callback);
                }
            })
        },

        rewriteMapEntry: Rewrite,

        createQueryString: function (parameter) {
            var ret = [];

            for (var key in parameter) {
                if (parameter.hasOwnProperty(key)) {
                    ret.push(encodeURIComponent(key) + "=" + encodeURIComponent(parameter[key]));
                }
            }

            return ret.join("&");
        },

        ajax: function (url, options, callback) {

            var s = {
                url: url
            };

            underscore.extend(s, rAppid.ajaxSettings, options);

            if (s.data && !underscore.isString(s.data)) {
                throw "data must be a string";
            }

            s.hasContent = !/^(?:GET|HEAD)$/.test(s.type);

            if (s.queryParameter && underscore.keys(s.queryParameter).length > 0) {
                // append query parameter to url
                s.url += /\?/.test(s.url) ? "&" : "?" + this.createQueryString(s.queryParameter);
            }

            // create new xhr
            var xhr = s.xhr();
            xhr.open(s.type, s.url, s.async);

            if (s.hasContent && s.contentType !== false) {
                xhr.setRequestHeader("Content-Type", s.contentType);
                xhr.setRequestHeader("Content-Length", s.data ? s.data.length.toString() : "0");
            }

            try {
                for (var header in s.headers) {
                    if (s.headers.hasOwnProperty(header)) {
                        xhr.setRequestHeader(header, s.headers[header]);
                    }
                }
            } catch (e) {
            } // FF3

            xhr.send(s.data);

            var xhrCallback = function (_, isAbort) {

                var wrappedXhr;

                if (xhrCallback && (isAbort || xhr.readyState === 4)) {
                    xhrCallback = undefined;

                    if (isAbort) {
                        // Abort it manually if needed
                        if (xhr.readyState !== 4) {
                            xhr.abort();
                        }
                    } else {
                        wrappedXhr = new rAppidXhr(xhr);
                    }

                    if (callback) {
                        callback(isAbort, wrappedXhr)
                    }
                }
            };

            if (!s.async || xhr.readyState === 4) {
                xhrCallback();
            } else {
                xhr.onreadystatechange = xhrCallback
            }

            return xhr;
        }
    };

    var rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg; // IE leaves an \r character at EOL

    var rAppidXhr = function (xhr) {
        this.xhr = xhr;
        this.status = xhr.status;
        this.$nativeResponseHeaders = xhr.getAllResponseHeaders();
        this.responses = {};

        var xml = xhr.responseXML;

        // Construct response list
        if (xml && xml.documentElement) {
            this.responses.xml = xml;
        }
        this.responses.text = xhr.responseText;

        try {
            this.statusText = xhr.statusText;
        } catch (e) {
            this.statusText = "";
        }
    };

    rAppidXhr.prototype.getResponseHeader = function (key) {
        var match;
        if (!this.$responseHeaders) {
            this.$responseHeaders = {};
            while (( match = rheaders.exec(this.$nativeResponseHeaders) )) {
                this.$responseHeaders[match[1].toLowerCase()] = match[2];
            }
        }
        return this.$responseHeaders[key.toLowerCase()];
    };

    rAppid.ajaxSettings = {
        type: "GET",
        contentType: "application/x-www-form-urlencoded",
        async: true,
        xhr: function () {
            return new XMLHttpRequest();
        },
        headers: {
        },
        data: null
    };

    function inherit(o) {
        function F() {} // Dummy constructor
        F.prototype = o;
        return new F();
    }

    var SystemManager = function (requirejsContext, applicationContext, document) {
        this.$requirejsContext = requirejsContext;
        this.$applicationContext = applicationContext;
        this.$applicationFactory = null;
        this.$document = document;
    };

    var ApplicationContext = function (requirejsContext, config) {
        SystemManager.call(this, requirejsContext);

        this.$config = config;
        this.$applicationContext = this;
    };

    ApplicationContext.prototype = inherit(SystemManager.prototype);
    ApplicationContext.prototype.constructor = ApplicationContext;

    ApplicationContext.prototype.createApplicationInstance = function (document, callback) {
            // create instance
            var applicationFactory = this.$applicationFactory;

            var systemManager = new SystemManager(this.$requirejsContext, this, document);

            this.$requirejsContext(["js/core/Application"], function (Application) {

                var application = new applicationFactory(null, false, systemManager, null, null);

                if (application instanceof Application) {

                    systemManager.$application = application;

                    application._initialize("auto");

                    // return rAppid instance
                    if (callback) {
                        callback(null, systemManager, application);
                    }

                } else {
                    var errMessage = "mainClass isn't an instance of js.core.Application";
                    if (callback) {
                        callback(errMessage);
                    } else {
                        throw(errMessage);
                    }
                }
            });

        };

    ApplicationContext.prototype.getFqClassName = function (namespace, className, useRewriteMap) {
            if (useRewriteMap == undefined || useRewriteMap == null) {
                useRewriteMap = true;
            }

            if (namespace && className) {
                namespace = (this.$config.namespaceMap[namespace] || namespace).replace(/\./g, '/');
                var fqClassName = [namespace, className].join("/");
            } else {
                fqClassName = (namespace || className).replace(/\./g, '/');
            }

            if (underscore.indexOf(this.$config.xamlClasses, fqClassName) !== -1) {
                fqClassName = 'xaml!' + fqClassName;
            }

            if (useRewriteMap) {
                for (var i = 0; i < this.$config.rewriteMap.length; i++) {
                    var entry = this.$config.rewriteMap[i];
                    if (entry instanceof rAppid.rewriteMapEntry) {
                        if (entry.$from.test(fqClassName)) {
                            return fqClassName.replace(entry.$from, entry.$to);
                        }
                    }
                }
            }

            return fqClassName;
        };

    ApplicationContext.prototype.createInstance = function (fqClassName, args, className) {
            className = className || fqClassName;
            args = args || [];

            fqClassName = fqClassName.replace(/\./g, "/");

            var classDefinition = this.$requirejsContext(fqClassName);

            function construct(constructor, args) {
                function F() {
                    return constructor.apply(this, args);
                }

                F.prototype = constructor.prototype;
                return new F();
            }

            var ret;
            try {
                ret = construct(classDefinition, args);
                ret.className = className;
            } catch (e) {
                console.log("Cannot create instance of '" + fqClassName + "'");
            }

            return ret;
        };

    ApplicationContext.prototype.ajax = function (url, options, callback) {

        if (!(/^http.*$/.test(url)) && this.$config.applicationUrl) {
            url = this.$config.applicationUrl + '/' + url;
        }

        rAppid.ajax(url, options, callback);
    };

    rAppid.defaultNamespaceMap = defaultNamespaceMap;
    rAppid.defaultRewriteMap = defaultRewriteMap;
    rAppid.SystemManager = SystemManager;
    rAppid.ApplicationContext = ApplicationContext;
    rAppid.Rewrite = Rewrite;

    exports.rAppid = rAppid;

}(  typeof exports !== "undefined" ? exports : window,
    typeof requirejs !== "undefined" ? requirejs : require('requirejs'),
    typeof requirejs !== "undefined" ? define : require('requirejs').define,
    typeof window !== "undefined" ? window.document : null,
    typeof window !== "undefined" ? window.XMLHttpRequest : require('xmlhttprequest').XMLHttpRequest));
<|endoftext|>


<commit_before>(function () {

    'use strict';

    angular
        .module('starter')
        .controller('attachmentCtrl', attachmentCtrl);

         function attachmentCtrl(dataService, $http, $timeout, $scope, $location) {
            var vm = this;
            vm.maxAttachments = 3;
            vm.maxSize = 60;
            vm.cameraShow = false;
            vm.setAttachCount = 2;
            vm.attachmentsForm = [];
            vm.webcamImages = [];

            // get attachment setup
            vm.getInitSetup = function() {
                $http({
                    method: 'GET',
                    url: '/amc-rest-api/attachments-api/settings',
                    headers: {
                        'PrincipalId': 'hudak',
                    },
                }).success(function(data){
                    vm.initSetup = data;
                    vm.maxAttachments = vm.initSetup.maxAttachmentsCount;
                    vm.maxSize = vm.initSetup.maxAttachmentsSizeInMB;
                }).error(function(e){
                    console.log("error", e);
                    vm.attachmentSetup = {
                        "maxAttachmentsSizeInMB": 50,
                        "maxAttachmentsCount": 2
                        }
                });
            }

            // url Params set forms
            vm.urlParams = $location.search();
            if(vm.urlParams.pz) {
                vm.pzNumber = vm.urlParams.pz;
            } else {
                vm.pzNumber = 123;
            }
            if(vm.urlParams.npz) {
                vm.npzNumber = vm.urlParams.npz;
            }
            if(vm.urlParams.ziadanka) {
                vm.ziadanka = vm.urlParams.ziadanka;
            }
            if(vm.urlParams.quantity) {
                vm.formNumber = vm.urlParams.quantity;
                for (var i = 1; i <= vm.formNumber; i++) {
                    vm.attachmentsForm.push({name: 'form'+i, id: i})
                }
            } else {
                vm.formNumber = 2;
                for (var i = 1; i <= vm.formNumber; i++) {
                    vm.attachmentsForm.push({name: 'form'+i, id: i})
                }
            }

            // ionic mobile or desktop
            vm.isWebView = ionic.Platform.isWebView();
            vm.isIPad = ionic.Platform.isIPad();
            vm.isIOS = ionic.Platform.isIOS();
            vm.isAndroid = ionic.Platform.isAndroid();
            vm.isWindowsPhone = ionic.Platform.isWindowsPhone();
            vm.currentPlatform = ionic.Platform.platform();

            if (vm.isWebView == false && vm.isIPad == false && vm.isIOS == false && vm.isAndroid == false &&  vm.isWindowsPhone == false ) {
                vm.isDesktop = true;
            } else {
                vm.isDesktop = false;
            }

            // attachment forms
            // vm.attachmentsForm = [{name: 'form1', id: 1}];

            vm.addNewForm = function() {
                vm.formNumber = vm.formNumber +1;
                var newItemNo = vm.formNumber;
                vm.attachmentsForm.push({'name':'form'+newItemNo, id: newItemNo});
            };

            vm.removeForm = function(objId) {
                for(var i = 0; i < vm.attachmentsForm.length; i++) {
                    var obj = vm.attachmentsForm[i];

                    if(obj.name == objId) {
                        vm.attachmentsForm.splice(i, 1);
                    }
                }
            };
            // init function to get brands object
            vm.brandsByIds = function(ids) {
                vm.brand[ids] = {};
                $http({
                    method: 'POST',
                    url: '/amc-rest-api/attachments-api/params/brand-by-ids',
                    headers: {
                        'PrincipalId': 'hudak',
                    }
                }).success(function(data){
                    vm.brand[ids] = data;
                    return data
                }).error(function(e){
                    console.log("error", e);
                    vm.brand[ids] = [
                        {
                            "id": "1",
                            "name": "new business"
                        },
                        {
                            "id": "2",
                            "name": "New business 2"
                        }
                        ];

                }).finally(function () {
                    if (vm.urlParams['brand'+ids]) {
                    console.log('finaly');
                    // set brand
                    vm.attachmentsForm[ids-1].brand = vm.urlParams['brand'+ids];
                    vm.categoriesByIds(ids, vm.attachmentsForm[ids-1].brand, true);
                    }
                });
            }

            // get categories object
            vm.categoriesByIds = function(ids, value, onInit) {
                console.log('categories');
            console.log(ids, value);
            vm.category[ids] = {};

                $http({
                    method: 'POST',
                    url: '/amc-rest-api/attachments-api/params/categories-by-ids',
                    headers: {
                        'PrincipalId': 'hudak',
                    },
                    data: { "brandId": value }

                }).success(function(data){
                    vm.category[ids] = data;
                    return data
                }).error(function(e){
                    console.log("error", e);
                    vm.category[ids] = [{
                            "id": "24",
                            "name": "PODNIKATELIA"
                        },
                        {
                            "id": "10",
                            "name": "Privát - ostatné"
                        },
                        {
                            "id": "33",
                            "name": "Intervencia-podn"
                        },
                        {
                            "id": "6",
                            "name": "MTPL"
                        },
                        {
                            "id": "44",
                            "name": "Intervencia privat"
                        }
                        ];

                console.log(vm.category);

                }).finally(function () {
                    if(onInit) {
                        console.log('onInit category');
                        vm.attachmentsForm[ids - 1].category = vm.urlParams['category' + ids];
                        vm.typesByIds(ids, vm.attachmentsForm[ids - 1].category, true);
                    }
                });
            }

            // get types object
            vm.typesByIds = function(ids, value, onInit) {
                vm.type[ids] = {};
                $http({
                    method: 'POST',
                    url: '/amc-rest-api/attachments-api/params/types-by-ids',
                    headers: {
                        'PrincipalId': 'hudak',
                    },
                    data: { "categoryId": value }
                }).success(function(data){
                    vm.type[ids] = data;
                    return data
                }).error(function(e){
                    console.log("error", e);
                    vm.type[ids] = [{
                            "id": "341",
                            "name": "Doklady o nadobudnutí veci"
                        },
                        {
                            "id": "380",
                            "name": "Nadobúd. doklady k MV (nadšt.)"
                        },
                        {
                            "id": "351",
                            "name": "Schválenie zľavy"
                        },
                        {
                            "id": "370",
                            "name": "Dohoda o uznaní záväzku"
                        },
                        {
                            "id": "361",
                            "name": "Podiel"
                        },
                        {
                            "id": "371",
                            "name": "Doplň. dotazník pre poisteného"
                        },
                        {
                            "id": "384",
                            "name": "Preberaci protokol od vozidla"
                        },
                        {
                            "id": "358",
                            "name": "Žiadanka na storno starej PZ"
                        }];
                console.log(vm.type);

                }).finally(function () {
                    if(onInit) {
                        console.log('onInit type');
                        vm.attachmentsForm[ids - 1].type = vm.urlParams['type' + ids];
                    }
                });
            }

            vm.category = [];
            vm.brand = [];
            vm.type = [];

            // to work with mobile file input
            // $scope.file_changed = function(element, id) {

            //     console.log(element, id);
            // $scope.$apply(function(scope) {
            //     var photofile = element.files[0];
            //     var reader = new FileReader();
            //     reader.onload = function(e) {
            //         // handle onload
            //         console.log('image', e);
            //     };
            //     reader.readAsDataURL(photofile);
            //     console.log('image2: ', photofile);
            //     vm.mobileImages.push(photofile);
            //     });
            // };

            // webcam on desktop
            var result;
            var formId;
            var formName;
            var webcamImage;
            var dataUri;
            vm.hideCam = function() {
                vm.cameraShow = false;
                result.innerHTML = '';
            }
            vm.showCam = function(id, name) {
                formId = id;
                formName = name;
                console.log('formId: ', formId, formName);

            vm.cameraShow = true;
            Webcam.set({
                width: 320,
                height: 240,
                dest_width: 640,
                dest_height: 480,
                image_format: 'jpeg',
                jpeg_quality: 90,
                force_flash: false,
                flip_horiz: false,
                fps: 45,
                upload_name: 'webcamImage'
            });
            var camera = document.getElementById('my_camera');
            result = document.getElementById('my_result');
            Webcam.attach(camera);
            }

            vm.snapshot = function () {
                console.log('camera works');
                Webcam.snap( function(data_uri) {
                    dataUri = data_uri;
                    result.innerHTML = '<img src="'+data_uri+'"/>';
                } );
                webcamImage = 'webcamImage' + formId + '.jpg'
            }
            vm.addWebcamImage = function () {
                for (var i = 0; i < vm.webcamImages.length; i++) {
                    var element = vm.webcamImages[i];
                    if(webcamImage == element.fileName) {
                        vm.webcamImages.splice(i,1)

                    }
                }
                vm.webcam['form' + formId] = webcamImage;
                vm.webcamImages.push( {file: formName, fileName: webcamImage, dataUri: dataUri});
                console.log(vm.webcamImages);
                console.log(vm.attachmentsForm);

                result.innerHTML = '';
                console.log('close');
                vm.cameraShow = false;
            }

            // submit form
            vm.submit = function () {
                vm.fileSize = 0;
                vm.mb = 1000000;
                vm.dataResult = {
                    forms: vm.attachmentsForm,
                    pzNumber: vm.pzNumber,
                    npzNumber: vm.npzNumber,
                    ziadanka: vm.ziadanka,
                    webcam: vm.webcamImages
                };
                console.log(vm.dataResult);

                // file size validation
                for (var i = 0; i < vm.attachmentsForm.length; i++) {
                    if (vm.attachmentsForm[i].file) {
                    var element = vm.attachmentsForm[i].file.size;
                    vm.fileSize += element;
                    console.log('el: ', vm.fileSize);
                    }
                }

                console.log(vm.fileSize / vm.mb);
                vm.fileSize = vm.fileSize / vm.mb;

                // if total size is bigger show alert otherwise post method
                if (vm.fileSize > vm.maxSize) {
                    alert('presahuje 60mb');
                } else {
                dataService.postData(vm.dataResult);
                }
            }
        }
})();<commit_msg>daily commit<commit_after>(function () {

    'use strict';

    angular
        .module('starter')
        .controller('attachmentCtrl', attachmentCtrl);

         function attachmentCtrl(dataService, $http, $timeout, $scope, $location) {
            var vm = this;
            vm.maxAttachments = 3;
            vm.maxSize = 60;
            vm.cameraShow = false;
            vm.setAttachCount = 2;
            vm.attachmentsForm = [];
            vm.webcamImages = [];
                                console.log(vm.maxAttachments);

            // get attachment setup
            vm.getInitSetup = function() {
                $http({
                    method: 'GET',
                    url: '/amc-rest-api/attachments-api/settings',
                    headers: {
                        'PrincipalId': 'hudak',
                    },
                }).success(function(data){
                    vm.initSetup = data;
                    vm.maxAttachments = vm.initSetup.maxAttachmentsCount;
                    vm.maxSize = vm.initSetup.maxAttachmentsSizeInMB;
                }).error(function(e){
                    console.log("error", e);
                    vm.attachmentSetup = {
                        "maxAttachmentsSizeInMB": 1,
                        "maxAttachmentsCount": 2
                        }
                    vm.maxAttachments = vm.attachmentSetup.maxAttachmentsCount;
                    vm.maxSize = vm.attachmentSetup.maxAttachmentsSizeInMB;
                    console.log(vm.maxAttachments);
                });
            }
            vm.getInitSetup();

            // url Params set forms
            vm.urlParams = $location.search();
            if(vm.urlParams.pz) {
                vm.pzNumber = vm.urlParams.pz;
            } else {
                vm.pzNumber = 123;
            }
            if(vm.urlParams.npz) {
                vm.npzNumber = vm.urlParams.npz;
            }
            if(vm.urlParams.ziadanka) {
                vm.ziadanka = vm.urlParams.ziadanka;
            }
            if(vm.urlParams.quantity) {
                vm.formNumber = vm.urlParams.quantity;
                for (var i = 1; i <= vm.formNumber; i++) {
                    vm.attachmentsForm.push({name: 'form'+i, id: i})
                }
            } else {
                vm.formNumber = 2;
                for (var i = 1; i <= vm.formNumber; i++) {
                    vm.attachmentsForm.push({name: 'form'+i, id: i})
                }
            }

            // ionic mobile or desktop
            vm.isWebView = ionic.Platform.isWebView();
            vm.isIPad = ionic.Platform.isIPad();
            vm.isIOS = ionic.Platform.isIOS();
            vm.isAndroid = ionic.Platform.isAndroid();
            vm.isWindowsPhone = ionic.Platform.isWindowsPhone();
            vm.currentPlatform = ionic.Platform.platform();

            if (vm.isWebView == false && vm.isIPad == false && vm.isIOS == false && vm.isAndroid == false &&  vm.isWindowsPhone == false ) {
                vm.isDesktop = true;
            } else {
                vm.isDesktop = false;
            }

            // attachment forms
            // vm.attachmentsForm = [{name: 'form1', id: 1}];

            vm.addNewForm = function() {
                vm.formNumber = vm.formNumber +1;
                var newItemNo = vm.formNumber;
                vm.attachmentsForm.push({'name':'form'+newItemNo, id: newItemNo});
            };

            vm.removeForm = function(objId) {
                for(var i = 0; i < vm.attachmentsForm.length; i++) {
                    var obj = vm.attachmentsForm[i];

                    if(obj.name == objId) {
                        vm.attachmentsForm.splice(i, 1);
                    }
                }
            };
            // init function to get brands object
            vm.brandsByIds = function(ids) {
                vm.brand[ids] = {};
                $http({
                    method: 'POST',
                    url: '/amc-rest-api/attachments-api/params/brand-by-ids',
                    headers: {
                        'PrincipalId': 'hudak',
                    }
                }).success(function(data){
                    vm.brand[ids] = data;
                    return data
                }).error(function(e){
                    console.log("error", e);
                    vm.brand[ids] = [
                        {
                            "id": "1",
                            "name": "new business"
                        },
                        {
                            "id": "2",
                            "name": "New business 2"
                        }
                        ];

                }).finally(function () {
                    if (vm.urlParams['brand'+ids]) {
                    console.log('finaly');
                    // set brand
                    vm.attachmentsForm[ids-1].brand = vm.urlParams['brand'+ids];
                    vm.categoriesByIds(ids, vm.attachmentsForm[ids-1].brand, true);
                    }
                });
            }

            // get categories object
            vm.categoriesByIds = function(ids, value, onInit) {
                console.log('categories');
            console.log(ids, value);
            vm.category[ids] = {};

                $http({
                    method: 'POST',
                    url: '/amc-rest-api/attachments-api/params/categories-by-ids',
                    headers: {
                        'PrincipalId': 'hudak',
                    },
                    data: { "brandId": value }

                }).success(function(data){
                    vm.category[ids] = data;
                    return data
                }).error(function(e){
                    console.log("error", e);
                    vm.category[ids] = [{
                            "id": "24",
                            "name": "PODNIKATELIA"
                        },
                        {
                            "id": "10",
                            "name": "Privát - ostatné"
                        },
                        {
                            "id": "33",
                            "name": "Intervencia-podn"
                        },
                        {
                            "id": "6",
                            "name": "MTPL"
                        },
                        {
                            "id": "44",
                            "name": "Intervencia privat"
                        }
                        ];

                console.log(vm.category);

                }).finally(function () {
                    if(onInit) {
                        console.log('onInit category');
                        vm.attachmentsForm[ids - 1].category = vm.urlParams['category' + ids];
                        vm.typesByIds(ids, vm.attachmentsForm[ids - 1].category, true);
                    }
                });
            }

            // get types object
            vm.typesByIds = function(ids, value, onInit) {
                vm.type[ids] = {};
                $http({
                    method: 'POST',
                    url: '/amc-rest-api/attachments-api/params/types-by-ids',
                    headers: {
                        'PrincipalId': 'hudak',
                    },
                    data: { "categoryId": value }
                }).success(function(data){
                    vm.type[ids] = data;
                    return data
                }).error(function(e){
                    console.log("error", e);
                    vm.type[ids] = [{
                            "id": "341",
                            "name": "Doklady o nadobudnutí veci"
                        },
                        {
                            "id": "380",
                            "name": "Nadobúd. doklady k MV (nadšt.)"
                        },
                        {
                            "id": "351",
                            "name": "Schválenie zľavy"
                        },
                        {
                            "id": "370",
                            "name": "Dohoda o uznaní záväzku"
                        },
                        {
                            "id": "361",
                            "name": "Podiel"
                        },
                        {
                            "id": "371",
                            "name": "Doplň. dotazník pre poisteného"
                        },
                        {
                            "id": "384",
                            "name": "Preberaci protokol od vozidla"
                        },
                        {
                            "id": "358",
                            "name": "Žiadanka na storno starej PZ"
                        }];
                console.log(vm.type);

                }).finally(function () {
                    if(onInit) {
                        console.log('onInit type');
                        vm.attachmentsForm[ids - 1].type = vm.urlParams['type' + ids];
                    }
                });
            }

            vm.category = [];
            vm.brand = [];
            vm.type = [];

            // to work with mobile file input
            // $scope.file_changed = function(element, id) {

            //     console.log(element, id);
            // $scope.$apply(function(scope) {
            //     var photofile = element.files[0];
            //     var reader = new FileReader();
            //     reader.onload = function(e) {
            //         // handle onload
            //         console.log('image', e);
            //     };
            //     reader.readAsDataURL(photofile);
            //     console.log('image2: ', photofile);
            //     vm.mobileImages.push(photofile);
            //     });
            // };

            // webcam on desktop
            var result;
            var formId;
            var formName;
            var webcamImage;
            var dataUri;
            vm.hideCam = function() {
                vm.cameraShow = false;
                result.innerHTML = '';
            }
            vm.showCam = function(id, name) {
                formId = id;
                formName = name;
                console.log('formId: ', formId, formName);

            vm.cameraShow = true;
            Webcam.set({
                width: 320,
                height: 240,
                dest_width: 640,
                dest_height: 480,
                image_format: 'jpeg',
                jpeg_quality: 90,
                force_flash: false,
                flip_horiz: false,
                fps: 45,
                upload_name: 'webcamImage'
            });
            var camera = document.getElementById('my_camera');
            result = document.getElementById('my_result');
            Webcam.attach(camera);
            }

            vm.snapshot = function () {
                console.log('camera works');
                Webcam.snap( function(data_uri) {
                    dataUri = data_uri;
                    result.innerHTML = '<img src="'+data_uri+'"/>';
                } );
                webcamImage = 'webcamImage' + formId + '.jpg'
            }
            vm.addWebcamImage = function () {
                for (var i = 0; i < vm.webcamImages.length; i++) {
                    var element = vm.webcamImages[i];
                    if(webcamImage == element.fileName) {
                        vm.webcamImages.splice(i,1)

                    }
                }
                vm.webcam['form' + formId] = webcamImage;
                vm.webcamImages.push( {file: formName, fileName: webcamImage, dataUri: dataUri});
                console.log(vm.webcamImages);
                console.log(vm.attachmentsForm);

                result.innerHTML = '';
                console.log('close');
                vm.cameraShow = false;
            }

            // submit form
            vm.submit = function () {
                vm.fileSize = 0;
                vm.mb = 1000000;
                vm.dataResult = {
                    forms: vm.attachmentsForm,
                    pzNumber: vm.pzNumber,
                    npzNumber: vm.npzNumber,
                    ziadanka: vm.ziadanka,
                    webcam: vm.webcamImages
                };
                console.log(vm.dataResult);

                // file size validation
                for (var i = 0; i < vm.attachmentsForm.length; i++) {
                    if (vm.attachmentsForm[i].file) {
                    var element = vm.attachmentsForm[i].file.size;
                    vm.fileSize += element;
                    console.log('el: ', vm.fileSize);
                    }
                }

                console.log(vm.fileSize / vm.mb);
                vm.fileSize = vm.fileSize / vm.mb;

                // if total size is bigger show alert otherwise post method
                if (vm.fileSize > vm.maxSize) {
                    alert('Velikost priloh presahuje ' + vm.maxSize + 'mb');
                } else {
                dataService.postData(vm.dataResult);
                }
            }
        }
})();<|endoftext|>


<commit_before>var Buffer  = require('buffer').Buffer,
    crypto  = require('crypto'),
    assert  = require('assert'),
    MaxUInt = 4294967295;

function _parseArgs(arg_array) {
   if (arg_array.length === 0) { throw new Error('Atleast a callback argument is required'); }
   var is_range = arg_array.length > 2;

   return {
      cb:  arg_array[arg_array.length-1],
      min: is_range ? arg_array[0] : undefined,
      max: is_range ? arg_array[1] : undefined
   };
}

/** Map random int to the range so that an even distrobution of results is possible
 *
 * Using this method ensures an even distrobution of as opposed to the modulo
 * technique is is biased.
 *
 * @see http://mathoverflow.net/questions/35556/skewing-the-distribution-of-random-values-over-a-range
 * for an explaination of the modulo issue.
 */
function _mapToRange(min, max, randUInt) {
   var result_range = max - min,
       factor = result_range / MaxUInt;

   return Math.round((randUInt * factor) + min); // Math.round may cause some slight issues.
}

/*** Returns a random unsigned Int ***
     Returns the random int returned by nodes crypto library
*/
exports.getRandomInt = function(min, max, callback) {
   var args = _parseArgs(arguments), unsigned_int, rand_int;

   crypto.randomBytes(8, function(err, bytes_slow_buf) {
      if (err) { return cb(err); }

      unsigned_int = Buffer(bytes_slow_buf).readUInt32LE(0);

      if (args.min !== undefined) {
         assert(args.max !== undefined && args.min < args.max);
         rand_int = _mapToRange(args.min, args.max, unsigned_int);
      }
      else {
         rand_int = unsigned_int;
      }

      args.cb(null, rand_int);
   });
};
<commit_msg>Update range distribution<commit_after>var Buffer  = require('buffer').Buffer,
    crypto  = require('crypto'),
    assert  = require('assert'),
    MaxUInt = 4294967295;

function _parseArgs(arg_array) {
   if (arg_array.length === 0) { throw new Error('Atleast a callback argument is required'); }
   var is_range = arg_array.length > 2;

   return {
      cb:  arg_array[arg_array.length-1],
      min: is_range ? arg_array[0] : undefined,
      max: is_range ? arg_array[1] : undefined
   };
}

/** Map random int to the range so that an even distrobution of results is possible
 *
 * Using this method ensures an even distrobution of as opposed to the modulo
 * technique is is biased.
 *
 * @see http://mathoverflow.net/questions/35556/skewing-the-distribution-of-random-values-over-a-range
 * for an explaination of the modulo issue.
 */
function _mapToRange(min, max, randUInt) {
   var result_range = (max + 1) - min,
       factor = result_range / MaxUInt;

   return ((randUInt * factor) + min) >> 0; // bitshifting by zero equates to Math.floor, albeit faster.
}

/*** Returns a random unsigned Int ***
     Returns the random int returned by nodes crypto library
*/
exports.getRandomInt = function(min, max, callback) {
   var args = _parseArgs(arguments), unsigned_int, rand_int;

   crypto.randomBytes(8, function(err, bytes_slow_buf) {
      if (err) { return cb(err); }

      unsigned_int = Buffer(bytes_slow_buf).readUInt32LE(0);

      if (args.min !== undefined) {
         assert(args.max !== undefined && args.min < args.max);
         rand_int = _mapToRange(args.min, args.max, unsigned_int);
      }
      else {
         rand_int = unsigned_int;
      }

      args.cb(null, rand_int);
   });
};
<|endoftext|>