<commit_before>/*jslint browser: true*/
/*global L */
/*global GEOHEX */
var geohexcode = null;
var startZoomlevel = 12;
var user = "barack";
var satelliteImages = null;
var map = null;
var polygon = null;
var default_geohex_level = 7;
var defaultSatelliteType = 'Landsat';
var uservote = null;

function getSatelliteImageByDate(date) {
    for (var i = 0; i < satelliteImages.features.length; i++) {
        if (satelliteImages.features[i].properties.Published === date) {
            return satelliteImages.features[i];
        }
    }
    return null;
}

function findEarthWatchersLayer() {
    var result = null;
    map.eachLayer(function (layer) {
        if (layer.options.type !== null) {
            if (layer.options.type === 'earthWatchers') {
                result = layer;
            }
        }
    });
    return result;
}

function sendObservation(observation) {
    if(observation!=uservote){
        colorizePolygon(observation);

        var zone = GEOHEX.getZoneByCode(geohexcode);
        var obs = {
            "user": user,
            "lat": zone.lat,
            "lon": zone.lon,
            "level": zone.getLevel(),
            "observation": observation,
            "geohex": geohexcode
        };
        var url = 'api/observations';
        var request = new XMLHttpRequest();
        request.open('POST', url, true);
        request.setRequestHeader("Content-type", "application/json");
        request.send(JSON.stringify(obs));

        request.onload = function () {
            if (request.status == 201) {
    //            var data = JSON.parse(request.responseText);
                getHexagon(geohexcode, user, hexagonCallback);
            }
        };
    }
}

function getColorByObservation(observation) {
    var color = "#32cd32";
    if (observation === "yes") {
        color = "#b23618";
    } else if (observation === "maybe") {
        color = "#ffd900";
    }
    return color;
}

function colorizePolygon(observation) {
    var color = getColorByObservation(observation);
    polygon.setStyle({color: color});
}

function timeSliderChanged(ctrl) {
    var day = satelliteImages.features[ctrl.value].properties.Published;
    var label = document.getElementById('rangeValLabel');
    label.innerHTML = day;
    // update label positioning
    label.className = 'value' + ctrl.value;

    var earthWatchersLayer = findEarthWatchersLayer();

    var s = getSatelliteImageByDate(day);
    var url = s.properties.UrlTileCache + '/{z}/{x}/{y}.png';
    var maxlevel = s.properties.MaxLevel;
    var newLayer = L.tileLayer(url, {
        tms: true,
        maxZoom: maxlevel,
        type: 'earthWatchers'
    });
    map.addLayer(newLayer);

    if (earthWatchersLayer !== null) {
        map.removeLayer(earthWatchersLayer);
    }
}

function getGeohexPolygon(geohexcode, style) {
    var zone = GEOHEX.getZoneByCode(geohexcode);
    return L.polygon(zone.getHexCoords(), style);
}

function getSatelliteImageData(bbox, imagetype, callback) {
    var url = 'api/satelliteimages?bbox=' + bbox + '&imagetype=' + imagetype;
    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            var data = JSON.parse(request.responseText);
            callback(data);
        }
    };
    request.send();
}

function getHexagon(geohex, username, callback) {
    var url = 'api/hexagons/' + geohex + '?user=' + username;
    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            var data = JSON.parse(request.responseText);
            callback(data);
        }
    };
    request.send();
}

function compare(a, b) {
    if (a.properties.Published < b.properties.Published) {
        return -1;
    }
    if (a.properties.Published > b.properties.Published) {
        return 1;
    }
    return 0;
}

function random(low, high) {
    return Math.random() * (high - low) + low;
}

function satelliteImagesCallback(req) {
    satelliteImages = req;
    var sel = document.getElementById('timeSlider');
    satelliteImages.features.sort(compare);
    sel.onchange();
}

function next() {
    var url = location.href.replace(location.hash,'');
    geohexcode=null;
    location.href=url;
}

function styleButton(button,checked){
    if(checked){
        button.style.border='5px solid black'
    }
    else{
        button.style.border='0px solid black'
    }
}

function hexagonCallback(req) {
    document.getElementById('btnYes').innerHTML = 'Yes (' + req.yes + ')';
    document.getElementById('btnNo').innerHTML = 'No (' + req.no + ')';
    document.getElementById('btnMaybe').innerHTML = 'Maybe (' + req.maybe + ')';

    uservote = req.uservote;
    styleButton (document.getElementById('btnYes'),uservote === 'yes');
    styleButton (document.getElementById('btnNo'),uservote === 'no');
    styleButton (document.getElementById('btnMaybe'),uservote === 'maybe');
}

function toggleSatelliteType(sel) {
    var labels = {
            Landsat: 'Landsat 8',
            Sentinel: 'Sentinel 1'
        },
        newtype = sel.value === 'Landsat' ? 'Sentinel' : 'Landsat';

    // change map layer
    satelliteTypeSelectionChanged({value: newtype});

    // update satellite type value
    sel.parentNode.classList.remove(sel.value.toLowerCase());
    sel.setAttribute('value', newtype);
    sel.parentNode.classList.add(sel.value.toLowerCase());

    // update satellite type label
    document.getElementById('satTypeLabel').innerText = labels[newtype];
}

function satelliteTypeSelectionChanged(sel) {
    var currentImageType = sel.value;
    var polygon = getGeohexPolygon(geohexcode);
    var bbox = polygon.getBounds().toBBoxString();
    getSatelliteImageData(bbox, currentImageType, satelliteImagesCallback);
}

(function (window, document, L) {
    'use strict';
    L.Icon.Default.imagePath = 'images/';

    Path.map("#/hexagon/:hex").to(function(){
        // sample: #/hexagon/PO2670248
        geohexcode = this.params['hex'];
    });
    Path.listen();

    var lon_min = 111.0;
    var lon_max = 112.0;
    var lat_min = 1;
    var lat_max = 2;

    if(geohexcode===null){
        var lon_rnd = random(lon_min, lon_max);
        var lat_rnd = random(lat_min, lat_max);
        geohexcode = GEOHEX.getZoneByLocation(lat_rnd, lon_rnd, default_geohex_level).code;
    }

    // fire onchange event of first combobox
    satelliteTypeSelectionChanged({value: defaultSatelliteType});

    map = L.map('map', {
        zoomControl: false,
        attributionControl: false
    });

    var myStyle = {
        'color': '#000000',
        'weight': 5,
        'opacity': 0.65,
        fillOpacity: 0
    };
    getHexagon(geohexcode, user, hexagonCallback);

    polygon = getGeohexPolygon(geohexcode, myStyle);
    var centerHex = polygon.getBounds().getCenter();
    map.setView(centerHex, startZoomlevel, {
        animation: true
    });

    map.addControl(new L.Control.ZoomMin({
        position: 'topright', startLevel: startZoomlevel, startCenter: centerHex
    }));

    L.control.scale({imperial: false, position: 'topleft'}).addTo(map);

    var ggl2 = new L.Google('satellite');
    map.addLayer(ggl2);
    //omnivore.topojson('project.topojson').addTo(map);
    map.addLayer(polygon);
}(window, document, L));
<commit_msg>always show location hash with permalink<commit_after>/*jslint browser: true*/
/*global L */
/*global GEOHEX */
var geohexcode = null;
var startZoomlevel = 12;
var user = "barack";
var satelliteImages = null;
var map = null;
var polygon = null;
var default_geohex_level = 7;
var defaultSatelliteType = 'Landsat';
var uservote = null;

function getSatelliteImageByDate(date) {
    for (var i = 0; i < satelliteImages.features.length; i++) {
        if (satelliteImages.features[i].properties.Published === date) {
            return satelliteImages.features[i];
        }
    }
    return null;
}

function findEarthWatchersLayer() {
    var result = null;
    map.eachLayer(function (layer) {
        if (layer.options.type !== null) {
            if (layer.options.type === 'earthWatchers') {
                result = layer;
            }
        }
    });
    return result;
}

function sendObservation(observation) {
    if(observation!=uservote){
        colorizePolygon(observation);

        var zone = GEOHEX.getZoneByCode(geohexcode);
        var obs = {
            "user": user,
            "lat": zone.lat,
            "lon": zone.lon,
            "level": zone.getLevel(),
            "observation": observation,
            "geohex": geohexcode
        };
        var url = 'api/observations';
        var request = new XMLHttpRequest();
        request.open('POST', url, true);
        request.setRequestHeader("Content-type", "application/json");
        request.send(JSON.stringify(obs));

        request.onload = function () {
            if (request.status == 201) {
    //            var data = JSON.parse(request.responseText);
                getHexagon(geohexcode, user, hexagonCallback);
            }
        };
    }
}

function getColorByObservation(observation) {
    var color = "#32cd32";
    if (observation === "yes") {
        color = "#b23618";
    } else if (observation === "maybe") {
        color = "#ffd900";
    }
    return color;
}

function colorizePolygon(observation) {
    var color = getColorByObservation(observation);
    polygon.setStyle({color: color});
}

function timeSliderChanged(ctrl) {
    var day = satelliteImages.features[ctrl.value].properties.Published;
    var label = document.getElementById('rangeValLabel');
    label.innerHTML = day;
    // update label positioning
    label.className = 'value' + ctrl.value;

    var earthWatchersLayer = findEarthWatchersLayer();

    var s = getSatelliteImageByDate(day);
    var url = s.properties.UrlTileCache + '/{z}/{x}/{y}.png';
    var maxlevel = s.properties.MaxLevel;
    var newLayer = L.tileLayer(url, {
        tms: true,
        maxZoom: maxlevel,
        type: 'earthWatchers'
    });
    map.addLayer(newLayer);

    if (earthWatchersLayer !== null) {
        map.removeLayer(earthWatchersLayer);
    }
}

function getGeohexPolygon(geohexcode, style) {
    var zone = GEOHEX.getZoneByCode(geohexcode);
    return L.polygon(zone.getHexCoords(), style);
}

function getSatelliteImageData(bbox, imagetype, callback) {
    var url = 'api/satelliteimages?bbox=' + bbox + '&imagetype=' + imagetype;
    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            var data = JSON.parse(request.responseText);
            callback(data);
        }
    };
    request.send();
}

function getHexagon(geohex, username, callback) {
    var url = 'api/hexagons/' + geohex + '?user=' + username;
    var request = new XMLHttpRequest();
    request.open('GET', url, true);

    request.onload = function () {
        if (request.status >= 200 && request.status < 400) {
            var data = JSON.parse(request.responseText);
            callback(data);
        }
    };
    request.send();
}

function compare(a, b) {
    if (a.properties.Published < b.properties.Published) {
        return -1;
    }
    if (a.properties.Published > b.properties.Published) {
        return 1;
    }
    return 0;
}

function random(low, high) {
    return Math.random() * (high - low) + low;
}

function satelliteImagesCallback(req) {
    satelliteImages = req;
    var sel = document.getElementById('timeSlider');
    satelliteImages.features.sort(compare);
    sel.onchange();
}

