<commit_before>/**
 * Audio Player
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the LICENSE.md file.
 *
 * @author Marcel Scherello <audioplayer@scherello.de>
 * @copyright 2016-2017 Marcel Scherello
 */

Audios.prototype.showSidebar = function (evt) {

    var trackid = $(evt.target).closest('li').attr('data-trackid');
    var fileid = $(evt.target).closest('li').attr('data-fileid');
    var $appsidebar = $("#app-sidebar");

    if ($appsidebar.data('trackid') === trackid) {
        $this.hideSidebar();
    } else {
        var getcoverUrl = OC.generateUrl('apps/audioplayer/getcover/');
        var trackData = $("li[data-trackid='" + trackid + "']");
        var cover = trackData.attr('data-cover');

        if (cover !== '') {
            //$('.thumbnailContainer').addClass('large');
            $('#sidebarThumbnail').attr({
                'style': 'background-image:url(' + getcoverUrl + cover + ')'
            }).addClass('larger');
        } else {
            //$('.thumbnailContainer').removeClass('large');
            $('#sidebarThumbnail').attr({
                'style': ''
            }).removeClass('larger');
        }

        $('#sidebarTitle').html(decodeURIComponent(trackData.attr('data-path')));
        $('#sidebarMime').html(trackData.attr('data-mimetype'));

        $('#sidebarFavorite').attr({'data-fileid': fileid})
            .on('click', $this.favoriteUpdate.bind($this));

        if ($appsidebar.data('trackid') === '') {
            $(".tabHeaders").empty();
            $(".tabsContainer").empty();
            $('#sidebarClose').click($this.hideSidebar.bind($this));
            $this.registerAudioplayerTab();
            $this.registerID3EditorTab();
            $this.registerPlaylistsTab();
            // noinspection JSUnresolvedFunction
            OC.Apps.showAppSidebar();
        }

        $appsidebar.data('trackid', trackid);
        $('.tabHeader.selected').click();
    }
};