function next() {
    var url = location.href.replace(location.hash,'');
    location.href=url;
}

function styleButton(button,checked){
    if(checked){
        button.style.border='5px solid black'
    }
    else{
        button.style.border='0px solid black'
    }
}

function hexagonCallback(req) {
    document.getElementById('btnYes').innerHTML = 'Yes (' + req.yes + ')';
    document.getElementById('btnNo').innerHTML = 'No (' + req.no + ')';
    document.getElementById('btnMaybe').innerHTML = 'Maybe (' + req.maybe + ')';

    uservote = req.uservote;
    styleButton (document.getElementById('btnYes'),uservote === 'yes');
    styleButton (document.getElementById('btnNo'),uservote === 'no');
    styleButton (document.getElementById('btnMaybe'),uservote === 'maybe');
}

function toggleSatelliteType(sel) {
    var labels = {
            Landsat: 'Landsat 8',
            Sentinel: 'Sentinel 1'
        },
        newtype = sel.value === 'Landsat' ? 'Sentinel' : 'Landsat';

    // change map layer
    satelliteTypeSelectionChanged({value: newtype});

    // update satellite type value
    sel.parentNode.classList.remove(sel.value.toLowerCase());
    sel.setAttribute('value', newtype);
    sel.parentNode.classList.add(sel.value.toLowerCase());

    // update satellite type label
    document.getElementById('satTypeLabel').innerText = labels[newtype];
}

function satelliteTypeSelectionChanged(sel) {
    var currentImageType = sel.value;
    var polygon = getGeohexPolygon(geohexcode);
    var bbox = polygon.getBounds().toBBoxString();
    getSatelliteImageData(bbox, currentImageType, satelliteImagesCallback);
}

(function (window, document, L) {
    'use strict';
    L.Icon.Default.imagePath = 'images/';

    Path.map("#/hexagon/:hex").to(function(){
        // sample: #/hexagon/PO2670248
        geohexcode = this.params['hex'];
    });
    Path.listen();

    var lon_min = 111.0;
    var lon_max = 112.0;
    var lat_min = 1;
    var lat_max = 2;

    if(geohexcode===null){
        var lon_rnd = random(lon_min, lon_max);
        var lat_rnd = random(lat_min, lat_max);
        geohexcode = GEOHEX.getZoneByLocation(lat_rnd, lon_rnd, default_geohex_level).code;
        location.hash = '#/hexagon/' + geohexcode;
    }

    // fire onchange event of first combobox
    satelliteTypeSelectionChanged({value: defaultSatelliteType});

    map = L.map('map', {
        zoomControl: false,
        attributionControl: false
    });

    var myStyle = {
        'color': '#000000',
        'weight': 5,
        'opacity': 0.65,
        fillOpacity: 0
    };
    getHexagon(geohexcode, user, hexagonCallback);

    polygon = getGeohexPolygon(geohexcode, myStyle);
    var centerHex = polygon.getBounds().getCenter();
    map.setView(centerHex, startZoomlevel, {
        animation: true
    });

    map.addControl(new L.Control.ZoomMin({
        position: 'topright', startLevel: startZoomlevel, startCenter: centerHex
    }));

    L.control.scale({imperial: false, position: 'topleft'}).addTo(map);

    var ggl2 = new L.Google('satellite');
    map.addLayer(ggl2);
    //omnivore.topojson('project.topojson').addTo(map);
    map.addLayer(polygon);
}(window, document, L));
<|endoftext|>


<commit_before>var locale = {
    titles: {
        panelTitle: 'Simulador de Viagens',
        tabTitle:   'Planear uma viagem',
        close:      'Fechar'
    },
    labels: {
        when:               'Quando',
        time:               'Hora',
        date:               'Data',
        depart:             'Embarcar',
        arrive:             'Chegada',
        mode:               'Viaja por',
        minimize:           'Mostrar o(a)',
        maxWalkDistance:    'Distância máxima a pé',
        walkSpeed:          'Velocidade a pé',
        wheelchair:         'Accessível à cadeira de rodas',
        planTrip:           'Simular percurso',
        trip_details:       'Detalhes da viagem',
        date_time:          'Data e Hora',
        validity:           'Validade',
        total_distance:     'Distância total',
        by_foot:            'A pé',
        by_transport:       'Transportes',
        total_duration:     'Duração total',
        startTime:          'Início',
        endTime:            'Fim',
        bike_options:       'Opções de bicicleta',
        bikeFriendly:       'Amigável',
        flat:               'Plano',
        quick:              'Mais curto'
    },
    vectors: {
        modes: [
            ['TRANSIT,WALK',    'Transportes'],
            ['BUSISH,WALK',     'Apenas Autocarro'],
            ['TRAINISH,WALK',   'Apenas Comboio'],
            ['WALK',            'Apenas a pe'],
            ['BICYCLE',         'Apenas de bicicleta'],
            ['TRANSIT,BICYCLE', 'Carros & Bicicletas']
        ],
        options: [
            ['TRANSFERS', 'Menos transferências'],
            ['QUICK',     'Viagem curta'],
            ['SAFE',      'Possivel por bicicleta'],
            ['TRIANGLE',  'Viagem personalizada...']
        ],
        maxWalkDistance: [
            ['500',     '500 metros'],
            ['1000',    '1 km'],
            ['5000',    '5 km'],
            ['10000',   '10 km'],
            ['20000',   '20 km']
        ],
        walkSpeed: [
            ['0.278',  '1 km/h'],
            ['0.556',  '2 km/h'],
            ['0.833',  '3 km/h'],
            ['1.111',  '4 km/h'],
            ['1.389',  '5 km/h'],
            ['1.667',  '6 km/h'],
            ['1.944',  '7 km/h'],
            ['2.222',  '8 km/h'],
            ['2.500',  '9 km/h'],
            ['2.778',  '10 km/h']
        ]
    },
    messages: {
        more_options:   ' Clique aqui para mais opções',
        less_options:   ' Clique aqui para menos opções',
        miss_origin:    'É necessário definir um ponto de partida',
        miss_destiny:   'É necessário definir um ponto de chegada.',
        hide_info:      'Esconder info',
        show_info:      'Mostrar info',
        right_mouse:    'Utilize o botão direito do rato para traçar rotas'
    },
    context_menu: {
        start_here:     'Começar daqui',
        end_here:       'Terminar aqui',
        center_map:     'Centralizar mapa',
        more_zoom:      'Mais zoom',
        less_zoom:      'Menos zoom'
    },
    info: {
        stop_depart:    'Paragem: (embarque) ',
        stop_arrive:    'Paragem: (desembarque) ',
        see_stops:      'ver paragens',
        at:             ' às ',
        bus:            'Autocarro',
        get_in_stop:    'Entrar na paragem:',
        get_out_stop:   'Descer na paragem:',
        depart_at:      'Partida às:',
        arrive_at:      'Chegada às:',
        service_by:     'Serviço prestado por:'
    }
};<commit_msg>Revisão do português<commit_after>var locale = {
    titles: {
        panelTitle: 'Simulador de Viagens',
        tabTitle:   'Planear uma viagem',
        close:      'Fechar'
    },
    labels: {
        when:               'Quando',
        time:               'Hora',
        date:               'Data',
        depart:             'Partida',
        arrive:             'Chegada',
        mode:               'Tipo de Viagem',
        minimize:           'Preferência de percurso',
        maxWalkDistance:    'Distância máx. a pé',
        walkSpeed:          'Velocidade a pé',
        wheelchair:         'Accessível a cadeira de rodas',
        planTrip:           'Simular percurso',
        trip_details:       'Detalhes da viagem',
        date_time:          'Data e Hora',
        validity:           'Validade',
        total_distance:     'Distância total',
        by_foot:            'A pé',
        by_transport:       'Transportes',
        total_duration:     'Duração total',
        startTime:          'Início',
        endTime:            'Fim',
        bike_options:       'Percurso de bicicleta',
        bikeFriendly:       'com ciclovia',
        flat:               'mais plano possivel',
        quick:              'mais rápido'
    },
    vectors: {
        modes: [
            ['TRANSIT,WALK',    'Transportes públicos'],
            ['BUSISH,WALK',     'Apenas autocarro'],
            ['TRAINISH,WALK',   'Apenas comboio'],
            ['WALK',            'Apenas a pé'],
            ['BICYCLE',         'Apenas de bicicleta'],
            ['TRANSIT,BICYCLE', 'Transportes e bicicleta']
        ],
        options: [
            ['TRANSFERS', 'Menos transferências'],
            ['QUICK',     'Viagem mais rápida'],
            ['SAFE',      'Bicicleta em segurança'],
            ['TRIANGLE',  'Personalizada de bicicleta...']
        ],
        maxWalkDistance: [
            ['500',     '500 metros'],
            ['1000',    '1 km'],
            ['5000',    '5 km'],
            ['10000',   '10 km'],
            ['20000',   '20 km']
        ],
        walkSpeed: [
            ['0.278',  '1 km/h'],
            ['0.556',  '2 km/h'],
            ['0.833',  '3 km/h'],
            ['1.111',  '4 km/h'],
            ['1.389',  '5 km/h'],
            ['1.667',  '6 km/h'],
            ['1.944',  '7 km/h'],
            ['2.222',  '8 km/h'],
            ['2.500',  '9 km/h'],
            ['2.778',  '10 km/h']
        ]
    },
    messages: {
        more_options:   ' Clique aqui para mais opções',
        less_options:   ' Clique aqui para menos opções',
        miss_origin:    'É necessário definir um ponto de partida',
        miss_destiny:   'É necessário definir um ponto de chegada.',
        hide_info:      'Esconder info',
        show_info:      'Mostrar info',
        right_mouse:    'Utilize o botão direito do rato para traçar rotas'
    },
    context_menu: {
        start_here:     'Começar aqui',
        end_here:       'Terminar aqui',
        center_map:     'Centrar mapa',
        more_zoom:      'Mais zoom',
        less_zoom:      'Menos zoom'
    },
    info: {
        stop_depart:    'Paragem: (embarque) ',
        stop_arrive:    'Paragem: (desembarque) ',
        see_stops:      'ver paragens',
        at:             ' às ',
        bus:            'Autocarro',
        get_in_stop:    'Entrar na paragem:',
        get_out_stop:   'Sair na paragem:',
        depart_at:      'Partida às:',
        arrive_at:      'Chegada às:',
        service_by:     'Serviço prestado por:'
    }
};<|endoftext|>


<commit_before>let currentUser = {userId: 2, userName: 'Houba'};

let sampleMessages = [
    'Tady scanuju celej byt.',
    'Houba si balí na čundr: dva obří spacáky po prababičce a další pravou zálesáckou výbavu. Počítám, že asi tak po půl kilometru omdlí pod tou vahou únavou a povezete ho k tábořišti na kárce.',
    'S Jendou případně jel já.',
    'Já to včera u vás viděl, slušná nálož. Má aspoň ten bráchuv batoh? Kárku teda budeme muset vyrobit, asi z kulatin a klacků. :-)',
    'Pche, to je všecko jen vzduch. To se nese samo.'
];
let sampleUsers = [
    {
        iconPath: '20_1',
        userId: 20,
        userName: 'Mokl'
    },
    {
        iconPath: '3_4',
        userId: 3,
        userName: 'Sovička'
    },
    {
        iconPath: '3_1',
        userId: 3,
        userName: 'Sovička'
    },
    {
        iconPath: '2_2',
        userId: 2,
        userName: 'Houba'
    }
];
let sampleImages = [
    [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],
    [{url: 'img1.jpg'}],
    [{url: 'img2.jpg'}],
    [{url: 'img1.jpg'}, {url: 'img2.jpg'}],
    [{url: 'img2.jpg'}, {url: 'img1.jpg'}],
    [{url: 'img1.jpg'}, {url: 'img2.jpg'}, {url: 'img1.jpg'}]
];

let messages = [];
let noOfMessages = Math.random() < .2 ? 0 : 10;
for (let i = 0; i < noOfMessages; i++) {
    let user = sampleUsers[Math.floor(Math.random() * 4)];
    let date = new Date();
    date.setMilliseconds(date.getMilliseconds() - i * 10000000);

    let imagesId = Math.floor(Math.random() * 31);

    messages.push({
        id: i,
        iconPath: user.iconPath,
        userId: user.userId,
        userName: user.userName,
        formatted: imagesId != 30 ? sampleMessages[Math.floor(Math.random() * 5)] : '',
        images: sampleImages[imagesId],
        createdOn: date
    });
}
messages.reverse();

setTimeout(messagesLoadResult, Math.round(Math.random() * 1500));

function userIcons() {
    return [{url: '3_1'}, {url: '3_4'}, {url: '3_1'}, {url: '3_4'}];
}<commit_msg>Adding icons to currentUser<commit_after>let currentUser = {
    userId: 2,
    userName: 'Houba',
    icons: [{url: '3_1'}, {url: '3_4'}, {url: '3_1'}, {url: '3_4'}]
};

let sampleMessages = [
    'Tady scanuju celej byt.',
    'Houba si balí na čundr: dva obří spacáky po prababičce a další pravou zálesáckou výbavu. Počítám, že asi tak po půl kilometru omdlí pod tou vahou únavou a povezete ho k tábořišti na kárce.',
    'S Jendou případně jel já.',
    'Já to včera u vás viděl, slušná nálož. Má aspoň ten bráchuv batoh? Kárku teda budeme muset vyrobit, asi z kulatin a klacků. :-)',
    'Pche, to je všecko jen vzduch. To se nese samo.'
];
let sampleUsers = [
    {
        iconPath: '20_1',
        userId: 20,
        userName: 'Mokl'
    },
    {
        iconPath: '3_4',
        userId: 3,
        userName: 'Sovička'
    },
    {
        iconPath: '3_1',
        userId: 3,
        userName: 'Sovička'
    },
    {
        iconPath: '2_2',
        userId: 2,
        userName: 'Houba'
    }
];
let sampleImages = [
    [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [],
    [{url: 'img1.jpg'}],
    [{url: 'img2.jpg'}],
    [{url: 'img1.jpg'}, {url: 'img2.jpg'}],
    [{url: 'img2.jpg'}, {url: 'img1.jpg'}],
    [{url: 'img1.jpg'}, {url: 'img2.jpg'}, {url: 'img1.jpg'}]
];

let messages = [];
let noOfMessages = Math.random() < .2 ? 0 : 10;
for (let i = 0; i < noOfMessages; i++) {
    let user = sampleUsers[Math.floor(Math.random() * 4)];
    let date = new Date();
    date.setMilliseconds(date.getMilliseconds() - i * 10000000);

    let imagesId = Math.floor(Math.random() * 31);

    messages.push({
        id: i,
        iconPath: user.iconPath,
        userId: user.userId,
        userName: user.userName,
        formatted: imagesId != 30 ? sampleMessages[Math.floor(Math.random() * 5)] : '',
        images: sampleImages[imagesId],
        createdOn: date
    });
}
messages.reverse();

setTimeout(messagesLoadResult, Math.round(Math.random() * 1500));
<|endoftext|>


<commit_before>// TryMongo
//
// Copyright (c) 2009 Kyle Banker
// Licensed under the MIT Licence.
// http://www.opensource.org/licenses/mit-license.php

// Readline class to handle line input.
var ReadLine = function(options) {
  this.options      = options || {};
  this.htmlForInput = this.options.htmlForInput;
  this.inputHandler = this.options.handler || this.mockHandler;
  this.scoper       = this.options.scoper;
  this.terminal     = $(this.options.terminalId || "#terminal");
  this.lineClass    = this.options.lineClass || '.readLine';
  this.history      = [];
  this.historyPtr   = 0;

  this.initialize();
};

ReadLine.prototype = {

  initialize: function() {
    this.addInputLine();
  },

  // Enter a new input line with proper behavior.
  addInputLine: function(stackLevel) {
    stackLevel = stackLevel || 0;
    this.terminal.append(this.htmlForInput(stackLevel));
    var ctx = this;
    ctx.activeLine = $(this.lineClass + '.active');

    // Bind key events for entering and navigting history.
    ctx.activeLine.bind("keydown", function(ev) {
      switch (ev.keyCode) {
        case EnterKeyCode:
          ctx.processInput(this.value);
          break;
        case UpArrowKeyCode:
          ctx.getCommand('previous');
          break;
        case DownArrowKeyCode:
          ctx.getCommand('next');
          break;
      }
    });

    this.activeLine.focus();
  },

  // Returns the 'next' or 'previous' command in this history.
  getCommand: function(direction) {
    if(this.history.length === 0) {
      return;
    }
    this.adjustHistoryPointer(direction);
    this.activeLine[0].value = this.history[this.historyPtr];
    $(this.activeLine[0]).focus();
    //this.activeLine[0].value = this.activeLine[0].value;
  },

  // Moves the history pointer to the 'next' or 'previous' position.
  adjustHistoryPointer: function(direction) {
    if(direction == 'previous') {
      if(this.historyPtr - 1 >= 0) {
        this.historyPtr -= 1;
      }
    }
    else {
      if(this.historyPtr + 1 < this.history.length) {
        this.historyPtr += 1;
      }
    }
  },

  // Return the handler's response.
  processInput: function(value) {
    var response = this.inputHandler.apply(this.scoper, [value]);
    this.insertResponse(response.result);

    // Save to the command history...
    if((lineValue = value.trim()) !== "") {
      this.history.push(lineValue);
      this.historyPtr = this.history.length;
    }

    // deactivate the line...
    this.activeLine.value = "";
    this.activeLine.attr({disabled: true});
    this.activeLine.removeClass('active');

    // and add add a new command line.
    this.addInputLine(response.stack);
  },

  insertResponse: function(response) {
    if((response.length < 1) || (response=='"donotprintme"') || (response=='donotprintme')) {
      this.activeLine.parent().append("

");
    }
    else {
      this.activeLine.parent().append("
" + response + "
");
    }
  },

  // Simply return the entered string if the user hasn't specified a smarter handler.
  mockHandler: function(inputString) {
    return function() {
      this._process = function() { return inputString; };
    };
  }
};

var MongoHandler = function() {
  this._currentCommand = "";
  this._rawCommand     = "";
  this._commandStack   = 0;
  this._tutorialPtr    = 0;
  this._tutorialMax    = 4;

  this._mongo          = {};
  this._mongo.test     = [];
  this.collections     = [];
};

MongoHandler.prototype = {

  _process: function(inputString, errorCheck) {
    this._rawCommand += ' ' + inputString;

    try {
      inputString += '  '; // fixes certain bugs with the tokenizer.
      var tokens    = inputString.tokens();
      var mongoFunc = this._getCommand(tokens);
      if(this._commandStack === 0 && inputString.match(/^\s*$/)) {
        return {stack: 0, result: ''};
      }
      else if(this._commandStack === 0 && mongoFunc) {
        this._resetCurrentCommand();
        return {stack: 0, result: mongoFunc.apply(this, [tokens])};
      }
      else {
        return this._evaluator(tokens);
      }
    }

    catch(err) {
        this._resetCurrentCommand();
        console.trace();
        return {stack: 0, result: "JS Error: " + err};
    }
  },

  // Calls eval on the input string when ready.
  _evaluator: function(tokens) {
    isAssignment = tokens.length>=2 && tokens[0].type=="name" && tokens[1].type=="operator" && tokens[1].value=="=";

    this._currentCommand += " " + this._massageTokens(tokens);
    if(this._shouldEvaluateCommand(tokens))  {
        print = this.print;

        // So this eval statement is the heart of the REPL.
        var result = eval(this._currentCommand.trim());
        if(result === undefined) {
          throw('result is undefined');
        } else if (typeof(result) === 'function') {
          throw('result is a function. did you mean to call it?');
        } else {
          result = $htmlFormat(result);
        }
        this._resetCurrentCommand();
        if (isAssignment) {
            return {stack: this._commandStack, result: ""};
        } else {
            return {stack: this._commandStack, result: result};
        }
      }

    else {
      return {stack: this._commandStack, result: ""};
    }
  },

  _resetCurrentCommand: function() {
    this._currentCommand = '';
    this._rawCommand     = '';
  },

  // Evaluate only when we've exited any blocks.
  _shouldEvaluateCommand: function(tokens) {
    for(var i=0; i < tokens.length; i++) {
      var token = tokens[i];
      if(token.type == 'operator') {
        if(token.value == '(' || token.value == '{') {
          this._commandStack += 1;
        }
        else if(token.value == ')' || token.value == '}') {
          this._commandStack -= 1;
        }
      }
    }

    if(this._commandStack === 0) {
      return true;
    }
    else {
      return false;
    }
  },

  _massageTokens: function(tokens) {
    for(var i=0; i < tokens.length; i++) {
      if(tokens[i].type == 'name') {
        if(tokens[i].value == 'var') {
          tokens[i].value = '';
        }
      }
    }
    return this._collectTokens(tokens);
  },

  // Collects tokens into a string, placing spaces between variables.
  // This methods is called after we scope the vars.
  _collectTokens: function(tokens) {
    var result = "";
    for(var i=0; i < tokens.length; i++) {
      if(tokens[i].type == "name" && tokens[i+1] && tokens[i+1].type == 'name') {
        result += tokens[i].value + ' ';
      }
      else if (tokens[i].type == 'string') {
        result += "'" + tokens[i].value + "'";
      }
      else {
        result += tokens[i].value;
      }
    }
    return result;
  },

  // print output to the screen, e.g., in a loop
  // TODO: remove dependency here
  print: function() {
   $('.readLine.active').parent().append('
' + JSON.stringify(arguments[0]) + '
');
   return "donotprintme";
  },

  /* MongoDB     */
  /* ________________________________________ */

  // help command
  _help: function() {
      return PTAG('HELP') +
             PTAG('xos                                 list xos API object types') +
             PTAG('xos.slices                          list methods to can call on slices') +
             PTAG('xos.slices.all()                    get all slices') +
             PTAG('xos.slices.filter({key: "value"})   filter using dictionary') +
             PTAG('xos.slices.get({key: "value"})      get using dictionary')

  },

  _tutorial: function() {
    this._tutorialPtr = 0;
    return PTAG("This is a self-guided tutorial on the xos shell.") +
           PTAG("The tutorial is simple, more or less a few basic commands to try.") +
           PTAG("To go directly to any part tutorial, enter one of the commands t0, t1, t2...t10") +
           PTAG("Otherwise, use 'next' and 'back'. Start by typing 'next' and pressing enter.");
  },

  // go to the next step in the tutorial.
  _next: function() {
    if(this._tutorialPtr < this._tutorialMax) {
      return this['_t' + (this._tutorialPtr + 1)]();
    }
    else {
      return "You've reached the end of the tutorial. To go to the beginning, type 'tutorial'";
    }
  },

  // go to the previous step in the tutorial.
  _back: function() {
    if(this._tutorialPtr > 1) {
      return this['_t' + (this._tutorialPtr - 1)]();
    }
    else {
      return this._tutorial();
    }
  },

  _t1: function() {
    this._tutorialPtr = 1;
    return PTAG('1. JavaScript Shell') +
           PTAG('The first thing to notice is that the MongoDB shell is JavaScript-based.') +
           PTAG('So you can do things like:') +
           PTAG('  a = 5; ') +
           PTAG('  a * 10; ') +
           PTAG('  print(a); ') +
           PTAG("  for(i=0; i<10; i++) { print('hello'); }; ") +
           PTAG("Try a few JS commands; when you're ready to move on, enter 'next'");

  },

  _t2: function() {
    this._tutorialPtr = 2;
    return PTAG('2. The API is asynchronous') +
           PTAG('Try these:') +
           PTAG('    xos.slices.fetch();') +
           PTAG('    // wait a second or two...') +
           PTAG('    xos.slices.objects();');

  },

  _t3: function() {
    this._tutorialPtr = 3;
    return PTAG('3. Filter some objects') +
           PTAG('Try these:');

  },

  _t4: function() {
    this._tutorialPtr = 4;
    return PTAG('4. Available xos objects and methods') +
           PTAG('Try these:') +
           PTAG('    xos;') +
           PTAG('    xos.slices;');

  },

  _getCommand: function(tokens) {
    if(tokens[0] && ArrayInclude(MongoKeywords,(tokens[0].value + '').toLowerCase())) {
      switch(tokens[0].value.toLowerCase()) {
        case 'help':
          return this._help;

        case 'tutorial':
          return this._tutorial;
        case 'next':
          return this._next;
        case 'back':
          return this._back;
        case 't0':
          return this._tutorial;
        case 't1':
          return this._t1;
        case 't2':
          return this._t2;
        case 't3':
          return this._t3;
        case 't4':
          return this._t4;
      }
    }
  }
};

function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

/* stackoverflow: http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript */
function syntaxHighlight(json) {
    if ( json.hasOwnProperty("__str__")) {
        return syntaxHighlight(json.__str__());
    }
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, "\t");
    }
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'terminal_number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'terminal_key';
            } else {
                cls = 'terminal_string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'terminal_boolean';
        } else if (/null/.test(match)) {
            cls = 'terminal_null';
        }
        return '' + match + '';
    });
}