Audios.prototype.registerPlaylistsTab = function () {
    var li = $('
').addClass('tabHeader')
        .attr({
            'id': 'tabHeaderPlaylists',
            'data-tabid': '3',
            'data-tabindex': '3'
        });
    var atag = $('').text(t('audioplayer', 'Playlists'));
    li.append(atag);
    $('.tabHeaders').append(li);

    var div = $('
').addClass('tab playlistsTabView')
        .attr({
            'id': 'playlistsTabView'
        });
    $('.tabsContainer').append(div);

    $('#tabHeaderPlaylists').click($this.playlistsTabView.bind($this));
};

Audios.prototype.registerAudioplayerTab = function () {
    var li = $('
').addClass('tabHeader selected')
        .attr({
            'id': 'tabHeaderAudiplayer',
            'data-tabid': '1',
            'data-tabindex': '1'
        });
    var atag = $('').text(t('audioplayer', 'Metadata'));
    li.append(atag);
    $('.tabHeaders').append(li);

    var div = $('
').addClass('tab audioplayerTabView')
        .attr({
            'id': 'audioplayerTabView'
        });
    $('.tabsContainer').append(div);

    $('#tabHeaderAudiplayer').click($this.audioplayerTabView.bind($this));
};

Audios.prototype.registerID3EditorTab = function () {
    var li = $('
').addClass('tabHeader')
        .attr({
            'id': 'tabHeaderID3Editor',
            'data-tabid': '2',
            'data-tabindex': '2'
        });
    var atag = $('').text(t('audioplayer', 'ID3 Editor'));
    li.append(atag);
    $('.tabHeaders').append(li);

    var div = $('
').addClass('tab ID3EditorTabView')
        .attr({
            'id': 'ID3EditorTabView'
        });
    $('.tabsContainer').append(div);

    if ($('#audioplayer_editor').val() === 'true') {
        $('#tabHeaderID3Editor').click($this.APEditorTabView.bind($this));
    } else {
        $('#tabHeaderID3Editor').click($this.ID3EditorTabView.bind($this));
    }
};

Audios.prototype.hideSidebar = function () {
    // noinspection JSUnresolvedFunction
    $("#app-sidebar").data('trackid', '');
    OC.Apps.hideAppSidebar();
    $(".tabHeaders").empty();
    $(".tabsContainer").empty();
};

Audios.prototype.audioplayerTabView = function () {
    var trackid = $("#app-sidebar").data('trackid');

    $this.resetView();
    $('#tabHeaderAudiplayer').addClass('selected');
    $('#audioplayerTabView').removeClass('hidden').html('

' + t('audioplayer', 'Reading data') + '

');

    $.ajax({
        type: 'GET',
        url: OC.generateUrl('apps/audioplayer/getaudioinfo'),
        data: {trackid: trackid},
        success: function (jsondata) {
            var table;
            if (jsondata.status === 'success') {

                table = $('
').css('display', 'table').addClass('table');
                var tablerow;
                var m;
                var tablekey;
                var tablevalue;

                var audioinfo = jsondata.data;
                for (m in audioinfo) {
                    tablerow = $('
').css('display', 'table-row');
                    tablekey = $('
').addClass('key').text(t('audioplayer', m));
                    tablevalue = $('
').addClass('value')
                        .text(audioinfo[m]);
                    tablerow.append(tablekey).append(tablevalue);

                    if (m === 'fav' && audioinfo[m] === 't') {
                        $('#sidebarFavorite').removeClass('icon-star')
                            .addClass('icon-starred')
                            .prop('title', t('files', 'Favorited'));
                        audioinfo[m] = '';
                    } else if (m === 'fav') {
                        $('#sidebarFavorite').removeClass('icon-starred')
                            .addClass('icon-star')
                            .prop('title', t('files', 'Favorite'));
                        audioinfo[m] = '';
                    }

                    if (audioinfo[m] !== '') {
                        table.append(tablerow);
                    }
                }
            } else {
                table = t('audioplayer', 'No Data');
            }

            $('#audioplayerTabView').html(table);
        }
    });
};

Audios.prototype.playlistsTabView = function () {
    var trackid = $("#app-sidebar").data('trackid');

    $this.resetView();
    $('#tabHeaderPlaylists').addClass('selected');
    $('#playlistsTabView').removeClass('hidden').html('

' + t('audioplayer', 'Reading data') + '

');

    $.ajax({
        type: 'POST',
        url: OC.generateUrl('apps/audioplayer/getplaylists'),
        data: {trackid: trackid},
        success: function (jsondata) {
            var table;
            if (jsondata.status === 'success') {

                table = $('
').css('display', 'table').addClass('table');
                var tablerow;
                var m;
                var tablekey;
                var tablevalue;

                var audioinfo = jsondata.data;
                for (m in audioinfo) {
                    var spanDelete = $('').attr({
                        'class': 'icon icon-delete toolTip',
                        'data-listid': audioinfo[m]['playlist_id'],
                        'data-trackid': trackid,
                        'title': t('audioplayer', 'Remove')
                    }).click($this.removeSongFromPlaylist.bind($this));

                    tablerow = $('
').css('display', 'table-row').attr({'data-id': audioinfo[m]['playlist_id']});
                    tablekey = $('
').addClass('key').append(spanDelete);

                    tablevalue = $('
').addClass('value')
                        .text(audioinfo[m]['name']);
                    tablerow.append(tablekey).append(tablevalue);
                    table.append(tablerow);
                }
            } else {
                table = '

' + t('audioplayer', 'No playlist entry') + '

';
            }

            $('#playlistsTabView').html(table);
        }
    });

};

Audios.prototype.ID3EditorTabView = function () {
    $this.resetView();
    $('#tabHeaderID3Editor').addClass('selected');
    $('#ID3EditorTabView').removeClass('hidden').html('

' + t('audioplayer', 'No ID3 editor installed') + '

');
};

Audios.prototype.resetView = function () {
    $('#tabHeaderAudiplayer').removeClass('selected');
    $('#tabHeaderPlaylists').removeClass('selected');
    $('#tabHeaderID3Editor').removeClass('selected');
    $('#audioplayerTabView').addClass('hidden');
    $('#playlistsTabView').addClass('hidden');
    $('#ID3EditorTabView').addClass('hidden');
};

Audios.prototype.removeSongFromPlaylist = function (evt) {

    var trackid = $(evt.target).attr('data-trackid');
    var playlist = $(evt.target).attr('data-listid');

    $.ajax({
        type: 'POST',
        url: OC.generateUrl('apps/audioplayer/removetrackfromplaylist'),
        data: {
            'playlistid': playlist,
            'songid': trackid
        },
        success: function (jsondata) {
            if (jsondata === true) {
                var currentCount = $('#myCategory li[data-id="' + playlist + '"]').find('.counter');
                currentCount.text(currentCount.text() - 1);
                $('#playlistsTabView div[data-id="' + playlist + '"]').remove()
            }
        }
    });
};
<commit_msg>information link to Audio Player Editor github<commit_after>/**
 * Audio Player
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the LICENSE.md file.
 *
 * @author Marcel Scherello <audioplayer@scherello.de>
 * @copyright 2016-2017 Marcel Scherello
 */

Audios.prototype.showSidebar = function (evt) {

    var trackid = $(evt.target).closest('li').attr('data-trackid');
    var fileid = $(evt.target).closest('li').attr('data-fileid');
    var $appsidebar = $("#app-sidebar");

    if ($appsidebar.data('trackid') === trackid) {
        $this.hideSidebar();
    } else {
        var getcoverUrl = OC.generateUrl('apps/audioplayer/getcover/');
        var trackData = $("li[data-trackid='" + trackid + "']");
        var cover = trackData.attr('data-cover');

        if (cover !== '') {
            //$('.thumbnailContainer').addClass('large');
            $('#sidebarThumbnail').attr({
                'style': 'background-image:url(' + getcoverUrl + cover + ')'
            }).addClass('larger');
        } else {
            //$('.thumbnailContainer').removeClass('large');
            $('#sidebarThumbnail').attr({
                'style': ''
            }).removeClass('larger');
        }

        $('#sidebarTitle').html(decodeURIComponent(trackData.attr('data-path')));
        $('#sidebarMime').html(trackData.attr('data-mimetype'));

        $('#sidebarFavorite').attr({'data-fileid': fileid})
            .on('click', $this.favoriteUpdate.bind($this));

        if ($appsidebar.data('trackid') === '') {
            $(".tabHeaders").empty();
            $(".tabsContainer").empty();
            $('#sidebarClose').click($this.hideSidebar.bind($this));
            $this.registerAudioplayerTab();
            $this.registerID3EditorTab();
            $this.registerPlaylistsTab();
            // noinspection JSUnresolvedFunction
            OC.Apps.showAppSidebar();
        }

        $appsidebar.data('trackid', trackid);
        $('.tabHeader.selected').click();
    }
};

Audios.prototype.registerPlaylistsTab = function () {
    var li = $('
').addClass('tabHeader')
        .attr({
            'id': 'tabHeaderPlaylists',
            'data-tabid': '3',
            'data-tabindex': '3'
        });
    var atag = $('').text(t('audioplayer', 'Playlists'));
    li.append(atag);
    $('.tabHeaders').append(li);

    var div = $('
').addClass('tab playlistsTabView')
        .attr({
            'id': 'playlistsTabView'
        });
    $('.tabsContainer').append(div);

    $('#tabHeaderPlaylists').click($this.playlistsTabView.bind($this));
};

Audios.prototype.registerAudioplayerTab = function () {
    var li = $('
').addClass('tabHeader selected')
        .attr({
            'id': 'tabHeaderAudiplayer',
            'data-tabid': '1',
            'data-tabindex': '1'
        });
    var atag = $('').text(t('audioplayer', 'Metadata'));
    li.append(atag);
    $('.tabHeaders').append(li);

    var div = $('
').addClass('tab audioplayerTabView')
        .attr({
            'id': 'audioplayerTabView'
        });
    $('.tabsContainer').append(div);

    $('#tabHeaderAudiplayer').click($this.audioplayerTabView.bind($this));
};

Audios.prototype.registerID3EditorTab = function () {
    var li = $('
').addClass('tabHeader')
        .attr({
            'id': 'tabHeaderID3Editor',
            'data-tabid': '2',
            'data-tabindex': '2'
        });
    var atag = $('').text(t('audioplayer', 'ID3 Editor'));
    li.append(atag);
    $('.tabHeaders').append(li);

    var div = $('
').addClass('tab ID3EditorTabView')
        .attr({
            'id': 'ID3EditorTabView'
        });
    $('.tabsContainer').append(div);

    if ($('#audioplayer_editor').val() === 'true') {
        $('#tabHeaderID3Editor').click($this.APEditorTabView.bind($this));
    } else {
        $('#tabHeaderID3Editor').click($this.ID3EditorTabView.bind($this));
    }
};

Audios.prototype.hideSidebar = function () {
    // noinspection JSUnresolvedFunction
    $("#app-sidebar").data('trackid', '');
    OC.Apps.hideAppSidebar();
    $(".tabHeaders").empty();
    $(".tabsContainer").empty();
};

Audios.prototype.audioplayerTabView = function () {
    var trackid = $("#app-sidebar").data('trackid');

    $this.resetView();
    $('#tabHeaderAudiplayer').addClass('selected');
    $('#audioplayerTabView').removeClass('hidden').html('

' + t('audioplayer', 'Reading data') + '

');

    $.ajax({
        type: 'GET',
        url: OC.generateUrl('apps/audioplayer/getaudioinfo'),
        data: {trackid: trackid},
        success: function (jsondata) {
            var table;
            if (jsondata.status === 'success') {

                table = $('
').css('display', 'table').addClass('table');
                var tablerow;
                var m;
                var tablekey;
                var tablevalue;

                var audioinfo = jsondata.data;
                for (m in audioinfo) {
                    tablerow = $('
').css('display', 'table-row');
                    tablekey = $('
').addClass('key').text(t('audioplayer', m));
                    tablevalue = $('
').addClass('value')
                        .text(audioinfo[m]);
                    tablerow.append(tablekey).append(tablevalue);

                    if (m === 'fav' && audioinfo[m] === 't') {
                        $('#sidebarFavorite').removeClass('icon-star')
                            .addClass('icon-starred')
                            .prop('title', t('files', 'Favorited'));
                        audioinfo[m] = '';
                    } else if (m === 'fav') {
                        $('#sidebarFavorite').removeClass('icon-starred')
                            .addClass('icon-star')
                            .prop('title', t('files', 'Favorite'));
                        audioinfo[m] = '';
                    }

                    if (audioinfo[m] !== '') {
                        table.append(tablerow);
                    }
                }
            } else {
                table = t('audioplayer', 'No Data');
            }

            $('#audioplayerTabView').html(table);
        }
    });
};

Audios.prototype.playlistsTabView = function () {
    var trackid = $("#app-sidebar").data('trackid');

    $this.resetView();
    $('#tabHeaderPlaylists').addClass('selected');
    $('#playlistsTabView').removeClass('hidden').html('

' + t('audioplayer', 'Reading data') + '

');

    $.ajax({
        type: 'POST',
        url: OC.generateUrl('apps/audioplayer/getplaylists'),
        data: {trackid: trackid},
        success: function (jsondata) {
            var table;
            if (jsondata.status === 'success') {

                table = $('
').css('display', 'table').addClass('table');
                var tablerow;
                var m;
                var tablekey;
                var tablevalue;

                var audioinfo = jsondata.data;
                for (m in audioinfo) {
                    var spanDelete = $('').attr({
                        'class': 'icon icon-delete toolTip',
                        'data-listid': audioinfo[m]['playlist_id'],
                        'data-trackid': trackid,
                        'title': t('audioplayer', 'Remove')
                    }).click($this.removeSongFromPlaylist.bind($this));

                    tablerow = $('
').css('display', 'table-row').attr({'data-id': audioinfo[m]['playlist_id']});
                    tablekey = $('
').addClass('key').append(spanDelete);

                    tablevalue = $('
').addClass('value')
                        .text(audioinfo[m]['name']);
                    tablerow.append(tablekey).append(tablevalue);
                    table.append(tablerow);
                }
            } else {
                table = '

' + t('audioplayer', 'No playlist entry') + '

';
            }

            $('#playlistsTabView').html(table);
        }
    });

};

Audios.prototype.ID3EditorTabView = function () {
    $this.resetView();
    $('#tabHeaderID3Editor').addClass('selected');
    var html = '
';
    html += '';
    html += '
' + t('audioplayer', 'No ID3 editor installed') + '
';
    html += '
';
    $('#ID3EditorTabView').removeClass('hidden').html(html);
};

Audios.prototype.resetView = function () {
    $('#tabHeaderAudiplayer').removeClass('selected');
    $('#tabHeaderPlaylists').removeClass('selected');
    $('#tabHeaderID3Editor').removeClass('selected');
    $('#audioplayerTabView').addClass('hidden');
    $('#playlistsTabView').addClass('hidden');
    $('#ID3EditorTabView').addClass('hidden');
};

Audios.prototype.removeSongFromPlaylist = function (evt) {

    var trackid = $(evt.target).attr('data-trackid');
    var playlist = $(evt.target).attr('data-listid');

    $.ajax({
        type: 'POST',
        url: OC.generateUrl('apps/audioplayer/removetrackfromplaylist'),
        data: {
            'playlistid': playlist,
            'songid': trackid
        },
        success: function (jsondata) {
            if (jsondata === true) {
                var currentCount = $('#myCategory li[data-id="' + playlist + '"]').find('.counter');
                currentCount.text(currentCount.text() - 1);
                $('#playlistsTabView div[data-id="' + playlist + '"]').remove()
            }
        }
    });
};
<|endoftext|>


<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
    Firebase.goOnline();
});

// Select the services
function selectServices(tipe) {
  console.log('User choose: ' + tipe);
  window.location.href = tipe + '/index.html';
}

// Select faskes function
function selectFaskes(username) {
  url = '../faskes/' + username + '.html';
  window.location.href = url;
}

// Puskesmas form action
function puskesmas() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	puskesmas = ref.child("puskesmas"),
	pasien = puskesmas.child("pasien");

	// Input value
	var nama = $('#nama').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val();

	if (nama == '') {
		// Validate name input
		alert('Nama is not filled');
	} else if (nik < 16) {
	  // Validate nik input
    alert('NIK anda kurang panjang');
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
	} else {
      // Log input value for testing
      console.log('Nama: ' + nama);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        nik: nik,
       lokasi: lokasi
     });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		  };
	}
};

// RSUD form action
function rsud() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	rsud = ref.child("rsud"),
	pasien = rsud.child("pasien");

	// Input value
  var nama = $('#nama').val(),
	rujuk = $('#rujuk').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val(),
	input = $('.input-rsud').val();

	if (input == '') {
		// Validate rujuk rsud input
		alert('Input is not filled');
	} else if (nik < 16) {
	  alert('NIK anda kurang panjang');
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
	} else if (rujuk != 20) {
	  alert('Nomor rujuk anda tidak valid');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		 };
	}
};

// RSUK form action
function rsuk() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	rsuk = ref.child("rsuk"),
	pasien = rsuk.child("pasien");

	// Input value
  var nama = $('#nama').val(),
	rujuk = $('#rujuk').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val(),
	input = $('.input-rsuk').val();

	if (input == '') {
		// Validate rujuk rsuk input
		alert('Input is not filled');
	} else if (nik < 16) {
	  alert('NIK anda kurang panjang');
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
	} else if (rujuk != 20) {
	  alert('Nomor rujuk anda tidak valid');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 };
	}
};

// RSS form action
function rss() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	rss = ref.child("rss"),
	pasien = rss.child("pasien");

	// Input value
  var nama = $('#nama').val(),
	rujuk = $('#rujuk').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val(),
	input = $('.input-rss').val();

	if (input == '') {
		// Validate rujuk rss input
		alert('Input is not filled');
	} else if (nik < 16) {
	  alert('NIK anda kurang panjang');
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
	} else if (rujuk != 20) {
	  alert('Nomor rujuk anda tidak valid');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 };
	}
}
<commit_msg>Log for testing<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
    Firebase.goOnline();
});

// Select the services
function selectServices(tipe) {
  console.log('User choose: ' + tipe);
  window.location.href = tipe + '/index.html';
}

// Select faskes function
function selectFaskes(username) {
  url = '../faskes/' + username + '.html';
  window.location.href = url;
}

// Puskesmas form action
function puskesmas() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	puskesmas = ref.child("puskesmas"),
	pasien = puskesmas.child("pasien");

	// Input value
	var nama = $('#nama').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val();

	if (nama == '') {
		// Validate name input
		alert('Nama is not filled');
	} else if (nik < 16) {
	  // Validate nik input
    alert('NIK anda kurang panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else {
      // Log input value for testing
      console.log('Nama: ' + nama);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        nik: nik,
       lokasi: lokasi
     });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		  };
	}
};

// RSUD form action
function rsud() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	rsud = ref.child("rsud"),
	pasien = rsud.child("pasien");

	// Input value
  var nama = $('#nama').val(),
	rujuk = $('#rujuk').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val(),
	input = $('.input-rsud').val();

	if (input == '') {
		// Validate rujuk rsud input
		alert('Input is not filled');
	} else if (nik < 16) {
	  alert('NIK anda kurang panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (rujuk != 20) {
	  alert('Nomor rujuk anda tidak valid');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		 };
	}
};

// RSUK form action
function rsuk() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	rsuk = ref.child("rsuk"),
	pasien = rsuk.child("pasien");

	// Input value
  var nama = $('#nama').val(),
	rujuk = $('#rujuk').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val(),
	input = $('.input-rsuk').val();

	if (input == '') {
		// Validate rujuk rsuk input
		alert('Input is not filled');
	} else if (nik < 16) {
	  alert('NIK anda kurang panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (rujuk != 20) {
	  alert('Nomor rujuk anda tidak valid');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 };
	}
};

// RSS form action
function rss() {
	// Firebase
  var ref = new Firebase("https://cepatsembuh.firebaseio.com/"),
	rss = ref.child("rss"),
	pasien = rss.child("pasien");

	// Input value
  var nama = $('#nama').val(),
	rujuk = $('#rujuk').val(),
	nik = $('#nik').val(),
	lokasi = $('#lokasi').val(),
	input = $('.input-rss').val();

	if (input == '') {
		// Validate rujuk rss input
		alert('Input is not filled');
	} else if (nik < 16) {
	  alert('NIK anda kurang panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (nik > 16) {
	  alert('NIK anda terlalu panjang');
    // Log for testing
    console.log('NIK length: ' + nik.length);
	} else if (rujuk != 20) {
	  alert('Nomor rujuk anda tidak valid');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 };
	}
}
<|endoftext|>


<commit_before>---
layout: nil
---

var sidebar = {};

{% for cat in site.categories-list %}
sidebar["{{ cat }}"] = [];
{% for page in site.pages %}{% if page.categories == cat %}{% if page.parent != null %}
sidebar["{{ cat }}"].push({url:"{{ page.url }}", parent: "{{ page.parent }}", weight:{% if page.weight != null %} {{ page.weight }}{% else %} 0{% endif %}, title: "{{ page.title }}"});
{% endif %}{% endif %}{% endfor %}{% endfor %}

function transformArr(orig) {
  var newArr = [],
  parents = {},
  newItem, i, j, cur, x, y;
  for (i = 0, j = orig.length; i < j; i++) {
    cur = orig[i];
    if (!(cur.parent in parents)) {
      parents[cur.parent] = {parent: cur.parent, urls: []};
      newArr.push(parents[cur.parent]);
    }
    parents[cur.parent].urls.push({url:cur.url, weight:cur.weight, title:cur.title});
  }

  for (i = 0, j = newArr.length; i < j; i++) {
    newArr[i]['urls'] = newArr[i]['urls'].sort(function(a,b) {
      return(a.weight - b.weight)
    });
    for (x = 0, y = newArr[i]['urls'].length; x < y; x++) {
      delete newArr[i]['urls'][x]['weight'];
    }
  }

  return newArr;
}

function makeSideBar(orig, space) {
  without_parent = orig.filter(function(x) {return x.parent == 'none'})[0];
  with_parent = orig.filter(function(x) {return x.parent != 'none'});

  parent_html = makeParentMenu(without_parent, space);
  parent_object = $('
').html(parent_html).contents();

  // dangerous recursion
  // Not finished yet, don't use this

  var counter = 0;
  while (with_parent.length != 0) {
    counter += 1;
    if (with_parent.length > 2) {
      var current_child = with_parent[~~(Math.random()*with_parent.length)];
    } else if (with_parent.length == 2) {
      var current_child = with_parent[Math.round(Math.random())];
    } else {
      var current_child = with_parent[0];
    }

    sidebar_url = '[href$="' + current_child['parent'] + '"]';
    find_a = parent_object.find(sidebar_url);
    if (find_a.length != 0) {
      with_parent = $.grep(with_parent, function(value) { return(value != current_child) });
      find_a.after("\n" + makeChildMenu(current_child) + "\n");
    }

    //failsafe 200 times iteration
    if (counter == 200) {
      with_parent = [];
    }

  }
  return parent_object.prop("outerHTML")
}

function makeParentMenu(orig, space) {
  output = "
\n";
  var i, j;
  for (i = 0, j = orig['urls'].length; i < j; i++) {
    var curr_menu = orig['urls'][i];
    output += '
' + curr_menu['title'] + "
\n";
  }
  output += "
";
  return output
}

function makeChildMenu(orig) {
  output = "
\n";
  var ci, cj;
  for (ci = 0, cj = orig['urls'].length; ci < cj; ci++) {
    var curr_menu = orig['urls'][ci];
    output += '
' + curr_menu['title'] + "
\n";
  }
  output += "
";
  return output
}

function createBreadcrumbs(category, currentSection) {

  if (sidebar[category]) {
    var locations = [];
    var currentPath = location.pathname;
    var currentCrumb = sidebar[category].filter(function(x) {return x.url == currentPath})[0]
    while (currentCrumb) {
      locations.unshift(currentCrumb);
      if (currentCrumb.parent == "none") break;
      currentPath = "/" + category.toLowerCase() + "/" + currentCrumb.parent;
      currentCrumb = sidebar[category].filter(function(x) {return x.url == currentPath})[0]
    }
  }

  var breadcrumbsHtml = "
";
  breadcrumbsHtml += "
Home
";
  breadcrumbsHtml += "
" + currentSection + "
";
  if (locations.length > 0) {
    for (var i=0; i<locations.length; i++) {
      breadcrumbsHtml += "
" + locations[i].title + "
";
    }
  }
  breadcrumbsHtml += "
";
  $("#breadcrumbs").append(breadcrumbsHtml);

}

<commit_msg>fix url finder in the sidebar creator<commit_after>---
layout: nil
---

var sidebar = {};

{% for cat in site.categories-list %}
sidebar["{{ cat }}"] = [];
{% for page in site.pages %}{% if page.categories == cat %}{% if page.parent != null %}
sidebar["{{ cat }}"].push({url:"{{ page.url }}", parent: "{{ page.parent }}", weight:{% if page.weight != null %} {{ page.weight }}{% else %} 0{% endif %}, title: "{{ page.title }}"});
{% endif %}{% endif %}{% endfor %}{% endfor %}

function transformArr(orig) {
  var newArr = [],
  parents = {},
  newItem, i, j, cur, x, y;
  for (i = 0, j = orig.length; i < j; i++) {
    cur = orig[i];
    if (!(cur.parent in parents)) {
      parents[cur.parent] = {parent: cur.parent, urls: []};
      newArr.push(parents[cur.parent]);
    }
    parents[cur.parent].urls.push({url:cur.url, weight:cur.weight, title:cur.title});
  }

  for (i = 0, j = newArr.length; i < j; i++) {
    newArr[i]['urls'] = newArr[i]['urls'].sort(function(a,b) {
      return(a.weight - b.weight)
    });
    for (x = 0, y = newArr[i]['urls'].length; x < y; x++) {
      delete newArr[i]['urls'][x]['weight'];
    }
  }

  return newArr;
}

function makeSideBar(orig, space) {
  without_parent = orig.filter(function(x) {return x.parent == 'none'})[0];
  with_parent = orig.filter(function(x) {return x.parent != 'none'});

  parent_html = makeParentMenu(without_parent, space);
  parent_object = $('
').html(parent_html).contents();

  // dangerous recursion
  // Not finished yet, don't use this

  var counter = 0;
  while (with_parent.length != 0) {
    counter += 1;
    if (with_parent.length > 2) {
      var current_child = with_parent[~~(Math.random()*with_parent.length)];
    } else if (with_parent.length == 2) {
      var current_child = with_parent[Math.round(Math.random())];
    } else {
      var current_child = with_parent[0];
    }

    sidebar_url = '[href$="' + current_child['parent'] + '"]';
    find_a = parent_object.find(decodeURI(sidebar_url));
    if (find_a.length != 0) {
      with_parent = $.grep(with_parent, function(value) { return(value != current_child) });
      find_a.after("\n" + makeChildMenu(current_child) + "\n");
    }

    //failsafe 200 times iteration
    if (counter == 600) {
      with_parent = [];
    }

  }
  return parent_object.prop("outerHTML")
}

function makeParentMenu(orig, space) {
  output = "
\n";
  var i, j;
  for (i = 0, j = orig['urls'].length; i < j; i++) {
    var curr_menu = orig['urls'][i];
    output += '
' + curr_menu['title'] + "
\n";
  }
  output += "
";
  return output
}

function makeChildMenu(orig) {
  output = "
\n";
  var ci, cj;
  for (ci = 0, cj = orig['urls'].length; ci < cj; ci++) {
    var curr_menu = orig['urls'][ci];
    output += '
' + curr_menu['title'] + "
\n";
  }
  output += "
";
  return output
}

function createBreadcrumbs(category, currentSection) {

  if (sidebar[category]) {
    var locations = [];
    var currentPath = location.pathname;
    var currentCrumb = sidebar[category].filter(function(x) {return x.url == currentPath})[0]
    while (currentCrumb) {
      locations.unshift(currentCrumb);
      if (currentCrumb.parent == "none") break;
      currentPath = "/" + category.toLowerCase() + "/" + currentCrumb.parent;
      currentCrumb = sidebar[category].filter(function(x) {return x.url == currentPath})[0]
    }
  }

  var breadcrumbsHtml = "
";
  breadcrumbsHtml += "
Home
";
  breadcrumbsHtml += "
" + currentSection + "
";
  if (locations.length > 0) {
    for (var i=0; i<locations.length; i++) {
      breadcrumbsHtml += "
" + locations[i].title + "
";
    }
  }
  breadcrumbsHtml += "
";
  $("#breadcrumbs").append(breadcrumbsHtml);

}

<|endoftext|>


<commit_before>/**
 *
 * @param lvl {number} level number
 */
this['@lib/spawnLevel'] = function(lvl){
    var my = this;
    var typeMap = {
        '*': 'levelWall',
        'w': 'wall',
        '@': 'player',
        '>': 'rightSpawn',
        '<': 'leftSpawn',
        '^': 'upSpawn',
        'v': 'downSpawn',
        'R': 'rightMark',
        'L': 'leftMark',
        'U': 'upMark',
        'D': 'downMark',
        'X': 'exit'
    };
    this._.patch(constants.path.PLAYER_LEVEL, lvl);
    return this._.lib.parser.parse(this._.selectOne("lib/levels/level" + lvl), function(x, y, type, params, param) {
        let dna = typeMap[type];
        if (dna){
            let entity = my._.sys.spawn('dna/' + dna, 'lab/camera', {
                x: x,
                y: y,
            });
            if (dna === 'player') {
                my._.lab.camera.follow(entity);
            }
        } else if (type.length == 0){
            console.error("Type is empty");
        }  else if (type != " "){
                console.error("No such type [" + type + "]");
        }
    });
};

this['@lib/spawnNextLevel'] = function(lvl){
    return this._.lib.spawnLevel(this._.selectOneNumber(constants.path.PLAYER_LEVEL) + 1);
};
<commit_msg>[-] fixed patch in lvl<commit_after>/**
 *
 * @param lvl {number} level number
 */
this['@lib/spawnLevel'] = function(lvl){
    var my = this;
    var typeMap = {
        '*': 'levelWall',
        'w': 'wall',
        '@': 'player',
        '>': 'rightSpawn',
        '<': 'leftSpawn',
        '^': 'upSpawn',
        'v': 'downSpawn',
        'R': 'rightMark',
        'L': 'leftMark',
        'U': 'upMark',
        'D': 'downMark',
        'X': 'exit'
    };
    this._.patch(this._, constants.path.PLAYER_LEVEL, lvl);
    return this._.lib.parser.parse(this._.selectOne("lib/levels/level" + lvl), function(x, y, type, params, param) {
        let dna = typeMap[type];
        if (dna){
            let entity = my._.sys.spawn('dna/' + dna, 'lab/camera', {
                x: x,
                y: y,
            });
            if (dna === 'player') {
                my._.lab.camera.follow(entity);
            }
        } else if (type.length == 0){
            console.error("Type is empty");
        }  else if (type != " "){
                console.error("No such type [" + type + "]");
        }
    });
};

this['@lib/spawnNextLevel'] = function(lvl){
    return this._.lib.spawnLevel(this._.selectOneNumber(constants.path.PLAYER_LEVEL) + 1);
};
<|endoftext|>


<commit_before>'use strict';

$.nette.ext('resizableTextareaRefresh', {
	complete: function () {
		PeerBlender.Chat.resizeTextarea();
		autosize($('#chat textarea'));
	}
});

$.nette.ext('forms', false);
$.nette.ext('forms', {
	init: function () {
		var snippets;
		if (!window.Nette || !(snippets = this.ext('snippets'))) return;

		snippets.after(function ($el) {
			$el.find('form').each(function() {
				window.Nette.initForm(this);
			});

			PeerBlender.Highlighting.refreshIframes();
		});
	},
	prepare: function (settings) {
		var analyze = settings.nette;
		if (!analyze || !analyze.form) return;
		var e = analyze.e;
		var originalData = settings.data || {};
		var data = {};

		if (analyze.isSubmit) {
			data[analyze.el.attr('name')] = analyze.el.val() || '';
		} else if (analyze.isImage) {
			var offset = analyze.el.offset();
			var name = analyze.el.attr('name');
			var dataOffset = [ Math.max(0, e.pageX - offset.left), Math.max(0, e.pageY - offset.top) ];

			if (name.indexOf('[', 0) !== -1) { // inside a container
				data[name] = dataOffset;
			} else {
				data[name + '.x'] = dataOffset[0];
				data[name + '.y'] = dataOffset[1];
			}
		}

		// https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects#Sending_files_using_a_FormData_object
		if (analyze.form.attr('method').toLowerCase() === 'post' && 'FormData' in window) {
			var formData = new FormData(analyze.form[0]);
			for (var i in data) {
				formData.append(i, data[i]);
			}

			if (typeof originalData !== 'string') {
				for (var i in originalData) {
					formData.append(i, originalData[i]);
				}
			}

			settings.data = formData;
			settings.processData = false;
			settings.contentType = false;
		} else {
			if (typeof originalData !== 'string') {
				originalData = $.param(originalData);
			}
			data = $.param(data);
			settings.data = analyze.form.serialize() + (data ? '&' + data : '') + '&' + originalData;
		}
	}
});

var PeerBlender = {
	baseUri: '',
	outdatedIframes: [],

	init: function() {
		$.nette.ext('status', {
			start: function() {
				$('#quick-save-button i.fa').attr('class', 'fa');
				$('#quick-save-button i.fa').addClass('fa-spinner fa-spin');

			},
			complete: function() {
				$('#quick-save-button i.fa').attr('class', 'fa');
				$('#quick-save-button i.fa').addClass('fa-check');
				setTimeout(function() {
					$('#quick-save-button i.fa').removeClass('fa-check');
					$('#quick-save-button i.fa').addClass('fa-save');
				}, 2000);
			},
			error: function(xhr, status, error) {
				//var err = eval("(" +  + ")");
				$('#quick-save-button i.fa').attr('class', 'fa');
				$('#quick-save-button i.fa').addClass('fa-exclamation-triangle');
			}
		});
		$.nette.ext('flash', {
			complete: function () {
				$('.flashMessages').animate({
					opacity: 1.0
				}, 4000).fadeOut(700);
			}
		});
		$.nette.init();

		this.ThirdParty.init();
		this.Highlighting.init();
		//this.Chat.init();
		this.Review.init();

		$('a[href^=http]').attr('target', '_blank');
	},

	ThirdParty: {
		init: function() {
			$(document).foundation();

			$(".tablesorter").tablesorter();
		}
	},

	Review: {
		init: function() {
			var reviewOngoing = ($('.assignmentQuestion input:radio').length > 0 || $('.assignmentQuestion input:checkbox').length > 0);
			if (reviewOngoing) {
				this.updateScore();
				$(document).on('change', '.assignmentQuestion input:radio, .assignmentQuestion input:checkbox', this.updateScore);
				$(document).on('change', '#frm-reviewForm-solutionIsComplete', this.updateScore);
			}

		},

		updateScore: function() {
			var allAnswered = true;
			$('.assignmentQuestion input:radio').each(function(){
				if($(':radio[name="'+$(this).attr('name')+'"]:checked').length == 0)
				{
					allAnswered = false;
				}
			});

			$('#totalScore span').text(allAnswered ? PeerBlender.Review.calculateScore() : '—');
		},

		calculateScore: function() {
			var values = [];
			var solutionIsCompleteMultiplier = 1;

			$.each($('.assignmentQuestion.model-ontology-rubric input:radio').serializeArray(), function(i, rubric) {
				values.push(rubric.value);
			});

			$.each($('.model-ontology-checklist'), function(i, checklist) {
				var labels = $(checklist).find('label');
				var totalWeight = 0;
				var totalScore = 0;
				var maxScore = 3;
				$.each($(labels), function(i, label) {
					if ($(label).find('.weight').length) {
						var weight = parseFloat($(label).find('.weight').text());
						totalWeight += weight;

						var checked = $(label).find('input').is(':checked');
						if (checked) {
							totalScore += weight;
						}
					}
				});
				var score = maxScore/totalWeight*totalScore;

				$(checklist).find('.calcWeightedScore').remove();
				$(checklist).append('
' + Math.round(score*100)/100 + '
');
				values.push(score);
			});

			if ($('#frm-reviewForm-solutionIsComplete:checked').length == 0) {
				solutionIsCompleteMultiplier = 0.5;
			}

			if (values.length == 0) {
				return '—';
			} else {
				return Math.round(this.average(values)*solutionIsCompleteMultiplier*100)/100;
			}
		},

		average: function(arr) {
			var sum = 0;
			for (var i = 0; i < arr.length; i++) {
				sum += parseFloat(arr[i], 10);
			}
			return sum/arr.length;
		}
	},

	Highlighting: {
		editors: [],

		init: function() {
			$('button.answerPreview').click(function(e) {
				var editorCount = PeerBlender.Highlighting.editors.length;
				for (var i = 0; i < editorCount; i++) {
					PeerBlender.Highlighting.editors[i].save();
				}

				var hlType = $(this).attr('type');
				if (hlType == 'highlight-javascript') {
					var answer = $(this).closest('.assignmentQuestion').find('textarea').val();
					$('#previewForm textarea[name="answer"]').text(answer);
					$('#previewForm')[0].submit();
				} else if (/^highlight-turtle/.test(hlType)) {
					var iframe = $(this).closest('.assignmentQuestion').find('iframe').first();
					var answerId = iframe.data('answerId');
					var location = iframe.attr('src');
					var newLocation = '';
					switch (hlType) {
						case 'highlight-turtle':
							newLocation = '/code-preview/turtle/' + answerId;
							break;
						case 'highlight-turtle-na':
							newLocation = '/code-preview/turtle/' + answerId + '?animated=0';
							break;
						default:
							newLocation = location;
					}

					PeerBlender.outdatedIframes.push({
						iframe: iframe,
						location: newLocation
					});

					var quickSaveButton = $('#quick-save-button');
					if (quickSaveButton.length) {
						setTimeout(function() {
							$('#quick-save-button').trigger('click');
						}, 2000);
					} else {
						PeerBlender.Highlighting.refreshIframes();
					}
				}

				e.preventDefault();
			});

			$('button.showPrefill').click(function(e) {
				var prefillViewer = $(this).closest('.assignmentQuestion').find('.prefill');
				prefillViewer.toggle('fast');
				if (!prefillViewer.hasClass('ready')) {
					PeerBlender.Highlighting.initCodeMirror(prefillViewer.find('textarea'));
					prefillViewer.addClass('ready');
				}

				e.preventDefault();
			});

			$('.assignmentQuestion textarea[class*="highlight-"]').each(function() {
				PeerBlender.Highlighting.initCodeMirror($(this));
			});

			$('#quick-save-button').click(function(e) {
				for (var i = 0; i < PeerBlender.Highlighting.editors.length; i++) {
					PeerBlender.Highlighting.editors[i].save();
				}
			});

			PeerBlender.Highlighting.initStickyIframes();
		},

		initCodeMirror: function(textarea) {
			var className = textarea.attr('class');
			if (!className) {
				return;
			}
			var mode = className.match(/highlight-([a-z]+)/)[1];
			var gutters = [];
			var lint = false;

			switch (mode) {
				case 'code':
				case 'markdown':
				case 'css':
				case 'sql':
				case 'xml':
					var highlightingMode = mode;
					break;
				case 'javascript':
					var highlightingMode = mode;
					lint = true;
					gutters = ["CodeMirror-lint-markers"];
					break;
				case 'html':
					var highlightingMode = 'htmlmixed';
					break;
				default:
					return;
			}

			var myCodeMirror = CodeMirror.fromTextArea(
				textarea[0], {
					lineNumbers: true,
					lineWrapping: true,
					mode: highlightingMode,
					lint: true,
					gutters: ["CodeMirror-lint-markers"],
					viewportMargin: Infinity,
					readOnly: textarea.hasClass('readonly') ? 'true' : false
				}
			);

			PeerBlender.Highlighting.editors.push(myCodeMirror);
		},

		initStickyIframes: function() {
			/*window.addEventListener('scroll', function() {
				var turtlePreviewHeight = 400;
				var previews = document.querySelectorAll('iframe.turtle-preview');

				for (var i = previews.length - 1; i >= 0; i--) {
					var iframe = previews[i];
					var codeColumn = document.querySelector('iframe.turtle-preview').parentNode.previousElementSibling.getBoundingClientRect();
					var height = codeColumn.height - 183;
					var top = codeColumn.top;
					if (codeColumn.height > turtlePreviewHeight + 100 && top < 0) {
						var translate = -top > turtlePreviewHeight ? turtlePreviewHeight : -top;
						iframe.style.transform = 'translate(0px, ' + (translate) + 'px)';
					} else {
						iframe.style.position = 'static';
						iframe.style.top = '';
						iframe.style.transform = '';
						iframe.style.width = '100%';
					}
				}
			});*/
		},

		refreshIframes: function() {
			for (var i = PeerBlender.outdatedIframes.length - 1; i >= 0; i--) {
				var item = PeerBlender.outdatedIframes[i];
				item.iframe.attr('src', item.location);

				PeerBlender.outdatedIframes.splice(i, 1);
			}
		}
	},

	Chat: {
		refresh: null,

		init: function() {
			if ($('#chat').length) {
				autosize($('#chat textarea'));
				$('#chat').show();

				$(document).on('click', '#chat .header', function() {
					if ($("#chat").height() > 400) {
						$("#chat .chatContent").hide();
						$("#chat").css({height: '30px', width: '100px'});
					} else {
						$("#chat .chatContent").show();
						$("#chat").css({height: '500px', width: '400px'});
					}

				});

				document.querySelector('#chat textarea').addEventListener('autosize:resized', function() {
					PeerBlender.Chat.resizeTextarea();
				});

				PeerBlender.Chat.refresh = setTimeout(function(){PeerBlender.Chat.refreshChat()}, 3*1000);
			}
		},

		resizeTextarea: function() {
			var messages = $('#chat .messages');
			messages.height(430 - $('#chat textarea').height());
			$('#chat .messages').scrollTop(document.querySelector('#chat .messages').scrollHeight);
		},

		refreshChat: function(courseId) {
			$.nette.ajax({
				url: '/generated/chat/' + 2 + '.html',
				complete: function (payload) {
					var messages = $('#chat .messages');
					messages.html(payload.responseText);
					PeerBlender.Chat.resizeTextarea();
					PeerBlender.Chat.refresh = setTimeout(function(courseId){PeerBlender.Chat.refreshChat(2)}, 3*1000);
				}
			});
		}
	}
}<commit_msg>Quicker submit<commit_after>'use strict';

$.nette.ext('resizableTextareaRefresh', {
	complete: function () {
		PeerBlender.Chat.resizeTextarea();
		autosize($('#chat textarea'));
	}
});

$.nette.ext('forms', false);
$.nette.ext('forms', {
	init: function () {
		var snippets;
		if (!window.Nette || !(snippets = this.ext('snippets'))) return;

		snippets.after(function ($el) {
			$el.find('form').each(function() {
				window.Nette.initForm(this);
			});

			PeerBlender.Highlighting.refreshIframes();
		});
	},
	prepare: function (settings) {
		var analyze = settings.nette;
		if (!analyze || !analyze.form) return;
		var e = analyze.e;
		var originalData = settings.data || {};
		var data = {};

		if (analyze.isSubmit) {
			data[analyze.el.attr('name')] = analyze.el.val() || '';
		} else if (analyze.isImage) {
			var offset = analyze.el.offset();
			var name = analyze.el.attr('name');
			var dataOffset = [ Math.max(0, e.pageX - offset.left), Math.max(0, e.pageY - offset.top) ];

			if (name.indexOf('[', 0) !== -1) { // inside a container
				data[name] = dataOffset;
			} else {
				data[name + '.x'] = dataOffset[0];
				data[name + '.y'] = dataOffset[1];
			}
		}

		// https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects#Sending_files_using_a_FormData_object
		if (analyze.form.attr('method').toLowerCase() === 'post' && 'FormData' in window) {
			var formData = new FormData(analyze.form[0]);
			for (var i in data) {
				formData.append(i, data[i]);
			}

			if (typeof originalData !== 'string') {
				for (var i in originalData) {
					formData.append(i, originalData[i]);
				}
			}

			settings.data = formData;
			settings.processData = false;
			settings.contentType = false;
		} else {
			if (typeof originalData !== 'string') {
				originalData = $.param(originalData);
			}
			data = $.param(data);
			settings.data = analyze.form.serialize() + (data ? '&' + data : '') + '&' + originalData;
		}
	}
});

var PeerBlender = {
	baseUri: '',
	outdatedIframes: [],

	init: function() {
		$.nette.ext('status', {
			start: function() {
				$('#quick-save-button i.fa').attr('class', 'fa');
				$('#quick-save-button i.fa').addClass('fa-spinner fa-spin');

			},
			complete: function() {
				$('#quick-save-button i.fa').attr('class', 'fa');
				$('#quick-save-button i.fa').addClass('fa-check');
				setTimeout(function() {
					$('#quick-save-button i.fa').removeClass('fa-check');
					$('#quick-save-button i.fa').addClass('fa-save');
				}, 2000);
			},
			error: function(xhr, status, error) {
				//var err = eval("(" +  + ")");
				$('#quick-save-button i.fa').attr('class', 'fa');
				$('#quick-save-button i.fa').addClass('fa-exclamation-triangle');
			}
		});
		$.nette.ext('flash', {
			complete: function () {
				$('.flashMessages').animate({
					opacity: 1.0
				}, 4000).fadeOut(700);
			}
		});
		$.nette.init();

		this.ThirdParty.init();
		this.Highlighting.init();
		//this.Chat.init();
		this.Review.init();

		$('a[href^=http]').attr('target', '_blank');
	},

	ThirdParty: {
		init: function() {
			$(document).foundation();

			$(".tablesorter").tablesorter();
		}
	},

	Review: {
		init: function() {
			var reviewOngoing = ($('.assignmentQuestion input:radio').length > 0 || $('.assignmentQuestion input:checkbox').length > 0);
			if (reviewOngoing) {
				this.updateScore();
				$(document).on('change', '.assignmentQuestion input:radio, .assignmentQuestion input:checkbox', this.updateScore);
				$(document).on('change', '#frm-reviewForm-solutionIsComplete', this.updateScore);
			}

		},

		updateScore: function() {
			var allAnswered = true;
			$('.assignmentQuestion input:radio').each(function(){
				if($(':radio[name="'+$(this).attr('name')+'"]:checked').length == 0)
				{
					allAnswered = false;
				}
			});

			$('#totalScore span').text(allAnswered ? PeerBlender.Review.calculateScore() : '—');
		},

		calculateScore: function() {
			var values = [];
			var solutionIsCompleteMultiplier = 1;

			$.each($('.assignmentQuestion.model-ontology-rubric input:radio').serializeArray(), function(i, rubric) {
				values.push(rubric.value);
			});

			$.each($('.model-ontology-checklist'), function(i, checklist) {
				var labels = $(checklist).find('label');
				var totalWeight = 0;
				var totalScore = 0;
				var maxScore = 3;
				$.each($(labels), function(i, label) {
					if ($(label).find('.weight').length) {
						var weight = parseFloat($(label).find('.weight').text());
						totalWeight += weight;

						var checked = $(label).find('input').is(':checked');
						if (checked) {
							totalScore += weight;
						}
					}
				});
				var score = maxScore/totalWeight*totalScore;

				$(checklist).find('.calcWeightedScore').remove();
				$(checklist).append('
' + Math.round(score*100)/100 + '
');
				values.push(score);
			});

			if ($('#frm-reviewForm-solutionIsComplete:checked').length == 0) {
				solutionIsCompleteMultiplier = 0.5;
			}

			if (values.length == 0) {
				return '—';
			} else {
				return Math.round(this.average(values)*solutionIsCompleteMultiplier*100)/100;
			}
		},

		average: function(arr) {
			var sum = 0;
			for (var i = 0; i < arr.length; i++) {
				sum += parseFloat(arr[i], 10);
			}
			return sum/arr.length;
		}
	},

	Highlighting: {
		editors: [],

		init: function() {
			$('button.answerPreview').click(function(e) {
				var editorCount = PeerBlender.Highlighting.editors.length;
				for (var i = 0; i < editorCount; i++) {
					PeerBlender.Highlighting.editors[i].save();
				}

				var hlType = $(this).attr('type');
				if (hlType == 'highlight-javascript') {
					var answer = $(this).closest('.assignmentQuestion').find('textarea').val();
					$('#previewForm textarea[name="answer"]').text(answer);
					$('#previewForm')[0].submit();
				} else if (/^highlight-turtle/.test(hlType)) {
					var iframe = $(this).closest('.assignmentQuestion').find('iframe').first();
					var answerId = iframe.data('answerId');
					var location = iframe.attr('src');
					var newLocation = '';
					switch (hlType) {
						case 'highlight-turtle':
							newLocation = '/code-preview/turtle/' + answerId;
							break;
						case 'highlight-turtle-na':
							newLocation = '/code-preview/turtle/' + answerId + '?animated=0';
							break;
						default:
							newLocation = location;
					}

					PeerBlender.outdatedIframes.push({
						iframe: iframe,
						location: newLocation
					});

					var quickSaveButton = $('#quick-save-button');
					if (quickSaveButton.length) {
						setTimeout(function() {
							$('#quick-save-button').trigger('click');
						}, 1000);
					} else {
						PeerBlender.Highlighting.refreshIframes();
					}
				}

				e.preventDefault();
			});

			$('button.showPrefill').click(function(e) {
				var prefillViewer = $(this).closest('.assignmentQuestion').find('.prefill');
				prefillViewer.toggle('fast');
				if (!prefillViewer.hasClass('ready')) {
					PeerBlender.Highlighting.initCodeMirror(prefillViewer.find('textarea'));
					prefillViewer.addClass('ready');
				}

				e.preventDefault();
			});

			$('.assignmentQuestion textarea[class*="highlight-"]').each(function() {
				PeerBlender.Highlighting.initCodeMirror($(this));
			});

			$('#quick-save-button').click(function(e) {
				for (var i = 0; i < PeerBlender.Highlighting.editors.length; i++) {
					PeerBlender.Highlighting.editors[i].save();
				}
			});

			PeerBlender.Highlighting.initStickyIframes();
		},

		initCodeMirror: function(textarea) {
			var className = textarea.attr('class');
			if (!className) {
				return;
			}
			var mode = className.match(/highlight-([a-z]+)/)[1];
			var gutters = [];
			var lint = false;

			switch (mode) {
				case 'code':
				case 'markdown':
				case 'css':
				case 'sql':
				case 'xml':
					var highlightingMode = mode;
					break;
				case 'javascript':
					var highlightingMode = mode;
					lint = true;
					gutters = ["CodeMirror-lint-markers"];
					break;
				case 'html':
					var highlightingMode = 'htmlmixed';
					break;
				default:
					return;
			}

			var myCodeMirror = CodeMirror.fromTextArea(
				textarea[0], {
					lineNumbers: true,
					lineWrapping: true,
					mode: highlightingMode,
					lint: true,
					gutters: ["CodeMirror-lint-markers"],
					viewportMargin: Infinity,
					readOnly: textarea.hasClass('readonly') ? 'true' : false
				}
			);

			PeerBlender.Highlighting.editors.push(myCodeMirror);
		},

		initStickyIframes: function() {
			/*window.addEventListener('scroll', function() {
				var turtlePreviewHeight = 400;
				var previews = document.querySelectorAll('iframe.turtle-preview');

				for (var i = previews.length - 1; i >= 0; i--) {
					var iframe = previews[i];
					var codeColumn = document.querySelector('iframe.turtle-preview').parentNode.previousElementSibling.getBoundingClientRect();
					var height = codeColumn.height - 183;
					var top = codeColumn.top;
					if (codeColumn.height > turtlePreviewHeight + 100 && top < 0) {
						var translate = -top > turtlePreviewHeight ? turtlePreviewHeight : -top;
						iframe.style.transform = 'translate(0px, ' + (translate) + 'px)';
					} else {
						iframe.style.position = 'static';
						iframe.style.top = '';
						iframe.style.transform = '';
						iframe.style.width = '100%';
					}
				}
			});*/
		},

		refreshIframes: function() {
			for (var i = PeerBlender.outdatedIframes.length - 1; i >= 0; i--) {
				var item = PeerBlender.outdatedIframes[i];
				item.iframe.attr('src', item.location);

				PeerBlender.outdatedIframes.splice(i, 1);
			}
		}
	},

	Chat: {
		refresh: null,

		init: function() {
			if ($('#chat').length) {
				autosize($('#chat textarea'));
				$('#chat').show();

				$(document).on('click', '#chat .header', function() {
					if ($("#chat").height() > 400) {
						$("#chat .chatContent").hide();
						$("#chat").css({height: '30px', width: '100px'});
					} else {
						$("#chat .chatContent").show();
						$("#chat").css({height: '500px', width: '400px'});
					}

				});

				document.querySelector('#chat textarea').addEventListener('autosize:resized', function() {
					PeerBlender.Chat.resizeTextarea();
				});

				PeerBlender.Chat.refresh = setTimeout(function(){PeerBlender.Chat.refreshChat()}, 3*1000);
			}
		},

		resizeTextarea: function() {
			var messages = $('#chat .messages');
			messages.height(430 - $('#chat textarea').height());
			$('#chat .messages').scrollTop(document.querySelector('#chat .messages').scrollHeight);
		},

		refreshChat: function(courseId) {
			$.nette.ajax({
				url: '/generated/chat/' + 2 + '.html',
				complete: function (payload) {
					var messages = $('#chat .messages');
					messages.html(payload.responseText);
					PeerBlender.Chat.resizeTextarea();
					PeerBlender.Chat.refresh = setTimeout(function(courseId){PeerBlender.Chat.refreshChat(2)}, 3*1000);
				}
			});
		}
	}
}<|endoftext|>


<commit_before>//function storage_check(){
//    // IF RETURNING USER
//    if(localStorage.getItem('clock_s') !== null) {
//
//    } else if(localStorage.getItem('timerClock_s') !== null) {
//
//    } else if(localStorage.getItem('countDownClock_s') !== null) {
//
//    } else if(localStorage.getItem('stopWatchClock_s') !== null) {
//
//    } else if(localStorage.getItem('lapTimerClock_s') !== null) {
//
//    } else {
//
//        timerClock.render(130, 0, 'Demo Timer'); // timer presented if user came in first time and no global \ local storage.
//    }
//
//}

var storage = {
    local : {
        save : function() {
            localStorage.setItem($('#storage_key_save').val(), JSON.stringify(temporary_storage));
           // maybe store last value in session and load after page reload.
           // or need track somehow from which name of local \ global storage get timers after page reload.
           // sessionStorage.setItem('last_timer', JSON.stringify(temporary_storage));
        },
        load : function() {
            var result = JSON.parse(localStorage.getItem($('#storage_key_load').val()));

            for (var i in result) {
                if(result.hasOwnProperty(i) && !jQuery.isEmptyObject(result[i])) {
                    var value = result[i],
                        timer_type = result[i].type;

                    switch(timer_type) {
                        case '1':
                            clock.render(value);
                            break;
                        case '2':
                            timerClock.render(value);
                            break;
                        case '3':
                            countDownClock.render(value);
                            break;
                        case '4':
                            stopWatchClock.render(value);
                            break;
                        case '5':
                            lapTimerClock.render(value);
                            break;
                        default :
                            alert('error, unknown type');
                            break;
                    }
                }
            }
        }
    },
    global : {
        save : function() {
            $.ajax({
                type: "POST",
                url: "/storage/save",
                data: 'padID=' + $('#storage_key_save').val() + '&text=' + JSON.stringify(temporary_storage), // not working
                cache: false,
                success: function(msg) {
                    alert('saved!');
                }
            });
        },
        load : function() {
            $.ajax({
                type: "POST",
                url: "/storage/load",
                data: 'padID=' + $('#storage_key_load').val(),
                cache: false,
                success: function(msg) {
                    //alert(msg);
                    var result = JSON.parse(msg);

                    for (var i in result) {
                        if(result.hasOwnProperty(i) && !jQuery.isEmptyObject(result[i])) {
                            var value = result[i],
                                timer_type = result[i].type;

                            switch(timer_type) {
                                case '1':
                                    clock.render(value);
                                    break;
                                case '2':
                                    timerClock.render(value);
                                    break;
                                case '3':
                                    countDownClock.render(value);
                                    break;
                                case '4':
                                    stopWatchClock.render(value);
                                    break;
                                case '5':
                                    lapTimerClock.render(value);
                                    break;
                                default :
                                    alert('error, unknown type');
                                    break;
                            }
                        }
                    }
                }
            });
        }
    },
    user : { // TODO: after auth, login, etc...
        save : function() {
            alert('save to users account');
        },
        load : function() {
            alert('load from users account');
        }
    },
};<commit_msg>little code refactoring<commit_after>//function storage_check(){
//    // IF RETURNING USER
//    if(localStorage.getItem('clock_s') !== null) {
//
//    } else if(localStorage.getItem('timerClock_s') !== null) {
//
//    } else if(localStorage.getItem('countDownClock_s') !== null) {
//
//    } else if(localStorage.getItem('stopWatchClock_s') !== null) {
//
//    } else if(localStorage.getItem('lapTimerClock_s') !== null) {
//
//    } else {
//
//        timerClock.render(130, 0, 'Demo Timer'); // timer presented if user came in first time and no global \ local storage.
//    }
//
//}

var storage = {
    generate: function(result) {
        for (var i in result) {
            if(result.hasOwnProperty(i) && !jQuery.isEmptyObject(result[i])) {
                var value = result[i],
                    timer_type = result[i].type;

                switch(timer_type) {
                    case '1':
                        clock.render(value);
                        break;
                    case '2':
                        timerClock.render(value);
                        break;
                    case '3':
                        countDownClock.render(value);
                        break;
                    case '4':
                        stopWatchClock.render(value);
                        break;
                    case '5':
                        lapTimerClock.render(value);
                        break;
                    default :
                        alert('error, unknown type');
                        break;
                }
        }
    }
    },
    local : {
        save : function() {
            localStorage.setItem($('#storage_key_save').val(), JSON.stringify(temporary_storage));
           // maybe store last value in session and load after page reload.
           // or need track somehow from which name of local \ global storage get timers after page reload.
           // sessionStorage.setItem('last_timer', JSON.stringify(temporary_storage));
        },
        load : function() {
            var result = JSON.parse(localStorage.getItem($('#storage_key_load').val()));

            storage.generate(result);
        }
    },
    global : {
        save : function() {
            $.ajax({
                type: "POST",
                url: "/storage/save",
                data: 'padID=' + $('#storage_key_save').val() + '&text=' + JSON.stringify(temporary_storage), // not working
                cache: false,
                success: function(msg) {
                    alert('saved!');
                }
            });
        },
        load : function() {
            $.ajax({
                type: "POST",
                url: "/storage/load",
                data: 'padID=' + $('#storage_key_load').val(),
                cache: false,
                success: function(msg) {
                    //alert(msg);
                    var result = JSON.parse(msg);

                    storage.generate(result);
                }
            });
        }
    },
    user : { // TODO: after auth, login, etc...
        save : function() {
            alert('save to users account');
        },
        load : function() {
            alert('load from users account');
        }
    },
};<|endoftext|>


<commit_before>function initialize() {
  var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Update maps.js<commit_after>/*function initialize() {
  var mapProp = {
    center:new google.maps.LatLng(51.508742,-0.120850),
    zoom:5,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };
  var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
*/
<|endoftext|>


<commit_before>"use strict";

var supportsLocalStorage = typeof(Storage) !== "undefined";
var settings = {
    showRowRaceNone: true,
    showRowRaceProtoss: true,
    showRowRaceTerran: true,
    showRowRaceZerg: true,
    showRowOffline: false,
    showColRace: false,
    showColViewers: true,
    showColPeak: false,
    showColDuration: true,
    showColLastSeen: false,
    autoRefresh: true,
    useFullScreenLinks: false,

    keys: (function() {
        return Object.keys(this).filter(s => typeof(this[s]) == "boolean")
    }),

    visibilityKeys: (function() {
        return this.keys().filter(s => s.substring(0, 4) === "show");
    }),

    loadSettings: function() {
        //console.log("loadSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            if (supportsLocalStorage && localStorage.hasOwnProperty(setting)) {
                this[setting] = localStorage[setting] === "true";
            }
            var checkboxId = this.settingToCheckboxId(setting);
            var element = $("#" + checkboxId);
            //console.log(setting + ": " + localStorage[setting]);
            if (element.length && element.is(":checked") !== this[setting])
            {
                element.click();
                //console.log("Fired click event");
            }
        }
    },

    saveSettings: function() {
        if (!supportsLocalStorage) {
            //console.log("localStorage not supported");
            return;
        }
        //console.log("saveSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            localStorage[setting] = Boolean(this[setting]);
            //console.log(setting + ": " + localStorage[setting]);
        }
    },

    settingToCheckboxId: function(s) {
        return "checkbox-" + s.replace(/([A-Z])/g, function (x, y){return "-" + y.toLowerCase()}).replace(/^-/, "");
    },

    settingToClassName: function(s) {
        switch (s) {
            case "showRowRaceNone":
                return "race-none";
            case "showRowRaceProtoss":
                return "race-protoss";
            case "showRowRaceTerran":
                return "race-terran";
            case "showRowRaceZerg":
                return "race-zerg";
            case "showRowOffline":
                return "stream-row-offline";
            case "showColRace":
                return "stream-col-race";
            case "showColViewers":
                return "stream-col-viewers";
            case "showColPeak":
                return "stream-col-peak";
            case "showColDuration":
                return "stream-col-duration";
            case "showColLastSeen":
                return "stream-col-last-seen";
            default:
                throw "Unknown value in switch statement: " + setting;
        }
    },

    callback: function(setting) {
        if (setting === "autoRefresh") {
            timer.updateTimerStatus();
            return;
        }

        if (setting === "useFullScreenLinks") {
            $("a.stream-link").each(function() {
                var streamLink = $(this).attr("href");
                var streamId = streamLink.split("/")[3];
                var updatedStreamLink = getStreamUrl(streamId, settings["useFullScreenLinks"]);
                $(this).attr("href", updatedStreamLink);
            });
            return;
        }

        var className = this.settingToClassName(setting);
        if (this[setting]) {
            if (setting === "showRowOffline") {
                var showRaceSettings = this.keys().filter(s => s.substring(0, 11) === "showRowRace");
                for (var i = 0; i < showRaceSettings.length; i++) {
                    var showRateSetting = showRaceSettings[i];
                    if (this[showRateSetting]) {
                        var query = "." + className + "." + this.settingToClassName(showRateSetting);
                        $(query).show();
                    }
                }
            } else if (setting.substring(0, 11) === "showRowRace" && !this["showRowOffline"]) {
                $("." + className + ".stream-row-online").show();
            } else {
                $("." + className).show();
            }
        } else {
            $("." + className).hide();
        }
    }
};

function getStreamUrl(streamId, useFullScreenLink) {
    var url = "http://play.afreecatv.com/" + streamId;
    if (useFullScreenLink) {
        url += "/embed";
    }
    return url;
}

function getLastSeenStatus(isOnline, lastSeen) {
    if (isOnline) {
        return "online";
    } else if (lastSeen === null) {
        return "never seen";
    } else {
        return moment(lastSeen).fromNow();
    }
}

function replaceTable(streams, updateTime) {
    var idTableStreams = "streams";
    var newTbody = document.createElement("tbody");

    for (var key in streams) {
        if (key.substring(0, 8) != "afreeca_") {
            continue;
        }
        if (streams.hasOwnProperty(key)) {
            var stream = streams[key];
            var game = stream["game"];
            if (game != "brood war") {
                continue;
            }

            var nickname = stream["nickname"];
            var race = stream["game_info"]["race"];
            var raceText = race ? race : "";
            var viewers = stream["viewers"];
            var maxViewers = stream["max_viewers"];
            var isOnline = stream["online_since"] !== null;
            var durationText = "offline";
            var durationValue = 0;
            if (stream["online_since"] !== null) {
                var duration = moment.duration(moment(updateTime).diff(moment(stream["online_since"])));
                durationText = duration.humanize();
                durationValue = duration.asMinutes();
            }
            var lastSeenText = getLastSeenStatus(isOnline, stream["last_seen"]);
            var lastSeenValue = stream["last_seen"] || 0;
            var url = getStreamUrl(stream["id"], settings["useFullScreenLinks"]);
            var previewImage = stream["image"];

            var cells = [
                [nickname,     { "class": [ "stream-col-nickname" ] } ],
                [raceText,     { "class": [ "stream-col-race", "text-capitalize" ] } ],
                [viewers,      { "class": [ "stream-col-viewers", "text-center" ] } ],
                [maxViewers,   { "class": [ "stream-col-peak", "text-center" ] } ],
                [durationText, { "class": [ "stream-col-duration", "text-center" ], "data-value": durationValue } ],
                [lastSeenText, { "class": [ "stream-col-last-seen", "text-center" ], "data-value": lastSeenValue } ],
            ];

            var newRow = newTbody.insertRow(-1);
            newRow.classList.add(isOnline ? "stream-row-online" : "stream-row-offline");
            newRow.classList.add("race-" + (race || "none"));
            for (var i = 0; i < cells.length; i++) {
                var text = cells[i][0];
                var data = cells[i][1];
                var newCell = newRow.insertCell(-1);
                if (data !== null) {
                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            if (key === "class") {
                                for (var j = 0; j < data[key].length; j++) {
                                    newCell.classList.add(data[key][j]);
                                }
                            } else if (key.slice(0, 5) === "data-") {
                                newCell.setAttribute(key, data[key]);
                            }
                        }
                    }
                }
                if (i == 0) {
                    var span = document.createElement("span");
                    span.innerHTML = "● ";
                    newCell.appendChild(span);
                    var a = document.createElement("a");
                    a.href = url;
                    a.rel = "noreferrer";
                    a.classList.add("stream-link");
                    a.appendChild(document.createTextNode(text));
                    newCell.appendChild(a);
                    if (previewImage) {
                        var div = document.createElement('div');
                        var img = document.createElement('img');
                        img.src = previewImage.replace(/^\/\//, 'https://');
                        img.className = 'hide-image';
                        div.className = 'image-wrapper';
                        div.append(img);
                        newCell.appendChild(div);
                        newRow.classList.add("preview");
                    }
                } else {
                    newCell.appendChild(document.createTextNode(text));
                }
            }
        }
    }

    var table = document.getElementById(idTableStreams);
    var oldTbody = document.getElementById(idTableStreams).getElementsByTagName("tbody")[0];
    table.replaceChild(newTbody, oldTbody);
}

function setLastUpdate(timeStr) {
    $("#text-last-updated").text(moment(timeStr).format("lll"));
}

var updater = {
    json: null,

    refreshStreams: function() {
        this.refreshStarted();
        var promise = $.getJSON('/streams.json');
        promise.done((function(data) {
            this.json = data;
            this.refreshComplete();
        }).bind(this));
    },

    refreshStarted: function() {
        $("#icon-refresh").addClass("fa-spin");
        $("#icon-refresh").addClass("active");
        timer.resetTimer();
    },

    refreshComplete: function() {
        replaceTable(this.json["streams"], this.json["last_update"]);
        setLastUpdate(this.json["last_update"]);
        $.bootstrapSortable(true);
        var visibilitySettings = settings.visibilityKeys();
        for (var i = 0; i < visibilitySettings.length; i++) {
            settings.callback(visibilitySettings[i]);
        }
        $("#icon-refresh").removeClass("fa-spin");
        $("#icon-refresh").removeClass("active");
    }
}

var timer = {
    timerDuration: 60,
    timerElapsed: 0,
    timerId: null,

    updateTimerStatus: function() {
        if (settings.autoRefresh && this.timerId == null) {
            this.startTimer();
        }
    },

    resetTimer: function() {
        this.timerElapsed = 0;
    },

    stopTimer: function() {
        if (this.timerId != null) {
            clearInterval(this.timerId);
            this.timerId = null;
        }
    },

    startTimer: function() {
        this.timerId = setInterval((function() {
            ++this.timerElapsed;
            if (settings.autoRefresh && this.timerElapsed >= this.timerDuration) {
                updater.refreshStreams();
            }
        }).bind(this), 1000);
    }
}

jQuery(document).ready(function($) {
    $("#btn-refresh").click(function() {
        updater.refreshStreams();
    });

    var visibilitySettings = settings.visibilityKeys();
    for (var i = 0; i < visibilitySettings.length; i++) {
        (function() {
            var setting = visibilitySettings[i];
            var checkboxId = settings.settingToCheckboxId(setting);
            $("#" + checkboxId).click(function() {
                settings[setting] = $("#" + checkboxId).is(":checked");
                settings.callback(setting);
            });
        })();
    }

    $("#checkbox-auto-refresh").click(function() {
        settings["autoRefresh"] = $("#checkbox-auto-refresh").is(":checked");
        settings.callback("autoRefresh");
    });

    $("#checkbox-use-full-screen-links").click(function() {
        settings["useFullScreenLinks"] = $("#checkbox-use-full-screen-links").is(":checked");
        settings.callback("useFullScreenLinks");
    });

    settings.loadSettings();

    watch(settings, settings.keys(), function(){
        settings.saveSettings();
    });

    updater.refreshStreams();
});
<commit_msg>change preview and stream links to use the same protocol as the current page<commit_after>"use strict";

var supportsLocalStorage = typeof(Storage) !== "undefined";
var settings = {
    showRowRaceNone: true,
    showRowRaceProtoss: true,
    showRowRaceTerran: true,
    showRowRaceZerg: true,
    showRowOffline: false,
    showColRace: false,
    showColViewers: true,
    showColPeak: false,
    showColDuration: true,
    showColLastSeen: false,
    autoRefresh: true,
    useFullScreenLinks: false,

    keys: (function() {
        return Object.keys(this).filter(s => typeof(this[s]) == "boolean")
    }),

    visibilityKeys: (function() {
        return this.keys().filter(s => s.substring(0, 4) === "show");
    }),

    loadSettings: function() {
        //console.log("loadSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            if (supportsLocalStorage && localStorage.hasOwnProperty(setting)) {
                this[setting] = localStorage[setting] === "true";
            }
            var checkboxId = this.settingToCheckboxId(setting);
            var element = $("#" + checkboxId);
            //console.log(setting + ": " + localStorage[setting]);
            if (element.length && element.is(":checked") !== this[setting])
            {
                element.click();
                //console.log("Fired click event");
            }
        }
    },

    saveSettings: function() {
        if (!supportsLocalStorage) {
            //console.log("localStorage not supported");
            return;
        }
        //console.log("saveSettings");
        var settingKeys = this.keys();
        for (var i = 0; i < settingKeys.length; i++) {
            var setting = settingKeys[i];
            localStorage[setting] = Boolean(this[setting]);
            //console.log(setting + ": " + localStorage[setting]);
        }
    },

    settingToCheckboxId: function(s) {
        return "checkbox-" + s.replace(/([A-Z])/g, function (x, y){return "-" + y.toLowerCase()}).replace(/^-/, "");
    },

    settingToClassName: function(s) {
        switch (s) {
            case "showRowRaceNone":
                return "race-none";
            case "showRowRaceProtoss":
                return "race-protoss";
            case "showRowRaceTerran":
                return "race-terran";
            case "showRowRaceZerg":
                return "race-zerg";
            case "showRowOffline":
                return "stream-row-offline";
            case "showColRace":
                return "stream-col-race";
            case "showColViewers":
                return "stream-col-viewers";
            case "showColPeak":
                return "stream-col-peak";
            case "showColDuration":
                return "stream-col-duration";
            case "showColLastSeen":
                return "stream-col-last-seen";
            default:
                throw "Unknown value in switch statement: " + setting;
        }
    },

    callback: function(setting) {
        if (setting === "autoRefresh") {
            timer.updateTimerStatus();
            return;
        }

        if (setting === "useFullScreenLinks") {
            $("a.stream-link").each(function() {
                var streamLink = $(this).attr("href");
                var streamId = streamLink.split("/")[3];
                var updatedStreamLink = getStreamUrl(streamId, settings["useFullScreenLinks"]);
                $(this).attr("href", updatedStreamLink);
            });
            return;
        }

        var className = this.settingToClassName(setting);
        if (this[setting]) {
            if (setting === "showRowOffline") {
                var showRaceSettings = this.keys().filter(s => s.substring(0, 11) === "showRowRace");
                for (var i = 0; i < showRaceSettings.length; i++) {
                    var showRateSetting = showRaceSettings[i];
                    if (this[showRateSetting]) {
                        var query = "." + className + "." + this.settingToClassName(showRateSetting);
                        $(query).show();
                    }
                }
            } else if (setting.substring(0, 11) === "showRowRace" && !this["showRowOffline"]) {
                $("." + className + ".stream-row-online").show();
            } else {
                $("." + className).show();
            }
        } else {
            $("." + className).hide();
        }
    }
};

function getStreamUrl(streamId, useFullScreenLink) {
    var url = "//play.afreecatv.com/" + streamId;
    if (useFullScreenLink) {
        url += "/embed";
    }
    return url;
}

function getLastSeenStatus(isOnline, lastSeen) {
    if (isOnline) {
        return "online";
    } else if (lastSeen === null) {
        return "never seen";
    } else {
        return moment(lastSeen).fromNow();
    }
}

function replaceTable(streams, updateTime) {
    var idTableStreams = "streams";
    var newTbody = document.createElement("tbody");

    for (var key in streams) {
        if (key.substring(0, 8) != "afreeca_") {
            continue;
        }
        if (streams.hasOwnProperty(key)) {
            var stream = streams[key];
            var game = stream["game"];
            if (game != "brood war") {
                continue;
            }

            var nickname = stream["nickname"];
            var race = stream["game_info"]["race"];
            var raceText = race ? race : "";
            var viewers = stream["viewers"];
            var maxViewers = stream["max_viewers"];
            var isOnline = stream["online_since"] !== null;
            var durationText = "offline";
            var durationValue = 0;
            if (stream["online_since"] !== null) {
                var duration = moment.duration(moment(updateTime).diff(moment(stream["online_since"])));
                durationText = duration.humanize();
                durationValue = duration.asMinutes();
            }
            var lastSeenText = getLastSeenStatus(isOnline, stream["last_seen"]);
            var lastSeenValue = stream["last_seen"] || 0;
            var url = getStreamUrl(stream["id"], settings["useFullScreenLinks"]);
            var previewImage = stream["image"];

            var cells = [
                [nickname,     { "class": [ "stream-col-nickname" ] } ],
                [raceText,     { "class": [ "stream-col-race", "text-capitalize" ] } ],
                [viewers,      { "class": [ "stream-col-viewers", "text-center" ] } ],
                [maxViewers,   { "class": [ "stream-col-peak", "text-center" ] } ],
                [durationText, { "class": [ "stream-col-duration", "text-center" ], "data-value": durationValue } ],
                [lastSeenText, { "class": [ "stream-col-last-seen", "text-center" ], "data-value": lastSeenValue } ],
            ];

            var newRow = newTbody.insertRow(-1);
            newRow.classList.add(isOnline ? "stream-row-online" : "stream-row-offline");
            newRow.classList.add("race-" + (race || "none"));
            for (var i = 0; i < cells.length; i++) {
                var text = cells[i][0];
                var data = cells[i][1];
                var newCell = newRow.insertCell(-1);
                if (data !== null) {
                    for (var key in data) {
                        if (data.hasOwnProperty(key)) {
                            if (key === "class") {
                                for (var j = 0; j < data[key].length; j++) {
                                    newCell.classList.add(data[key][j]);
                                }
                            } else if (key.slice(0, 5) === "data-") {
                                newCell.setAttribute(key, data[key]);
                            }
                        }
                    }
                }
                if (i == 0) {
                    var span = document.createElement("span");
                    span.innerHTML = "● ";
                    newCell.appendChild(span);
                    var a = document.createElement("a");
                    a.href = url;
                    a.rel = "noreferrer";
                    a.classList.add("stream-link");
                    a.appendChild(document.createTextNode(text));
                    newCell.appendChild(a);
                    if (previewImage) {
                        var div = document.createElement('div');
                        var img = document.createElement('img');
                        img.src = previewImage;
                        img.className = 'hide-image';
                        div.className = 'image-wrapper';
                        div.append(img);
                        newCell.appendChild(div);
                        newRow.classList.add("preview");
                    }
                } else {
                    newCell.appendChild(document.createTextNode(text));
                }
            }
        }
    }

    var table = document.getElementById(idTableStreams);
    var oldTbody = document.getElementById(idTableStreams).getElementsByTagName("tbody")[0];
    table.replaceChild(newTbody, oldTbody);
}

function setLastUpdate(timeStr) {
    $("#text-last-updated").text(moment(timeStr).format("lll"));
}

var updater = {
    json: null,

    refreshStreams: function() {
        this.refreshStarted();
        var promise = $.getJSON('/streams.json');
        promise.done((function(data) {
            this.json = data;
            this.refreshComplete();
        }).bind(this));
    },

    refreshStarted: function() {
        $("#icon-refresh").addClass("fa-spin");
        $("#icon-refresh").addClass("active");
        timer.resetTimer();
    },

    refreshComplete: function() {
        replaceTable(this.json["streams"], this.json["last_update"]);
        setLastUpdate(this.json["last_update"]);
        $.bootstrapSortable(true);
        var visibilitySettings = settings.visibilityKeys();
        for (var i = 0; i < visibilitySettings.length; i++) {
            settings.callback(visibilitySettings[i]);
        }
        $("#icon-refresh").removeClass("fa-spin");
        $("#icon-refresh").removeClass("active");
    }
}

var timer = {
    timerDuration: 60,
    timerElapsed: 0,
    timerId: null,

    updateTimerStatus: function() {
        if (settings.autoRefresh && this.timerId == null) {
            this.startTimer();
        }
    },

    resetTimer: function() {
        this.timerElapsed = 0;
    },

    stopTimer: function() {
        if (this.timerId != null) {
            clearInterval(this.timerId);
            this.timerId = null;
        }
    },

    startTimer: function() {
        this.timerId = setInterval((function() {
            ++this.timerElapsed;
            if (settings.autoRefresh && this.timerElapsed >= this.timerDuration) {
                updater.refreshStreams();
            }
        }).bind(this), 1000);
    }
}

jQuery(document).ready(function($) {
    $("#btn-refresh").click(function() {
        updater.refreshStreams();
    });

    var visibilitySettings = settings.visibilityKeys();
    for (var i = 0; i < visibilitySettings.length; i++) {
        (function() {
            var setting = visibilitySettings[i];
            var checkboxId = settings.settingToCheckboxId(setting);
            $("#" + checkboxId).click(function() {
                settings[setting] = $("#" + checkboxId).is(":checked");
                settings.callback(setting);
            });
        })();
    }

    $("#checkbox-auto-refresh").click(function() {
        settings["autoRefresh"] = $("#checkbox-auto-refresh").is(":checked");
        settings.callback("autoRefresh");
    });

    $("#checkbox-use-full-screen-links").click(function() {
        settings["useFullScreenLinks"] = $("#checkbox-use-full-screen-links").is(":checked");
        settings.callback("useFullScreenLinks");
    });

    settings.loadSettings();

    watch(settings, settings.keys(), function(){
        settings.saveSettings();
    });

    updater.refreshStreams();
});
<|endoftext|>