$htmlFormat = function(obj) {
  //JSON.stringify(obj,undefined,2)
  result=replaceAll("\t"," ",replaceAll("\n","
",syntaxHighlight(obj))); //tojson(obj, ' ', ' ', true);
  return result;
}

function startTerminal() {
  var mongo       = new MongoHandler();
  var terminal    = new ReadLine({htmlForInput: DefaultInputHtml,
                                  handler: mongo._process,
                                  scoper: mongo});
  $("#terminal_help1").show();
  $("#terminal_help2").show();
  $("#terminal_wait").hide();

  $("#terminal").bind('click', function() { $(".readLine.active").focus(); });
};

$(document).ready(function() {
    startTerminal();
});
<commit_msg>xoslib wip<commit_after>// TryMongo
//
// Copyright (c) 2009 Kyle Banker
// Licensed under the MIT Licence.
// http://www.opensource.org/licenses/mit-license.php

// Readline class to handle line input.
var ReadLine = function(options) {
  this.options      = options || {};
  this.htmlForInput = this.options.htmlForInput;
  this.inputHandler = this.options.handler || this.mockHandler;
  this.scoper       = this.options.scoper;
  this.terminal     = $(this.options.terminalId || "#terminal");
  this.lineClass    = this.options.lineClass || '.readLine';
  this.history      = [];
  this.historyPtr   = 0;

  this.initialize();
};

ReadLine.prototype = {

  initialize: function() {
    this.addInputLine();
  },

  // Enter a new input line with proper behavior.
  addInputLine: function(stackLevel) {
    stackLevel = stackLevel || 0;
    this.terminal.append(this.htmlForInput(stackLevel));
    var ctx = this;
    ctx.activeLine = $(this.lineClass + '.active');

    // Bind key events for entering and navigting history.
    ctx.activeLine.bind("keydown", function(ev) {
      switch (ev.keyCode) {
        case EnterKeyCode:
          ctx.processInput(this.value);
          break;
        case UpArrowKeyCode:
          ctx.getCommand('previous');
          break;
        case DownArrowKeyCode:
          ctx.getCommand('next');
          break;
      }
    });

    this.activeLine.focus();
  },

  // Returns the 'next' or 'previous' command in this history.
  getCommand: function(direction) {
    if(this.history.length === 0) {
      return;
    }
    this.adjustHistoryPointer(direction);
    this.activeLine[0].value = this.history[this.historyPtr];
    $(this.activeLine[0]).focus();
    //this.activeLine[0].value = this.activeLine[0].value;
  },

  // Moves the history pointer to the 'next' or 'previous' position.
  adjustHistoryPointer: function(direction) {
    if(direction == 'previous') {
      if(this.historyPtr - 1 >= 0) {
        this.historyPtr -= 1;
      }
    }
    else {
      if(this.historyPtr + 1 < this.history.length) {
        this.historyPtr += 1;
      }
    }
  },

  // Return the handler's response.
  processInput: function(value) {
    var response = this.inputHandler.apply(this.scoper, [value]);
    this.insertResponse(response.result);

    // Save to the command history...
    if((lineValue = value.trim()) !== "") {
      this.history.push(lineValue);
      this.historyPtr = this.history.length;
    }

    // deactivate the line...
    this.activeLine.value = "";
    this.activeLine.attr({disabled: true});
    this.activeLine.removeClass('active');

    // and add add a new command line.
    this.addInputLine(response.stack);
  },

  insertResponse: function(response) {
    if((response.length < 1) || (response=='"donotprintme"') || (response=='donotprintme')) {
      this.activeLine.parent().append("

");
    }
    else {
      this.activeLine.parent().append("
" + response + "
");
    }
  },

  // Simply return the entered string if the user hasn't specified a smarter handler.
  mockHandler: function(inputString) {
    return function() {
      this._process = function() { return inputString; };
    };
  }
};

var MongoHandler = function() {
  this._currentCommand = "";
  this._rawCommand     = "";
  this._commandStack   = 0;
  this._tutorialPtr    = 0;
  this._tutorialMax    = 4;

  this._mongo          = {};
  this._mongo.test     = [];
  this.collections     = [];
};

MongoHandler.prototype = {

  _process: function(inputString, errorCheck) {
    this._rawCommand += ' ' + inputString;

    try {
      inputString += '  '; // fixes certain bugs with the tokenizer.
      var tokens    = inputString.tokens();
      var mongoFunc = this._getCommand(tokens);
      if(this._commandStack === 0 && inputString.match(/^\s*$/)) {
        return {stack: 0, result: ''};
      }
      else if(this._commandStack === 0 && mongoFunc) {
        this._resetCurrentCommand();
        return {stack: 0, result: mongoFunc.apply(this, [tokens])};
      }
      else {
        return this._evaluator(tokens);
      }
    }

    catch(err) {
        this._resetCurrentCommand();
        console.trace();
        return {stack: 0, result: "JS Error: " + err};
    }
  },

  // Calls eval on the input string when ready.
  _evaluator: function(tokens) {
    isAssignment = tokens.length>=2 && tokens[0].type=="name" && tokens[1].type=="operator" && tokens[1].value=="=";

    this._currentCommand += " " + this._massageTokens(tokens);
    if(this._shouldEvaluateCommand(tokens))  {
        print = this.print;

        // So this eval statement is the heart of the REPL.
        var result = eval(this._currentCommand.trim());
        if(result === undefined) {
          throw('result is undefined');
        } else if (typeof(result) === 'function') {
          throw('result is a function. did you mean to call it?');
        } else {
          result = $htmlFormat(result);
        }
        this._resetCurrentCommand();
        if (isAssignment) {
            return {stack: this._commandStack, result: ""};
        } else {
            return {stack: this._commandStack, result: result};
        }
      }

    else {
      return {stack: this._commandStack, result: ""};
    }
  },

  _resetCurrentCommand: function() {
    this._currentCommand = '';
    this._rawCommand     = '';
  },

  // Evaluate only when we've exited any blocks.
  _shouldEvaluateCommand: function(tokens) {
    for(var i=0; i < tokens.length; i++) {
      var token = tokens[i];
      if(token.type == 'operator') {
        if(token.value == '(' || token.value == '{') {
          this._commandStack += 1;
        }
        else if(token.value == ')' || token.value == '}') {
          this._commandStack -= 1;
        }
      }
    }

    if(this._commandStack === 0) {
      return true;
    }
    else {
      return false;
    }
  },

  _massageTokens: function(tokens) {
    for(var i=0; i < tokens.length; i++) {
      if(tokens[i].type == 'name') {
        if(tokens[i].value == 'var') {
          tokens[i].value = '';
        }
      }
    }
    return this._collectTokens(tokens);
  },

  // Collects tokens into a string, placing spaces between variables.
  // This methods is called after we scope the vars.
  _collectTokens: function(tokens) {
    var result = "";
    for(var i=0; i < tokens.length; i++) {
      if(tokens[i].type == "name" && tokens[i+1] && tokens[i+1].type == 'name') {
        result += tokens[i].value + ' ';
      }
      else if (tokens[i].type == 'string') {
        result += "'" + tokens[i].value + "'";
      }
      else {
        result += tokens[i].value;
      }
    }
    return result;
  },

  // print output to the screen, e.g., in a loop
  // TODO: remove dependency here
  print: function() {
   $('.readLine.active').parent().append('
' + JSON.stringify(arguments[0]) + '
');
   return "donotprintme";
  },

  /* MongoDB     */
  /* ________________________________________ */

  // help command
  _help: function() {
      return PTAG('HELP') +
             PTAG('xos                                 list xos API object types') +
             PTAG('xos.slices.fetch()                  fetch slices from the server') +
             PTAG('xos.slices                          get the slices that were fetched');

  },

  _tutorial: function() {
    this._tutorialPtr = 0;
    return PTAG("This is a self-guided tutorial on the xos shell.") +
           PTAG("The tutorial is simple, more or less a few basic commands to try.") +
           PTAG("To go directly to any part tutorial, enter one of the commands t0, t1, t2...t10") +
           PTAG("Otherwise, use 'next' and 'back'. Start by typing 'next' and pressing enter.");
  },

  // go to the next step in the tutorial.
  _next: function() {
    if(this._tutorialPtr < this._tutorialMax) {
      return this['_t' + (this._tutorialPtr + 1)]();
    }
    else {
      return "You've reached the end of the tutorial. To go to the beginning, type 'tutorial'";
    }
  },

  // go to the previous step in the tutorial.
  _back: function() {
    if(this._tutorialPtr > 1) {
      return this['_t' + (this._tutorialPtr - 1)]();
    }
    else {
      return this._tutorial();
    }
  },

  _t1: function() {
    this._tutorialPtr = 1;
    return PTAG('1. JavaScript Shell') +
           PTAG('The first thing to notice is that the MongoDB shell is JavaScript-based.') +
           PTAG('So you can do things like:') +
           PTAG('  a = 5; ') +
           PTAG('  a * 10; ') +
           PTAG('  print(a); ') +
           PTAG("  for(i=0; i<10; i++) { print('hello'); }; ") +
           PTAG("Try a few JS commands; when you're ready to move on, enter 'next'");

  },

  _t2: function() {
    this._tutorialPtr = 2;
    return PTAG('2. The API is asynchronous') +
           PTAG('Try these:') +
           PTAG('    xos.slices.models;') +
           PTAG('    // the above should have printed empty list') +
           PTAG('    xos.slices.fetch();') +
           PTAG('    // wait a second or two...') +
           PTAG('    xos.slices.models;');

  },

  _t3: function() {
    this._tutorialPtr = 3;
    return PTAG('3. Responding to events') +
           PTAG('Try these:') +
           PTAG('    xos.slices.fetch();') +
           PTAG('    tmp=xos.slices.on("change", function() { alert("woot!"); });') +
           PTAG('    xos.slices.models[0].set("description", "somerandomtext");');

  },

  _t4: function() {
    this._tutorialPtr = 4;
    return PTAG('4. Available xos objects and methods') +
           PTAG('Try these:') +
           PTAG('    xos;') +
           PTAG('    xos.slices;');

  },

  _getCommand: function(tokens) {
    if(tokens[0] && ArrayInclude(MongoKeywords,(tokens[0].value + '').toLowerCase())) {
      switch(tokens[0].value.toLowerCase()) {
        case 'help':
          return this._help;

        case 'tutorial':
          return this._tutorial;
        case 'next':
          return this._next;
        case 'back':
          return this._back;
        case 't0':
          return this._tutorial;
        case 't1':
          return this._t1;
        case 't2':
          return this._t2;
        case 't3':
          return this._t3;
        case 't4':
          return this._t4;
      }
    }
  }
};

function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

/* stackoverflow: http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript */
function syntaxHighlight(json) {
    if ( json.hasOwnProperty("__str__")) {
        return syntaxHighlight(json.__str__());
    }
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, "\t");
    }
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'terminal_number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'terminal_key';
            } else {
                cls = 'terminal_string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'terminal_boolean';
        } else if (/null/.test(match)) {
            cls = 'terminal_null';
        }
        return '' + match + '';
    });
}

$htmlFormat = function(obj) {
  //JSON.stringify(obj,undefined,2)
  result=replaceAll("\t"," ",replaceAll("\n","
",syntaxHighlight(obj))); //tojson(obj, ' ', ' ', true);
  return result;
}

function startTerminal() {
  var mongo       = new MongoHandler();
  var terminal    = new ReadLine({htmlForInput: DefaultInputHtml,
                                  handler: mongo._process,
                                  scoper: mongo});
  $("#terminal_help1").show();
  $("#terminal_help2").show();
  $("#terminal_wait").hide();

  $("#terminal").bind('click', function() { $(".readLine.active").focus(); });
};

$(document).ready(function() {
    startTerminal();
});
<|endoftext|>


<commit_before>//		a spectrum viewer
//
//	  Copyright  2015 Rappsilber Laboratory, Edinburgh University
//
// 		Licensed 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.
//
//		authors: Lars Kolbowski
//
//
//		SpectrumView2.js

var xiSPEC = xiSPEC || {};
var CLMSUI = CLMSUI || {};

var SpectrumView = Backbone.View.extend({

	events : {},

	initialize: function(viewOptions) {

		var defaultOptions = {
			invert: false,
			hidden: false,
			xlabel: "m/z",
			ylabelLeft: "Intensity",
			ylabelRight: "% of base Peak",
			butterfly: false,
			accentuateCLcontainingFragments: false,
		};

		this.options = _.extend(defaultOptions, viewOptions);

		this.spinner = new Spinner({scale: 5});
		// this.svg = d3.select(this.el.getElementsByTagName("svg")[0]);
		this.svg = d3.select(this.el);

		//create graph
		this.graph = new Graph (this.svg, this.model, this.options);

		$(this.el).css('background-color', '#fff');

		this.listenTo(window, 'resize', _.debounce(this.resize));

		this.listenTo(this.model, 'change:JSONdata', this.render);
		this.listenTo(this.model, 'change:measureMode', this.measuringTool);
		this.listenTo(this.model, 'change:moveLabels', this.moveLabels);
		this.listenTo(this.model, 'change:changedAnnotation', this.changedAnnotation);
		this.listenTo(this.model, 'change:highlightColor', this.updateHighlightColors);
		this.listenTo(this.model, 'changed:ColorScheme', this.updateColors);
		this.listenTo(this.model, 'change:mzRange', this.updateMzRange);

		this.listenTo(xiSPEC.vent, 'butterflyToggle', this.butterflyToggle);
		this.listenTo(xiSPEC.vent, 'butterflySwap', this.butterflySwap);
		this.listenTo(xiSPEC.vent, 'AccentuateCrossLinkContainingFragments', this.accentuateCLcontainingToggle);
		this.listenTo(xiSPEC.vent, 'labelFragmentCharge', this.labelFragmentChargeToggle);
		this.listenTo(xiSPEC.vent, 'downloadSpectrumSVG', this.downloadSVG);
		this.listenTo(xiSPEC.vent, 'resize:spectrum', this.resize);
		this.listenTo(xiSPEC.vent, 'clearSpectrumHighlights', this.clearHighlights);
		this.listenTo(xiSPEC.vent, 'lockZoomToggle', this.lockZoom);

		this.listenTo(this.model, 'resetZoom', this.resetZoom);
		this.listenTo(this.model, 'changed:Highlights', this.updateHighlights);
		this.listenTo(this.model, 'changed:lossyShown', this.showLossy);
		this.listenTo(this.model, 'request_annotation:pending', this.showSpinner);
		this.listenTo(this.model, 'request_annotation:done', this.hideSpinner);
		this.listenTo(this.model, 'changed:fragHighlighting', this.updatePeakHighlighting);
		//this.listenTo(this.model, 'destroy', this.remove);
	},

	render: function() {
		this.graph.clear();
		if(this.options.hidden){
			this.graph.hide();
			return this;
		}
		else{
			this.graph.show();
		}
		this.graph.resize(this.model.xminPrimary, this.model.xmaxPrimary, this.model.ymin, this.model.ymaxPrimary);
		if (this.model.get("JSONdata")){
			this.graph.setData();
		}
		return this;
	},

	resetZoom: function(){
		this.graph.yZoomed = false;
		this.graph.resize(this.model.xminPrimary, this.model.xmaxPrimary, this.model.ymin, this.model.ymaxPrimary);
	},

	updateMzRange: function(){
		//resize if the mzRange is not up to date
		var mzRange = this.model.get('mzRange');
		if (mzRange === undefined)
			return;
		if (mzRange[0] == this.graph.xscale.domain()[0] && mzRange[1] == this.graph.xscale.domain()[1])
			return;
		this.resize();
	},

	resize: function(){
		var mzRange = this.model.get('mzRange');
		if (mzRange === undefined)
			return;
		this.graph.resize(mzRange[0], mzRange[1], this.model.ymin, this.model.ymax);
	},

	showLossy: function(e){
		this.graph.lossyShown = this.model.lossyShown;
		this.graph.updatePeakLabels();
	},

	lockZoom: function(){

		if(xiSPEC.lockZoom){
			this.graph.disableZoom();
		}
		else{
			this.graph.enableZoom();
		}
	},

	clearHighlights: function(){
		this.model.clearStickyHighlights();
	},

	updateColors: function(){
		this.graph.updateColors();
	},

	updatePeakHighlighting: function(){
		this.graph.updatePeakLabels();
		this.graph.updatePeakColors();
	},

	updateHighlightColors: function(){
		this.graph.updateHighlightColors();
	},

	updateHighlights: function(){

		var peaks = this.graph.peaks;

		for(p = 0; p < peaks.length; p++){
			if(peaks[p].fragments.length > 0)
				peaks[p].highlight(false);

			var highlightFragments = _.intersection(peaks[p].fragments, this.model.highlights);
			if(highlightFragments.length != 0){
				peaks[p].highlight(true, highlightFragments);
			}
		}
		this.graph.updatePeakColors();
		this.graph.updatePeakLabels();
	},

	measuringTool: function(){
		this.graph.measure(this.model.get('measureMode'));
	},

	butterflyToggle: function(toggle){
		this.graph.options.butterfly = toggle;
		if(this.options.invert){
			this.model.clearStickyHighlights();
			this.options.hidden = !toggle;
			this.render();
		}
		this.resize();
	},

	butterflySwap: function(){
		this.options.invert = !this.options.invert;
		this.render();
	},

	accentuateCLcontainingToggle: function(toggle){
		this.options.accentuateCLcontainingFragments = toggle;
		this.render();
	},

	labelFragmentChargeToggle: function(toggle){
		this.options.labelFragmentCharge = toggle;
		this.render();
	},

	moveLabels: function(){

		var peaks = this.graph.peaks;

		if (this.model.get('moveLabels')){
			// for(p = 0; p < peaks.length; p++){
			// 	if(peaks[p].labels){
			// 		for(l = 0; l < peaks[p].labels.length; l++){
			// 			peaks[p].labels[l].call(peaks[p].labelDrag);
			// 			peaks[p].labels[l].style("cursor", "pointer");
			// 		}
			// 	}
			// }
			for(p = 0; p < peaks.length; p++){
				if(peaks[p].labels.length){
						peaks[p].labels
							.call(peaks[p].labelDrag)
							//.style("cursor", "pointer");
				}
			}
		}
		else{
			for(p = 0; p < peaks.length; p++){
				if(peaks[p].labels.length){
					peaks[p].labels
						.on(".drag", null)
						//.style("cursor", "default")
					;
				}
			}
		}

	},

	downloadSVG: function(){
		var svgSel = d3.select(this.el.parentNode);
		var svgArr = svgSel[0];
		var svgStrings = CLMSUI.svgUtils.capture (svgArr);
		var svgXML = CLMSUI.svgUtils.makeXMLStr (new XMLSerializer(), svgStrings[0]);

		var charge = this.model.get("JSONdata").annotation.precursorCharge;
		var pepStrs = this.model.pepStrsMods;
		var linkSites = Array(this.model.get("JSONdata").LinkSite.length);

		this.model.get("JSONdata").LinkSite.forEach(function(ls){
			linkSites[ls.peptideId] = ls.linkSite;
		});

		//insert CL sites with #
		if (linkSites.length > 0){

			var ins_pepStrs = Array();
			pepStrs.forEach(function(pepStr, index){
				var positions = [];
				for(var i=0; i<pepStr.length; i++){
					if(pepStr[i].match(/[A-Z]/) != null){
						positions.push(i);
					};
				}
				var clAA_index = positions[linkSites[index]]+1;
				var ins_pepStr = pepStr.slice(0, clAA_index) + "#" + pepStr.slice(clAA_index, pepStr.length);
				pepStrs[index] = ins_pepStr;
			})
		}

		var svg_name = pepStrs.join("-") + "_z=" + charge;
		svg_name += svgSel.node().id;
		svg_name += ".svg";
		download (svgXML, 'application/svg', svg_name);
	},

	showSpinner: function(){
		this.graph.clear();
		this.spinner.spin(d3.select(this.el.parentNode).node());
	},

	hideSpinner: function(){
		this.spinner.stop();
	},

	changedAnnotation: function(){
		if(this.model.get('changedAnnotation')){
			$(this.el.parentNode).attr('style', 'background-color:#9abaff;');
		}
		else{
			$(this.el.parentNode).attr('style', 'background-color:#fff;');
		}
	},

});
<commit_msg>lockzoom fix<commit_after>//		a spectrum viewer
//
//	  Copyright  2015 Rappsilber Laboratory, Edinburgh University
//
// 		Licensed 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.
//
//		authors: Lars Kolbowski
//
//
//		SpectrumView2.js

var xiSPEC = xiSPEC || {};
var CLMSUI = CLMSUI || {};

var SpectrumView = Backbone.View.extend({

	events : {},

	initialize: function(viewOptions) {

		var defaultOptions = {
			invert: false,
			hidden: false,
			xlabel: "m/z",
			ylabelLeft: "Intensity",
			ylabelRight: "% of base Peak",
			butterfly: false,
			accentuateCLcontainingFragments: false,
		};

		this.options = _.extend(defaultOptions, viewOptions);

		this.spinner = new Spinner({scale: 5});
		// this.svg = d3.select(this.el.getElementsByTagName("svg")[0]);
		this.svg = d3.select(this.el);

		//create graph
		this.graph = new Graph (this.svg, this.model, this.options);

		$(this.el).css('background-color', '#fff');

		this.listenTo(window, 'resize', _.debounce(this.resize));

		this.listenTo(this.model, 'change:JSONdata', this.render);
		this.listenTo(this.model, 'change:measureMode', this.measuringTool);
		this.listenTo(this.model, 'change:moveLabels', this.moveLabels);
		this.listenTo(this.model, 'change:changedAnnotation', this.changedAnnotation);
		this.listenTo(this.model, 'change:highlightColor', this.updateHighlightColors);
		this.listenTo(this.model, 'changed:ColorScheme', this.updateColors);
		this.listenTo(this.model, 'change:mzRange', this.updateMzRange);

		this.listenTo(xiSPEC.vent, 'butterflyToggle', this.butterflyToggle);
		this.listenTo(xiSPEC.vent, 'butterflySwap', this.butterflySwap);
		this.listenTo(xiSPEC.vent, 'AccentuateCrossLinkContainingFragments', this.accentuateCLcontainingToggle);
		this.listenTo(xiSPEC.vent, 'labelFragmentCharge', this.labelFragmentChargeToggle);
		this.listenTo(xiSPEC.vent, 'downloadSpectrumSVG', this.downloadSVG);
		this.listenTo(xiSPEC.vent, 'resize:spectrum', this.resize);
		this.listenTo(xiSPEC.vent, 'clearSpectrumHighlights', this.clearHighlights);
		this.listenTo(xiSPEC.vent, 'lockZoomToggle', this.lockZoom);

		this.listenTo(this.model, 'resetZoom', this.resetZoom);
		this.listenTo(this.model, 'changed:Highlights', this.updateHighlights);
		this.listenTo(this.model, 'changed:lossyShown', this.showLossy);
		this.listenTo(this.model, 'request_annotation:pending', this.showSpinner);
		this.listenTo(this.model, 'request_annotation:done', this.hideSpinner);
		this.listenTo(this.model, 'changed:fragHighlighting', this.updatePeakHighlighting);
		//this.listenTo(this.model, 'destroy', this.remove);
	},

	render: function() {
		this.graph.clear();
		if(this.options.hidden){
			this.graph.hide();
			return this;
		}else{
			this.graph.show();}
		if(!xiSPEC.lockZoom){
			this.graph.resize(this.model.xminPrimary, this.model.xmaxPrimary, this.model.ymin, this.model.ymaxPrimary);}
		if (this.model.get("JSONdata")){
			this.graph.setData();}
		return this;
	},

	resetZoom: function(){
		this.graph.yZoomed = false;
		this.graph.resize(this.model.xminPrimary, this.model.xmaxPrimary, this.model.ymin, this.model.ymaxPrimary);
	},

	updateMzRange: function(){
		//resize if the mzRange is not up to date
		var mzRange = this.model.get('mzRange');
		if (mzRange === undefined)
			return;
		if (mzRange[0] == this.graph.xscale.domain()[0] && mzRange[1] == this.graph.xscale.domain()[1])
			return;
		this.resize();
	},

	resize: function(){
		var mzRange = this.model.get('mzRange');
		if (mzRange === undefined)
			return;
		this.graph.resize(mzRange[0], mzRange[1], this.model.ymin, this.model.ymax);
	},

	showLossy: function(e){
		this.graph.lossyShown = this.model.lossyShown;
		this.graph.updatePeakLabels();
	},

	lockZoom: function(){

		if(xiSPEC.lockZoom){
			this.graph.disableZoom();
		}
		else{
			this.graph.enableZoom();
		}
	},

	clearHighlights: function(){
		this.model.clearStickyHighlights();
	},

	updateColors: function(){
		this.graph.updateColors();
	},

	updatePeakHighlighting: function(){
		this.graph.updatePeakLabels();
		this.graph.updatePeakColors();
	},

	updateHighlightColors: function(){
		this.graph.updateHighlightColors();
	},

	updateHighlights: function(){

		var peaks = this.graph.peaks;

		for(p = 0; p < peaks.length; p++){
			if(peaks[p].fragments.length > 0)
				peaks[p].highlight(false);

			var highlightFragments = _.intersection(peaks[p].fragments, this.model.highlights);
			if(highlightFragments.length != 0){
				peaks[p].highlight(true, highlightFragments);
			}
		}
		this.graph.updatePeakColors();
		this.graph.updatePeakLabels();
	},

	measuringTool: function(){
		this.graph.measure(this.model.get('measureMode'));
	},

	butterflyToggle: function(toggle){
		this.graph.options.butterfly = toggle;
		if(this.options.invert){
			this.model.clearStickyHighlights();
			this.options.hidden = !toggle;
			this.render();
		}
		this.resize();
	},

	butterflySwap: function(){
		this.options.invert = !this.options.invert;
		this.render();
	},

	accentuateCLcontainingToggle: function(toggle){
		this.options.accentuateCLcontainingFragments = toggle;
		this.render();
	},

	labelFragmentChargeToggle: function(toggle){
		this.options.labelFragmentCharge = toggle;
		this.render();
	},

	moveLabels: function(){

		var peaks = this.graph.peaks;

		if (this.model.get('moveLabels')){
			// for(p = 0; p < peaks.length; p++){
			// 	if(peaks[p].labels){
			// 		for(l = 0; l < peaks[p].labels.length; l++){
			// 			peaks[p].labels[l].call(peaks[p].labelDrag);
			// 			peaks[p].labels[l].style("cursor", "pointer");
			// 		}
			// 	}
			// }
			for(p = 0; p < peaks.length; p++){
				if(peaks[p].labels.length){
						peaks[p].labels
							.call(peaks[p].labelDrag)
							//.style("cursor", "pointer");
				}
			}
		}
		else{
			for(p = 0; p < peaks.length; p++){
				if(peaks[p].labels.length){
					peaks[p].labels
						.on(".drag", null)
						//.style("cursor", "default")
					;
				}
			}
		}

	},

	downloadSVG: function(){
		var svgSel = d3.select(this.el.parentNode);
		var svgArr = svgSel[0];
		var svgStrings = CLMSUI.svgUtils.capture (svgArr);
		var svgXML = CLMSUI.svgUtils.makeXMLStr (new XMLSerializer(), svgStrings[0]);

		var charge = this.model.get("JSONdata").annotation.precursorCharge;
		var pepStrs = this.model.pepStrsMods;
		var linkSites = Array(this.model.get("JSONdata").LinkSite.length);

		this.model.get("JSONdata").LinkSite.forEach(function(ls){
			linkSites[ls.peptideId] = ls.linkSite;
		});

		//insert CL sites with #
		if (linkSites.length > 0){

			var ins_pepStrs = Array();
			pepStrs.forEach(function(pepStr, index){
				var positions = [];
				for(var i=0; i<pepStr.length; i++){
					if(pepStr[i].match(/[A-Z]/) != null){
						positions.push(i);
					};
				}
				var clAA_index = positions[linkSites[index]]+1;
				var ins_pepStr = pepStr.slice(0, clAA_index) + "#" + pepStr.slice(clAA_index, pepStr.length);
				pepStrs[index] = ins_pepStr;
			})
		}

		var svg_name = pepStrs.join("-") + "_z=" + charge;
		svg_name += svgSel.node().id;
		svg_name += ".svg";
		download (svgXML, 'application/svg', svg_name);
	},

	showSpinner: function(){
		this.graph.clear();
		this.spinner.spin(d3.select(this.el.parentNode).node());
	},

	hideSpinner: function(){
		this.spinner.stop();
	},

	changedAnnotation: function(){
		if(this.model.get('changedAnnotation')){
			$(this.el.parentNode).attr('style', 'background-color:#9abaff;');
		}
		else{
			$(this.el.parentNode).attr('style', 'background-color:#fff;');
		}
	},

});
<|endoftext|>


<commit_before>
// ----------------------------------------------------------------
// CardDetail Class

// ----------------------------------------------------------------
// Model

class CardDetailModel extends CommonModel {
  constructor({
    name
  } = {}) {
    super({
      name: name
    });

    this.NAME = 'Card Detail Model';
    this.EVENT = PS.CDE;

    this.CARD_DETAIL_AREA_SELECTOR = '#card-detail-area';
    this.$CARD_DETAIL_AREA_SELECTOR = $(this.CARD_DETAIL_AREA_SELECTOR);

    this.ID = null;
    this.HASH = null;
    this.CARD = null;
  }
}

// ----------------------------------------------------------------
// View

class CardDetailView extends CommonView {
  constructor(_model = new CardDetailModel()) {
    super(_model);

    this.NAME = 'Card Detail View';
  }

  setModel(
    _card = null
  ) {

  }

  generateCardDetailArea(
    _alertType = 'success',
    _message = null,
    _close = true
  ) {
    this.model.$USER_DETAIL_AREA_SELECTOR.empty();
    this.generateAlert(this.model.$USER_DETAIL_AREA_SELECTOR, _alertType, _message, _close);

  }
}

// ----------------------------------------------------------------
// Controller

class CardDetailController extends CommonController {
  constructor(_obj) {
    super(_obj);

    this.model = new CardDetailModel(_obj);
    this.view = new CardDetailView(this.model);

    this.NAME = 'Card Detail Controller';
  }

  setCard(
    _id = null,
    _hash = null,
    _card = null
  ) {
    this.model.ID = _id;
    this.model.HASH = _hash;
    this.model.CARD = _card;
  }

  openCard(
    _id = this.model.ID,
    _hash = this.model.HASH,
    _card = this.model.CARD
  ) {
    if (_id != null && _hash != null) {
      if (_card == null) {
        // カードの追加

      } else {
        // カードの編集

      }
    }
  }
}

// ----------------------------------------------------------------
// Event

class CardDetailEvent extends CommonEvent {
  constructor({
    name = 'Card Detail Event'
  } = {})
  {
    super({
      name: name
    });

    PS.CDE = this;

    this.NAME = name;
    this.CONTROLLER = new CardDetailController({
      name: 'Card Detail Controller',
    });
  }
}
<commit_msg>Add function addCard to CardDetailController<commit_after>
// ----------------------------------------------------------------
// CardDetail Class

// ----------------------------------------------------------------
// Model

class CardDetailModel extends CommonModel {
  constructor({
    name
  } = {}) {
    super({
      name: name
    });

    this.NAME = 'Card Detail Model';
    this.EVENT = PS.CDE;

    this.CARD_DETAIL_AREA_SELECTOR = '#card-detail-area';
    this.$CARD_DETAIL_AREA_SELECTOR = $(this.CARD_DETAIL_AREA_SELECTOR);

    this.ID = null;
    this.HASH = null;
    this.CARD = null;
  }
}

// ----------------------------------------------------------------
// View

class CardDetailView extends CommonView {
  constructor(_model = new CardDetailModel()) {
    super(_model);

    this.NAME = 'Card Detail View';
  }

  setModel(
    _card = null
  ) {

  }

  generateCardDetailArea(
    _alertType = 'success',
    _message = null,
    _close = true
  ) {
    this.model.$USER_DETAIL_AREA_SELECTOR.empty();
    this.generateAlert(this.model.$USER_DETAIL_AREA_SELECTOR, _alertType, _message, _close);

  }
}

// ----------------------------------------------------------------
// Controller

class CardDetailController extends CommonController {
  constructor(_obj) {
    super(_obj);

    this.model = new CardDetailModel(_obj);
    this.view = new CardDetailView(this.model);

    this.NAME = 'Card Detail Controller';
  }

  setCard(
    _id = null,
    _hash = null,
    _card = null
  ) {
    this.model.ID = _id;
    this.model.HASH = _hash;
    this.model.CARD = _card;
  }

  openCard(
    _id = this.model.ID,
    _hash = this.model.HASH,
    _card = this.model.CARD
  ) {
    if (_id != null && _hash != null) {
      if (_card == null) {
        // カードの追加

      } else {
        // カードの編集

      }
    }
  }

  addCard() {

  }
}

// ----------------------------------------------------------------
// Event

class CardDetailEvent extends CommonEvent {
  constructor({
    name = 'Card Detail Event'
  } = {})
  {
    super({
      name: name
    });

    PS.CDE = this;

    this.NAME = name;
    this.CONTROLLER = new CardDetailController({
      name: 'Card Detail Controller',
    });
  }
}
<|endoftext|>


<commit_before>/*
 * gui-builder - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

/**
 * Global object to access ADM page utils.
 *
 */
$(function() {
    var pageUtils = {
        options :{
            design: null,
            pageTemplate: "Blank Page",
            pageTitle: "Default",
            layout: ['Content']
        },
        /**
         * Creates an new page according to page configure.
         *
         * @param {Object} config The page configure to create new page.
         * @return {ADMNode} The page node, or null if the page type was invalid.
         */
        createNewPage: function(config) {
            var design = config.design || ADM.getDesignRoot(),
                pageTemplate = config.pageTemplate || this.options[pageTemplate],
                pageTitle = config.pageTitle || this.options[pageTitle],
                layout = this.options.layout.concat(config.layout),
                newPage, result;

            if (!design.instanceOf("Design")) {
                console.error("Error: wrong design root passed in");
                return null;
            }

            // create New ADM page node
            newPage = creatPageNode();
            if (!newPage) {
                return null;
            }

            //set page layout
            result = setPageLayout(newPage, layout);
            //TODO: if we have some specfic logic to handle with template,
            //      use below code
            /*
            if (result) {
                switch (pageTemplate) {
                    case "JQuery Mobile Page":
                        // TODO handle specific with JQM
                        break;
                    case "Recent Used Page":
                        // TODO handle specific with Recent Used Page
                        break;
                    default:
                        break;
                }
            }
            */
            return result? newPage: null;

            /**
             * Adds given child object to parent
             *
             * @param {ADMNode} parent The parent object to be added.
             * @param {String} child widget type
             * @return {ADMNode} The node, or null if add failed.
             */
            function addNode(parent, type) {
                design.suppressEvents(true);
                var child = ADM.createNode(type);
                if (!child) {
                    design.suppressEvents(false);
                    return null;
                }
                parent.addChild(child, false);
                design.suppressEvents(false);
                return child;
            }

            /*
             * Create a page node and set it's id property
             * @return {ADMNode} page node or null if add failed.
             */
            function creatPageNode() {
                var pageNode = addNode(design, 'Page');
                if (!pageNode) {
                    return null;
                }
                // set page title
                pageNode.setProperty("id", pageTitle);
                return pageNode;
            }

            /*
             * create  new page's child according to layout
             * @param {ADMNode} pageNode new page node.
             * @param {Array} layout which contains types of child type
             *                       we want create
             * @return {Boolean} true if nodes have been created successfully,
             *                   otherwise return false
             */
            function setPageLayout(pageNode, layout) {
                var t,that;
                for (t in layout ){
                     that = addNode(pageNode, layout[t]);
                     if (that === null) {
                         return false;
                     }
                }
                return true;
            }
        },

        /*
         * Get active page's layout
         * @return {Array} The array, which contais the page's child node type.
         */
        getActivePageLayout: function() {
            var i, children, types = [], type,
                pageNode = ADM.getActivePage();

            children = pageNode.getChildren();
            for (i in children) {
                type = children[i].getType();
                if (type !== 'Content') {
                    types.push(type);
                }
            }
            return types;
        }
    };

    /*******************  export pageUtils to $.gb **********************/
    $.gb = $.gb || {};
    $.gb.pageUtils = pageUtils;
});
<commit_msg>[General] fix issue: replace page id with page Title<commit_after>/*
 * gui-builder - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

/**
 * Global object to access ADM page utils.
 *
 */
$(function() {
    var pageUtils = {
        options :{
            design: null,
            pageTemplate: "Blank Page",
            pageTitle: "Default",
            layout: ['Content']
        },
        /**
         * Creates an new page according to page configure.
         *
         * @param {Object} config The page configure to create new page.
         * @return {ADMNode} The page node, or null if the page type was invalid.
         */
        createNewPage: function(config) {
            var design = config.design || ADM.getDesignRoot(),
                pageTemplate = config.pageTemplate || this.options[pageTemplate],
                pageTitle = config.pageTitle || this.options[pageTitle],
                layout = this.options.layout.concat(config.layout),
                newPage, result;

            if (!design.instanceOf("Design")) {
                console.error("Error: wrong design root passed in");
                return null;
            }

            // create New ADM page node
            newPage = creatPageNode();
            if (!newPage) {
                return null;
            }

            //set page layout
            result = setPageLayout(newPage, layout);
            //TODO: if we have some specfic logic to handle with template,
            //      use below code
            /*
            if (result) {
                switch (pageTemplate) {
                    case "JQuery Mobile Page":
                        // TODO handle specific with JQM
                        break;
                    case "Recent Used Page":
                        // TODO handle specific with Recent Used Page
                        break;
                    default:
                        break;
                }
            }
            */
            return result? newPage: null;

            /**
             * Adds given child object to parent
             *
             * @param {ADMNode} parent The parent object to be added.
             * @param {String} child widget type
             * @return {ADMNode} The node, or null if add failed.
             */
            function addNode(parent, type) {
                design.suppressEvents(true);
                var child = ADM.createNode(type);
                if (!child) {
                    design.suppressEvents(false);
                    return null;
                }
                parent.addChild(child, false);
                design.suppressEvents(false);
                return child;
            }

            /*
             * Create a page node and set it's id property
             * @return {ADMNode} page node or null if add failed.
             */
            function creatPageNode() {
                var pageNode = addNode(design, 'Page');
                if (!pageNode) {
                    return null;
                }
                return pageNode;
            }

            /*
             * create  new page's child according to layout
             * @param {ADMNode} pageNode new page node.
             * @param {Array} layout which contains types of child type
             *                       we want create
             * @return {Boolean} true if nodes have been created successfully,
             *                   otherwise return false
             */
            function setPageLayout(pageNode, layout) {
                var t,that;
                for (t in layout ){
                     that = addNode(pageNode, layout[t]);
                     if (that === null) {
                         return false;
                     }
                }
                return true;
            }
        },

        /*
         * Get active page's layout
         * @return {Array} The array, which contais the page's child node type.
         */
        getActivePageLayout: function() {
            var i, children, types = [], type,
                pageNode = ADM.getActivePage();

            children = pageNode.getChildren();
            for (i in children) {
                type = children[i].getType();
                if (type !== 'Content') {
                    types.push(type);
                }
            }
            return types;
        }
    };

    /*******************  export pageUtils to $.gb **********************/
    $.gb = $.gb || {};
    $.gb.pageUtils = pageUtils;
});
<|endoftext|>


<commit_before>// Functions for the serialization of a vis.js network. This allows for storing
// a network as JSON and then loading it back later.

// GLOBALS //

// In abbreviated JSON data, these replacements are used to keep the data short
var abbvReplacements = {
  a: "label",
  b: "value",
  c: "parent"
};

// DEBUGGING FUNCTIONS //

// Debugging function to see the number of characters saved by only including
// select values in the JSON output. This helps me assess the efficiency of my
// abbreviation method.
function howConcise() {
  // Length of all the data if no abbre
  var unAbbreviatedLength = JSON.stringify(nodes._data).length +
                            JSON.stringify(edges._data).length +
                            JSON.stringify(startpages).length;
  var abbreviatedLength = networkToJson().length;
  var bytesSaved = unAbbreviatedLength - abbreviatedLength;
  var percentSaved = bytesSaved/unAbbreviatedLength * 100;
  var averageSize = abbreviatedLength/nodes.length;
  console.log("Abbreviation takes JSON size from " + unAbbreviatedLength +
               " bytes (unabbreviated) to " + abbreviatedLength + " bytes (abbreviated)");
  console.log("Saves a total of " + bytesSaved + " bytes (" + percentSaved+ " percent)");
  console.log("Average size of " + averageSize + " bytes per node");
}

// SERIALIZATION METHODS //

// Get all the edges that are not directly from a node to its parent. These
// are formed at all cases in which expanding a node links it to a pre-existing
// node.
function getFloatingEdges() {
  floatingEdges = [];
  edges.forEach(function(edge) {
    if (nodes.get(edge.to).parent != edge.from) {
      floatingEdges.push(edge);
    }
  });
  return floatingEdges;
}

//Remove all properties from a node Object which can easily be reconstructed
function abbreviateNode(node) {
  /* Omits the following properties:
  - node.id, which is inferred from `label` through `getNeutralId`
  - node.color, which is inferred from `level` through `getColor`
  - node.value, which is inferred from `startpages` (included separately)
  - node.x, which doesn't matter at all for reconstruction
  - node.y, which also doesn't matter at all

  This leaves us with:
  - node.label, which is used to reconstruct node.id
  - node.level, which is used to reconstruct node.color
  - node.parent, which is used to reconstruct the network's edges */

  var newnode = {a: node.label,
                 b: node.level,
                 c: node.parent};
  return newnode;
}

// Remove all properties from an edge Object which can be easily reconstructed
function abbreviateEdge(edge) {
  /* Omits the following properties:
  - edge.color, which is inferred from nodes.get(edge.to).color
  - edge.selectionWidth, which is always 2
  - edge.hoverWidth, which is always 0
  */
  var newedge = {a: edge.from,
                 b: edge.to,
                 c: edge.level};
  return newedge;
}

// Concisely JSON-ize the data needed to quickly reconstruct the network
function networkToJson() {
  var out = {};

  // Store nodes
  var data = nodes._data; // Retreive an object representing nodes data
  var vals = Object.keys(data).map(function(k){return data[k];});
  var abbv = vals.map(abbreviateNode); // Process it
  out.nodes = abbv; // Store it

  // Store startpages
  out.startpages = startpages;

  return JSON.stringify(out);
}

// DESERIALIZATION METHODS //

// Unabbreviate a node Object
function unabbreviateNode(node, startpgs) {
  // Make quick substitutions
  var newnode = {label: node.a,
                 level: node.b,
                 parent: node.c};
  // Infer omitted properties
  newnode.id = getNeutralId(newnode.label);
  newnode.color = getColor(newnode.level);
  newnode.value = startpgs.indexOf(newnode.id) === -1 ? 1:2;

  return newnode;
}

// Unabbreviate an edge Object.
function unabbreviateEdge(edge) {
  var newedge = {from: edge.a,
                 to: edge.b,
                 level: edge.c};
  newedge.color = getEdgeColor(newedge.level);
  newedge.selectionWidth = 2;
  newedge.hoverWidth = 0;

  return newedge;
}

// Reconstruct edges given a list of nodes
function buildEdges (nds) {
  var edgs = new vis.DataSet();
  for (var i = 0; i < nds.length; i++) {
    node = nds[i];
    if (node.parent != node.id) { // Don't create an edge from start nodes to themselves
      edgs.add({from: node.parent, to: node.id, color: getEdgeColor(node.level),
                level: node.level, selectionWidth: 2, hoverWidth:0});
    }
  }
  return edgs;
}

// Take consise JSON and use it to reconstruct `nodes` and `edges`
function networkFromJson(data) {
  // Get data
  data = JSON.parse(data);

  out = {};

  // Store startpages
  out.startpages = data.startpages;
  // Store nodes
  var nds = data.nodes;
  var expandedNodes = nds.map(function(x){return unabbreviateNode(x, out.startpages);});
  out.nodes = new vis.DataSet();
  out.nodes.add(expandedNodes);
  // Store edges
  out.edges = buildEdges(expandedNodes);

  return out;
}
<commit_msg>Remove unusued Object<commit_after>// Functions for the serialization of a vis.js network. This allows for storing
// a network as JSON and then loading it back later.

// DEBUGGING FUNCTIONS //

// Debugging function to see the number of characters saved by only including
// select values in the JSON output. This helps me assess the efficiency of my
// abbreviation method.
function howConcise() {
  // Length of all the data if no abbre
  var unAbbreviatedLength = JSON.stringify(nodes._data).length +
                            JSON.stringify(edges._data).length +
                            JSON.stringify(startpages).length;
  var abbreviatedLength = networkToJson().length;
  var bytesSaved = unAbbreviatedLength - abbreviatedLength;
  var percentSaved = bytesSaved/unAbbreviatedLength * 100;
  var averageSize = abbreviatedLength/nodes.length;
  console.log("Abbreviation takes JSON size from " + unAbbreviatedLength +
               " bytes (unabbreviated) to " + abbreviatedLength + " bytes (abbreviated)");
  console.log("Saves a total of " + bytesSaved + " bytes (" + percentSaved+ " percent)");
  console.log("Average size of " + averageSize + " bytes per node");
}

// SERIALIZATION METHODS //

// Get all the edges that are not directly from a node to its parent. These
// are formed at all cases in which expanding a node links it to a pre-existing
// node.
function getFloatingEdges() {
  floatingEdges = [];
  edges.forEach(function(edge) {
    if (nodes.get(edge.to).parent != edge.from) {
      floatingEdges.push(edge);
    }
  });
  return floatingEdges;
}

//Remove all properties from a node Object which can easily be reconstructed
function abbreviateNode(node) {
  /* Omits the following properties:
  - node.id, which is inferred from `label` through `getNeutralId`
  - node.color, which is inferred from `level` through `getColor`
  - node.value, which is inferred from `startpages` (included separately)
  - node.x, which doesn't matter at all for reconstruction
  - node.y, which also doesn't matter at all

  This leaves us with:
  - node.label, which is used to reconstruct node.id
  - node.level, which is used to reconstruct node.color
  - node.parent, which is used to reconstruct the network's edges */

  var newnode = {a: node.label,
                 b: node.level,
                 c: node.parent};
  return newnode;
}

// Remove all properties from an edge Object which can be easily reconstructed
function abbreviateEdge(edge) {
  /* Omits the following properties:
  - edge.color, which is inferred from nodes.get(edge.to).color
  - edge.selectionWidth, which is always 2
  - edge.hoverWidth, which is always 0
  */
  var newedge = {a: edge.from,
                 b: edge.to,
                 c: edge.level};
  return newedge;
}

// Concisely JSON-ize the data needed to quickly reconstruct the network
function networkToJson() {
  var out = {};

  // Store nodes
  var data = nodes._data; // Retreive an object representing nodes data
  var vals = Object.keys(data).map(function(k){return data[k];});
  var abbv = vals.map(abbreviateNode); // Process it
  out.nodes = abbv; // Store it

  // Store startpages
  out.startpages = startpages;

  return JSON.stringify(out);
}

// DESERIALIZATION METHODS //

// Unabbreviate a node Object
function unabbreviateNode(node, startpgs) {
  // Make quick substitutions
  var newnode = {label: node.a,
                 level: node.b,
                 parent: node.c};
  // Infer omitted properties
  newnode.id = getNeutralId(newnode.label);
  newnode.color = getColor(newnode.level);
  newnode.value = startpgs.indexOf(newnode.id) === -1 ? 1:2;

  return newnode;
}

// Unabbreviate an edge Object.
function unabbreviateEdge(edge) {
  var newedge = {from: edge.a,
                 to: edge.b,
                 level: edge.c};
  newedge.color = getEdgeColor(newedge.level);
  newedge.selectionWidth = 2;
  newedge.hoverWidth = 0;

  return newedge;
}

// Reconstruct edges given a list of nodes
function buildEdges (nds) {
  var edgs = new vis.DataSet();
  for (var i = 0; i < nds.length; i++) {
    node = nds[i];
    if (node.parent != node.id) { // Don't create an edge from start nodes to themselves
      edgs.add({from: node.parent, to: node.id, color: getEdgeColor(node.level),
                level: node.level, selectionWidth: 2, hoverWidth:0});
    }
  }
  return edgs;
}

// Take consise JSON and use it to reconstruct `nodes` and `edges`
function networkFromJson(data) {
  // Get data
  data = JSON.parse(data);

  out = {};

  // Store startpages
  out.startpages = data.startpages;
  // Store nodes
  var nds = data.nodes;
  var expandedNodes = nds.map(function(x){return unabbreviateNode(x, out.startpages);});
  out.nodes = new vis.DataSet();
  out.nodes.add(expandedNodes);
  // Store edges
  out.edges = buildEdges(expandedNodes);

  return out;
}
<|endoftext|>


<commit_before>'use strict'
const render = require('./state')
module.exports = function renderMultiple (state, type, stamp, subs, tree, sType) {
  const _ = subs._
  if (sType === 'done') {
    if (_.dlist) {
      for (let i = 0, len = _.dlist.length; i < len; i += 3) {
        render(_.dlist[i + 2], state, type, stamp, subs, tree, _.dlist[i], _.dlist[i + 1])
      }
    }
  } else if (type !== 'update') {
    if (_.tList) {
      for (let i = 0, len = _.tList.length; i < len; i += 3) {
        render(_.tList[i + 2], state, type, stamp, subs, tree, _.tList[i], _.tList[i + 1])
      }
    }
  } else if (_.sList) {
    for (let i = 0, len = _.sList.length; i < len; i += 3) {
      render(_.sList[i + 2], state, type, stamp, subs, tree, _.sList[i], _.sList[i + 1])
    }
  }
}
<commit_msg>dList<commit_after>'use strict'
const render = require('./state')
module.exports = function renderMultiple (state, type, stamp, subs, tree, sType) {
  const _ = subs._
  if (sType === 'done') {
    if (_.dList) {
      for (let i = 0, len = _.dList.length; i < len; i += 3) {
        render(_.dList[i + 2], state, type, stamp, subs, tree, _.dList[i], _.dList[i + 1])
      }
    }
  } else if (type !== 'update') {
    if (_.tList) {
      for (let i = 0, len = _.tList.length; i < len; i += 3) {
        render(_.tList[i + 2], state, type, stamp, subs, tree, _.tList[i], _.tList[i + 1])
      }
    }
  } else if (_.sList) {
    for (let i = 0, len = _.sList.length; i < len; i += 3) {
      render(_.sList[i + 2], state, type, stamp, subs, tree, _.sList[i], _.sList[i + 1])
    }
  }
}
<|endoftext|>