<commit_before>$(document).ready(function () {

	//variables declaration
	var tableData=[], tableDataReverse=[];
	var pressure=[], pressurerev=[];

	$("#chart").shieldChart({
                theme: "light",
                exportOptions: {
                    image: false,
                    print: false
                },
                primaryHeader: {
                    text: "Pressure, termperature and vibration statistics over six interval"
                },
                zoomMode: "xy",
                seriesSettings: {
                    bar: {
                        barOffset: 0
                    }
                },
                axisX: {
                    categoricalValues: ["1st", "2nd", "3rd", "4th", "5th", "6th"]
                },
                axisY: {
                    title: {
                        text: "Value statistics"
                    }
                },
                dataSeries: [{
                    seriesType: "bar",
                    collectionAlias: "Pressure",
                    data: pressurerev
                }, {
                    seriesType: "bar",
                    collectionAlias: "Temperature",
                    data: [72, 90, 84, 78, 67, 83]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Vibration",
                    data: [152, 234, 123, 348]
                }]
            });

	$("#grid").shieldGrid({
            dataSource: {
				data: tableDataReverse
			},
			rowHover: false,
            scrolling: {
                virtual: true
            },
            sorting: true,
            columnReorder: true,
            columns: [
                { field: "key", title: "Key" },
                { field: "value", title: "Value" }
            ]
        });

	//updating table (live)
    function refreshGird() {
        var grid = $("#grid").swidget(),
            initialOptions = grid.initialOptions;
        initialOptions.dataSource = {
            data: tableDataReverse
        };
        grid.refresh(initialOptions);
    }

	//styling table (assigning red/green colour)
	function gridDataBound(e) {
		var data = e.target.dataSource.view;
		var rows = e.target.contentTable.find(">tbody>tr");
		for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.message == thresholdMsg) {
                $(rows[i].cells[3]).addClass("red");
            }
            if (item.message == msg) {
                $(rows[i].cells[3]).addClass("green");
            }
        }
    }

	if(tableData.length == 5){
						for(var i=0; i<(tableData.length)-1; i++){
							tableData[i]= tableData[i+1];
						}
						tableData[4]={
							key: "internalTemperature",
							value: "128"
						};
					}
					else{
						tableData.push({
							key: "internalTemperature",
							value: "128"
						});
					}

		tableDataReverse = tableData.slice(0);
		tableDataReverse.reverse();

	//websocket connection
	var ws = new WebSocket('wss://' + location.host);

	ws.onopen = function () {
		console.log('Successfully connect WebSocket');
	}

	//websocket receiving messages
	ws.onmessage = function (message) {
		console.log('Receive message via websocket in client side: ' + message.data);
		try {
			var obj = JSON.parse(message.data);

						tableData.push({
							key: "Time of reading",
							value: obj.timeOfReading
						});
						tableData.push({
							key: "Internal temperature",
							value: obj.internalTemperature
						});
						tableData.push({
							key: "Daily flow",
							value: obj.dailyFlow
						});
						tableData.push({
							key: "Daily reverse flow",
							value: obj.dailyReverseFlow
						});
						tableData.push({
							key: "Peak flow rate",
							value: obj.peakFlowRate
						});
						tableData.push({
							key: "Peak flow rate time",
							value: obj.peakFlowRateTime
						});
						tableData.push({
							key: "Event time",
							value: obj.eventTime
						});

						pressure.push({
							parseInt("453")
						});
						pressure.push({
							parseInt("452")
						});
						pressure.push({
							parseInt("451")
						});
						pressure.push({
							parseInt("450")
						});
						pressure.push({
							parseInt("449")
						});
						pressure.push({
							parseInt("448")
						});

			pressurerev = pressure.slice(0)	;
			pressurerev.reverse;
			tableDataReverse = tableData.slice(0);
			tableDataReverse.reverse();

			refreshGird();
			}
		catch (err) {
		  console.error(err);
		}
	}
});<commit_msg>trying grid code10<commit_after>$(document).ready(function () {

	//variables declaration
	var tableData=[], tableDataReverse=[];
	var pressure=[], pressurerev=[];

	$("#grid").shieldGrid({
            dataSource: {
				data: tableDataReverse
			},
			rowHover: false,
            scrolling: {
                virtual: true
            },
            sorting: true,
            columnReorder: true,
            columns: [
                { field: "key", title: "Key" },
                { field: "value", title: "Value" }
            ]
        });

	//updating table (live)
    function refreshGird() {
        var grid = $("#grid").swidget(),
            initialOptions = grid.initialOptions;
        initialOptions.dataSource = {
            data: tableDataReverse
        };
        grid.refresh(initialOptions);
    }

	//styling table (assigning red/green colour)
	function gridDataBound(e) {
		var data = e.target.dataSource.view;
		var rows = e.target.contentTable.find(">tbody>tr");
		for (var i = 0; i < data.length; i++) {
            var item = data[i];
            if (item.message == thresholdMsg) {
                $(rows[i].cells[3]).addClass("red");
            }
            if (item.message == msg) {
                $(rows[i].cells[3]).addClass("green");
            }
        }
    }

	//websocket connection
	var ws = new WebSocket('wss://' + location.host);

	ws.onopen = function () {
		console.log('Successfully connect WebSocket');
	}

	//websocket receiving messages
	ws.onmessage = function (message) {
		console.log('Receive message via websocket in client side: ' + message.data);
		try {
			var obj = JSON.parse(message.data);

						tableData.push({
							key: "Time of reading",
							value: obj.timeOfReading
						});
						tableData.push({
							key: "Internal temperature",
							value: obj.internalTemperature
						});
						tableData.push({
							key: "Daily flow",
							value: obj.dailyFlow
						});
						tableData.push({
							key: "Daily reverse flow",
							value: obj.dailyReverseFlow
						});
						tableData.push({
							key: "Peak flow rate",
							value: obj.peakFlowRate
						});
						tableData.push({
							key: "Peak flow rate time",
							value: obj.peakFlowRateTime
						});
						tableData.push({
							key: "Event time",
							value: obj.eventTime
						});

						pressure.push({
							parseInt("453")
						});
						pressure.push({
							parseInt("452")
						});
						pressure.push({
							parseInt("451")
						});
						pressure.push({
							parseInt("450")
						});
						pressure.push({
							parseInt("449")
						});
						pressure.push({
							parseInt("448")
						});

			pressurerev = pressure.slice(0)	;
			pressurerev.reverse;
			tableDataReverse = tableData.slice(0);
			tableDataReverse.reverse();

			refreshGird();
			}
		catch (err) {
		  console.error(err);
		}
	}

	$("#chart").shieldChart({
                theme: "light",
                exportOptions: {
                    image: false,
                    print: false
                },
                primaryHeader: {
                    text: "Pressure, termperature and vibration statistics over six interval"
                },
                zoomMode: "xy",
                seriesSettings: {
                    bar: {
                        barOffset: 0
                    }
                },
                axisX: {
                    categoricalValues: ["1st", "2nd", "3rd", "4th", "5th", "6th"]
                },
                axisY: {
                    title: {
                        text: "Value statistics"
                    }
                },
                dataSeries: [{
                    seriesType: "bar",
                    collectionAlias: "Pressure",
                    data: pressurerev
                }, {
                    seriesType: "bar",
                    collectionAlias: "Temperature",
                    data: [72, 90, 84, 78, 67, 83]
                }, {
                    seriesType: "bar",
                    collectionAlias: "Vibration",
                    data: [152, 234, 123, 348]
                }]
            });
});<|endoftext|>


<commit_before>function modalEvents(button, modal, page ) {
    switch (button.data('action')) {
        case "new_user":
            modal.find('.modal-title').text('Registrar usuario');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/new', { user_id: button.data('user_id')  }, function(){

            });
            break;
        case "user_profile":
            modal.find('.modal-title').text('Editar información del usuario');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/profile', { user_id: button.data('user_id')  }, function(){
                $('#form_updateprofile').submit(function(event){
                    $.post('/user/update', $(this).serialize()).done(function (data) {
                        alert(data.message);
                        if (data.status=='Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "change_password":
            modal.find('.modal-title').text('Cambiar contraseña');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/change-password', { user_id: button.data('user_id')  }, function(){
                $('#form_updatepassword').submit(function (event) {
                    $.post('/user/update-password', $(this).serialize()).done(function (data) {
                        alert(data.message);
                        if(data.status=='Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "new_item":
            modal.find('.modal-title').text('Registrar artículo');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/item/new', {}, function(){
                $('#itemForm').submit(function(event) {
                    var n_articles = $('input[id=nArts]').val();
                    if (confirm("¿Está seguro que quiere registrar " + n_articles + " artículos?")){
                            $.post('/item/register', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if (data.status == 'Ok') {
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                }
                })
            });
            break;
        case "edit_item":
            modal.find('.modal-title').text('Editar artículos');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/item/list/',{ page: page }, function(){
                $(this).find('.list-group-item').click(function(){
                    // alert("Funciona, item: "+ $(this).data('item_id'));
                    $("#modal_content").load('/item/edit-item/',{ id: $(this).data('item_id') }, function () {
                        $('#itemForm').submit(function (event) {
                            $.post('/item/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });
                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
        // Editar articulos
        case "edit_user":
            modal.find('.modal-title').text('Editar usuario');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/list/',{ page: page }, function(){
                $(this).find('.list-group-item').click(function(){
                    // alert("Funciona, item: "+ $(this).data('item_id'));
                    $("#modal_content").load('/user/edit-user/',{ id: $(this).data('user_id') }, function () {
                        $('#updateUser').submit(function (event) {
                            $.post('/user/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });
                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
        //stores
        case "new_store":
            modal.find('.modal-title').text('Registrar sucursal');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/store/new', { /* post body data */ }, function(){
                $('#storeForm').submit(function(event){
                    $.post('/store/register', $(this).serialize()).done(function (data){
                        alert(data.message);
                        if(data.status == 'Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "edit_store":
            modal.find('.modal-title').text('Editar sucursal');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/store/list/',{ page: page }, function(){
                $(this).find('.list-group-item').click(function(){
                    $("#modal_content").load('/store/edit-store/', {id: $(this).data('store_id')}, function () {
                        $('#storeForm').submit(function (event) {
                            $.post('/store/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });
                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
        case "new_sale":
            modal.find('.modal-title').text('Registrar venta');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/item/list/sale',{ page: page},function(){
                var select = $('select[id=vselect]').val();
                alert(select);
                //alert("Usuario: "+ select.options[select.selectedIndex].value);
                $(this).find('.list-group-item').click(function(){
                    if (confirm("¿Está seguro que quiere vender el artículo: " +  $(this).data('item_id'))){
                        $.post('/carrito/new', {item_id:$(this).data('item_id'), user_id:select}).done(function (data) {
                            alert(data.message);
                            if(data.status=='Ok'){
                                modal.modal('hide');
                            }
                        });
                        event.preventDefault();
                    }
                });
            });
            break;
        case "new_supplier":
            modal.find('.modal-title').text('Registrar proveedor');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/supplier/new', { /* post body data */ }, function(){
                $('#supplierForm').submit(function(event){
                    $.post('/supplier/register', $(this).serialize()).done(function (data){
                        alert(data.message);
                        if(data.status == 'Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "edit_supplier":
            modal.find('.modal-title').text('Editar proveedor');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/supplier/list/', { page : page } , function(){
                $(this).find('.list-group-item').click(function(){
                    $("#modal_content").load("/supplier/edit-supplier/", {id: $(this).data('supplier_id')}, function(){
                        $('#supplierForm').submit(function (event) {
                            $.post('/supplier/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });

                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
    }
}

$('#genericModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    var page = 0;
    modalEvents(button, modal, page);
});

<commit_msg>alert<commit_after>function modalEvents(button, modal, page ) {
    switch (button.data('action')) {
        case "new_user":
            modal.find('.modal-title').text('Registrar usuario');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/new', { user_id: button.data('user_id')  }, function(){

            });
            break;
        case "user_profile":
            modal.find('.modal-title').text('Editar información del usuario');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/profile', { user_id: button.data('user_id')  }, function(){
                $('#form_updateprofile').submit(function(event){
                    $.post('/user/update', $(this).serialize()).done(function (data) {
                        alert(data.message);
                        if (data.status=='Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "change_password":
            modal.find('.modal-title').text('Cambiar contraseña');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/change-password', { user_id: button.data('user_id')  }, function(){
                $('#form_updatepassword').submit(function (event) {
                    $.post('/user/update-password', $(this).serialize()).done(function (data) {
                        alert(data.message);
                        if(data.status=='Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "new_item":
            modal.find('.modal-title').text('Registrar artículo');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/item/new', {}, function(){
                $('#itemForm').submit(function(event) {
                    var n_articles = $('input[id=nArts]').val();
                    if (confirm("¿Está seguro que quiere registrar " + n_articles + " artículos?")){
                            $.post('/item/register', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if (data.status == 'Ok') {
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                }
                })
            });
            break;
        case "edit_item":
            modal.find('.modal-title').text('Editar artículos');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/item/list/',{ page: page }, function(){
                $(this).find('.list-group-item').click(function(){
                    // alert("Funciona, item: "+ $(this).data('item_id'));
                    $("#modal_content").load('/item/edit-item/',{ id: $(this).data('item_id') }, function () {
                        $('#itemForm').submit(function (event) {
                            $.post('/item/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });
                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
        // Editar articulos
        case "edit_user":
            modal.find('.modal-title').text('Editar usuario');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/user/list/',{ page: page }, function(){
                $(this).find('.list-group-item').click(function(){
                    // alert("Funciona, item: "+ $(this).data('item_id'));
                    $("#modal_content").load('/user/edit-user/',{ id: $(this).data('user_id') }, function () {
                        $('#updateUser').submit(function (event) {
                            $.post('/user/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });
                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
        //stores
        case "new_store":
            modal.find('.modal-title').text('Registrar sucursal');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/store/new', { /* post body data */ }, function(){
                $('#storeForm').submit(function(event){
                    $.post('/store/register', $(this).serialize()).done(function (data){
                        alert(data.message);
                        if(data.status == 'Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "edit_store":
            modal.find('.modal-title').text('Editar sucursal');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/store/list/',{ page: page }, function(){
                $(this).find('.list-group-item').click(function(){
                    $("#modal_content").load('/store/edit-store/', {id: $(this).data('store_id')}, function () {
                        $('#storeForm').submit(function (event) {
                            $.post('/store/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });
                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
        case "new_sale":
            modal.find('.modal-title').text('Registrar venta');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/item/list/sale',{ page: page},function(){
                var select = $('select[id=vselect]').val();
                //alert("Usuario: "+ select.options[select.selectedIndex].value);
                $(this).find('.list-group-item').click(function(){
                    if (confirm("¿Está seguro que quiere vender el artículo: " +  $(this).data('item_id'))){
                        $.post('/carrito/new', {item_id:$(this).data('item_id'), user_id:select}).done(function (data) {
                            alert(data.message);
                            if(data.status=='Ok'){
                                modal.modal('hide');
                            }
                        });
                        event.preventDefault();
                    }
                });
            });
            break;
        case "new_supplier":
            modal.find('.modal-title').text('Registrar proveedor');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/supplier/new', { /* post body data */ }, function(){
                $('#supplierForm').submit(function(event){
                    $.post('/supplier/register', $(this).serialize()).done(function (data){
                        alert(data.message);
                        if(data.status == 'Ok'){
                            modal.modal('hide');
                        }
                    });
                    event.preventDefault();
                });
            });
            break;
        case "edit_supplier":
            modal.find('.modal-title').text('Editar proveedor');
            modal.find('#modal_content').html("");
            modal.find('#modal_content').load('/supplier/list/', { page : page } , function(){
                $(this).find('.list-group-item').click(function(){
                    $("#modal_content").load("/supplier/edit-supplier/", {id: $(this).data('supplier_id')}, function(){
                        $('#supplierForm').submit(function (event) {
                            $.post('/supplier/update', $(this).serialize()).done(function (data) {
                                alert(data.message);
                                if(data.status=='Ok'){
                                    modal.modal('hide');
                                }
                            });
                            event.preventDefault();
                        });
                    });
                });

                $('.pagination').find('li').click(function () {
                    modalEvents(button, modal, $(this).data('pagenumber'));
                });
            });
            break;
    }
}

$('#genericModal').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var modal = $(this);
    var page = 0;
    modalEvents(button, modal, page);
});

<|endoftext|>


<commit_before>var parse   = require('url').parse,
    querystring = require('querystring').parse,
    processors = require('../processors'),
    sessions = {},
    sessionsFromUser = {},
    pending = {};

var metrics = require('../metrics'),
    open = 0;

setInterval(function () {
  pending = {};
}, 15 * 60 * 1000);

function removeConnection(id, res) {
  if (sessions[id]) {
    var responses = sessions[id].res,
        index = responses.indexOf(res);

    if (index !== -1) {
      responses.splice(index, 1);
      open -= 1;
      if (open < 0) open = 0;
      metrics.gauge('spike.open', open);

      // Remove the object if we're not using it.
      if (!responses.length) {
        delete sessions[id];
      }
    }
  }
}

function keyForBin(bin) {
  return bin.url + '/' + bin.revision;
}

function sessionForBin(bin, create) {
  var key = keyForBin(bin),
      session = sessions[key];

  if (!session && create === true) {
    session = sessions[key] = { res: [], log: [] };
  }

  return session || null;
}

/**
 * Process a spike data object with the relevant preprocessor. Takes an object
 * and a bin's settings object.
 *
 * Returns an object with the same keys but with processed data.
 */
var process = function(data, settings) {
  data = data || {};
  settings = settings || {};
  // Grab the processor settings
  var processorSettings = settings.processors;
  if (!processorSettings) return data;
  // Get the name of the currently used processor
  var processorName = processorSettings[data.panelId];
  if (!processorName) return data;
  // Find this processor in the list of processors
  if (!processors[processorName]) return data;
  // And process!
  data.content = processors[processorName](data.content);
  return data;
};

module.exports = {
  getLog: function (req, res) {
    // TODO: Work out what the hell to do with this.
    var session = sessionForBin(req.bin), log;
    res.writeHead(200, {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'});
    log = session ? session.log.join('\n
') : 'No session';
    res.end('<!DOCTYPE html><title>\n' + req.bin.url + '</title>

' + log);
  },

  postLog: function (req, res, next) {
    var session = sessionForBin(req.bin, true);

    // passed over to Server Sent Events on jsconsole.com
    if (session) {
      session.log.push('message: ' + req.body.data);
      res.send(200);
    } else {
      next();
    }
  },

  // listening stream
  getStream: function (req, res, next) {

    // Check request's accepts header for supported content types. If event
    // stream has precedence then return it otherwise pass on to next handler.
    if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') !== -1) {
      var session = sessionForBin(req.bin, true),
          keepalive = null,
          close, closeTimer;

      // Store the connection
      open += 1;
      metrics.gauge('spike.open', open);

      console.log('STREAM ACCEPTED', req.headers['user-agent']);
      res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
      res.write('id: 0\n\n');

      session.res.push(res);

      if (req.keepLatest) {
        if (!sessionsFromUser[req.user.name]) {
          sessionsFromUser[req.user.name] = [];
        }
        sessionsFromUser[req.user.name].push({ key: keyForBin(req.bin), res: res });
      }

      keepalive = setInterval(function () {
        res.write('id: 0\n\n');
      }, 15 * 1000);

      // FIXME this will break when using /rem/last/ as req.bin won't be the same bin anymore.
      close = function () {
        clearInterval(keepalive);
        clearTimeout(closeTimer);
        removeConnection(keyForBin(req.bin), res);
      };

      // every 5 minutes, let's let them reconnect
      closeTimer = setTimeout(function () {
        res.end();
        req.emit('close');
      }, 15 * 60 * 1000);

      res.socket.on('close', close);
      req.on('close', close);
      res.req = req;
    } else {
      next();
    }
  },

  reload: function (bin) {
    var session = sessionForBin(bin);

    if (session) {
      session.res.forEach(function (res) {
        res.write('event: reload\ndata: 0\n\n');

        if (res.ajax) {
          res.end(); // lets older browsers finish their xhr request
          res.req.emit('close');
        }
      });
    }
  },

  updateUserSpikes: function (user, bin) {
    var key = keyForBin(bin);
    if (sessionsFromUser[user]) {
      sessionsFromUser[user].forEach(function (oldbin) {
        var oldbinKey = oldbin.key,
            session;

        if (oldbinKey !== key) {
          oldbin.res.req.bin = bin; // this allows the clean up function to remove the *right* bin
          // change the session link
          removeConnection(oldbinKey, oldbin.res);

          session = sessionForBin(bin, true);
          session.res.push(oldbin.res);
          oldbin.key = key;
        }
      });
    }
  },

  ping: function (bin, data) {
    var id = bin.id,
        delayTrigger = 500;

    if (!pending[id]) {
      pending[id] = {};
    }

    pending[id].bin = bin;
    pending[id][data.panelId] = process(data, bin.settings);

    clearTimeout(pending[id].timer);

    // NOTE: this will only fire once per jsbin session -
    // not for every panel sent - because we clear the timer
    pending[id].timer = setTimeout(function () {
      var session = sessionForBin(bin),
          data = null;

      if (session) {
        // were we try to get clever.
        if (pending[id].javascript) {
          // this will cause a reload on the client
          data = pending[id].javascript;
        } else if (pending[id].html) {
          // this will cause a reload on the client (but in future will be conditional)
          data = pending[id].html;

          // so at some point, we'll also want to send the CSS as a second message
        } else if (pending[id].css) {
          // this will cause a CSS reload only
          data = pending[id].css;
        }

        if (data) {
          session.res.forEach(function (res) {
            res.write('data:' + data.content.split('\n').join('\ndata:') + '\nevent:' + data.panelId + '\n\n');
            res.write('event: stats\ndata: ' + JSON.stringify({ connections: session.res.length }) + '\n\n');
            if (res.ajax) {
              res.end(); // lets older browsers finish their xhr request
              res.req.emit('close');
            }
          });
        }
      }

      delete pending[id];
    }, delayTrigger);
  },
  appendScripts: function (scripts) {
    // TODO this should really detect that there's an active session going
    // on and the user is saving, and therefore include the spike intelligently
    scripts.push('js/vendor/eventsource.js');
    scripts.push('js/spike.js');
  }
};
<commit_msg>Don't modify in place.<commit_after>var parse   = require('url').parse,
    querystring = require('querystring').parse,
    processors = require('../processors'),
    _ = require('underscore'),
    sessions = {},
    sessionsFromUser = {},
    pending = {};

var metrics = require('../metrics'),
    open = 0;

setInterval(function () {
  pending = {};
}, 15 * 60 * 1000);

function removeConnection(id, res) {
  if (sessions[id]) {
    var responses = sessions[id].res,
        index = responses.indexOf(res);

    if (index !== -1) {
      responses.splice(index, 1);
      open -= 1;
      if (open < 0) open = 0;
      metrics.gauge('spike.open', open);

      // Remove the object if we're not using it.
      if (!responses.length) {
        delete sessions[id];
      }
    }
  }
}

function keyForBin(bin) {
  return bin.url + '/' + bin.revision;
}

function sessionForBin(bin, create) {
  var key = keyForBin(bin),
      session = sessions[key];

  if (!session && create === true) {
    session = sessions[key] = { res: [], log: [] };
  }

  return session || null;
}

/**
 * Process a spike data object with the relevant preprocessor. Takes an object
 * and a bin's settings object.
 *
 * Returns an object with the same keys but with processed data.
 */
var process = function(data, settings) {
  data = data || {};
  settings = settings || {};
  // Grab the processor settings
  var processorSettings = settings.processors;
  if (!processorSettings) return data;
  // Get the name of the currently used processor
  var processorName = processorSettings[data.panelId];
  if (!processorName) return data;
  // Find this processor in the list of processors
  if (!processors[processorName]) return newData;
  // And process!
  var newData = _.clone(data);
  newData.content = processors[processorName](data.content);
  return newData;
};

module.exports = {
  getLog: function (req, res) {
    // TODO: Work out what the hell to do with this.
    var session = sessionForBin(req.bin), log;
    res.writeHead(200, {'Content-Type': 'text/html', 'Cache-Control': 'no-cache'});
    log = session ? session.log.join('\n
') : 'No session';
    res.end('<!DOCTYPE html><title>\n' + req.bin.url + '</title>

' + log);
  },

  postLog: function (req, res, next) {
    var session = sessionForBin(req.bin, true);

    // passed over to Server Sent Events on jsconsole.com
    if (session) {
      session.log.push('message: ' + req.body.data);
      res.send(200);
    } else {
      next();
    }
  },

  // listening stream
  getStream: function (req, res, next) {

    // Check request's accepts header for supported content types. If event
    // stream has precedence then return it otherwise pass on to next handler.
    if (req.headers.accept && req.headers.accept.indexOf('text/event-stream') !== -1) {
      var session = sessionForBin(req.bin, true),
          keepalive = null,
          close, closeTimer;

      // Store the connection
      open += 1;
      metrics.gauge('spike.open', open);

      console.log('STREAM ACCEPTED', req.headers['user-agent']);
      res.writeHead(200, {'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache'});
      res.write('id: 0\n\n');

      session.res.push(res);

      if (req.keepLatest) {
        if (!sessionsFromUser[req.user.name]) {
          sessionsFromUser[req.user.name] = [];
        }
        sessionsFromUser[req.user.name].push({ key: keyForBin(req.bin), res: res });
      }

      keepalive = setInterval(function () {
        res.write('id: 0\n\n');
      }, 15 * 1000);

      // FIXME this will break when using /rem/last/ as req.bin won't be the same bin anymore.
      close = function () {
        clearInterval(keepalive);
        clearTimeout(closeTimer);
        removeConnection(keyForBin(req.bin), res);
      };

      // every 5 minutes, let's let them reconnect
      closeTimer = setTimeout(function () {
        res.end();
        req.emit('close');
      }, 15 * 60 * 1000);

      res.socket.on('close', close);
      req.on('close', close);
      res.req = req;
    } else {
      next();
    }
  },

  reload: function (bin) {
    var session = sessionForBin(bin);

    if (session) {
      session.res.forEach(function (res) {
        res.write('event: reload\ndata: 0\n\n');

        if (res.ajax) {
          res.end(); // lets older browsers finish their xhr request
          res.req.emit('close');
        }
      });
    }
  },

  updateUserSpikes: function (user, bin) {
    var key = keyForBin(bin);
    if (sessionsFromUser[user]) {
      sessionsFromUser[user].forEach(function (oldbin) {
        var oldbinKey = oldbin.key,
            session;

        if (oldbinKey !== key) {
          oldbin.res.req.bin = bin; // this allows the clean up function to remove the *right* bin
          // change the session link
          removeConnection(oldbinKey, oldbin.res);

          session = sessionForBin(bin, true);
          session.res.push(oldbin.res);
          oldbin.key = key;
        }
      });
    }
  },

  ping: function (bin, data) {
    var id = bin.id,
        delayTrigger = 500;

    if (!pending[id]) {
      pending[id] = {};
    }

    pending[id].bin = bin;
    pending[id][data.panelId] = process(data, bin.settings);

    clearTimeout(pending[id].timer);

    // NOTE: this will only fire once per jsbin session -
    // not for every panel sent - because we clear the timer
    pending[id].timer = setTimeout(function () {
      var session = sessionForBin(bin),
          data = null;

      if (session) {
        // were we try to get clever.
        if (pending[id].javascript) {
          // this will cause a reload on the client
          data = pending[id].javascript;
        } else if (pending[id].html) {
          // this will cause a reload on the client (but in future will be conditional)
          data = pending[id].html;

          // so at some point, we'll also want to send the CSS as a second message
        } else if (pending[id].css) {
          // this will cause a CSS reload only
          data = pending[id].css;
        }

        if (data) {
          session.res.forEach(function (res) {
            res.write('data:' + data.content.split('\n').join('\ndata:') + '\nevent:' + data.panelId + '\n\n');
            res.write('event: stats\ndata: ' + JSON.stringify({ connections: session.res.length }) + '\n\n');
            if (res.ajax) {
              res.end(); // lets older browsers finish their xhr request
              res.req.emit('close');
            }
          });
        }
      }

      delete pending[id];
    }, delayTrigger);
  },
  appendScripts: function (scripts) {
    // TODO this should really detect that there's an active session going
    // on and the user is saving, and therefore include the spike intelligently
    scripts.push('js/vendor/eventsource.js');
    scripts.push('js/spike.js');
  }
};
<|endoftext|>


<commit_before>
onClickTitle = function(e) {
  var title = $(this).html();
  var $todo = $(this).parent('.todo');
  $todo.data('title', title);
  $(this).remove();
  $todo.append('<input class="title-input" type="text" value="' + title + '"/>');
  var $input = $todo.children('.title-input');
  $input.keydown(onKeydownTitle).focus();

  // Move cursor to end of input
  var tmpStr = $input.val();
  $input.val('');
  $input.val(tmpStr);
};

reloadTodo = function(id) {
  $todo = $('#'+id);
  getTodo(id, function(res, success) {
    if(!success) console.log(res);
    $todo.replaceWith(res);
  })
}

showUndo = function(message, action, undoAction) {
  $('.notice').html(message + ' Undo ').fadeIn(0);

  setTimeout(function() { $('.notice').fadeOut(1000); }, 2000);
  window.undo_timeout = setTimeout(action, 3000);

  $('.undo').click(function(e) {
    e.preventDefault();
    $('.notice').fadeOut(0);
    clearTimeout(window.undo_timeout);
    undoAction();
  });
};

renderTitle = function($todo, title) {
  var title = title || $todo.data('title');
  $todo.data('title', '');
  $todo.children('.title-input').remove();
  $todo.append('' + title + '');
  $todo.children('.title').click(onClickTitle);
};

onKeydownTitle = function(e) {

  // Press Enter
  if(e.which === 13) {
    e.preventDefault();
    var $todo = $(this).parent('.todo');
    var title = $(this).val();
    restoreTitle($todo, title);
    updateTodo($todo.attr('id'), { title: title }, function(res, success) {
      console.log('update title res: ', res);
    });
  }

  // Press Backspace when input is empty
  if(e.which === 8 && $(this).val() === '') {
    e.preventDefault();
    var $todo = $(this).parent('.todo');
    $todo.hide();
    showUndo('Task Deleted', function() {
      $todo.remove();
      deleteTodo($todo.attr('id'), function(res, success) {
        console.log(res);
      });
    }, function() {
      renderTitle($todo);
      $todo.show();
    });
  }

  if(e.which === 27) {
    renderTitle($(this).parent('.todo'));
  }
};

getTodo = function(id, callback) {
  var url = '/api/todo/' + id;
  $.get(url, callback);
};

renderTodo = function(id, callback) {
  var url = '/api/todo/' + id;
  $.get(url, { render: true }, callback);
};

renderNewTodo = function(todo, callback) {
  var data = JSON.stringify({
    todo: todo,
    render: true
  });
  $.post('/api/todo', { data: data }, callback);
};

updateTodo = function(id, todo, callback) {
  var url = '/api/todo/' + id;
  $.put(url, todo, callback);
};

deleteTodo = function(id, callback) {
  var url = '/api/todo/' + id;
  $.delete(url, callback);
};

reorderTodos = function(ids, callback) {
  $.post('/api/todo/reorder', { data: JSON.stringify(ids) }, callback);
};

setTodoOrder = function() {
  var ids = $.map($('.todo'), function(todo) { return $(todo).attr('id'); });
  reorderTodos(ids, function(res) { console.log(res); });
};

$(function() {
  $('.add-todo').keydown(function(e) {
    if(e.which !== 13) return;

    var title = $(this).val();
    var uid = getCookie('productivUid');

    renderNewTodo({ title: title, owner: uid }, function(res, success) {
      console.log('res: ', res);
      if(!success) console.log(res.message);
      else {
        $('.todos').prepend(res);
        $('.add-todo').val('');
        var $todo = $('.todos').children('.todo').first();
        $todo.children('.title').click(onClickTitle);
        setTodoOrder();
      }
    });
  });

  $('.todo .check').click(function(e) {
    e.stopPropagation();
  }).change(function(e) {
    e.preventDefault();

    var $focused = $(document.activeElement);
    console.log($focused);
    var $todo = $(this).parent('.todo');
    var isDone = this.checked;
    var id = $todo.attr('id');

    $todo.toggleClass('done');

    updateTodo(id, { isDone: isDone }, function(res, success) {
      if(!success) {
        console.log(res.message);
        isDone = !isDone;
        e.target.checked = isDone;
        isDone ? $todo.addClass('done') : $todo.removeClass('done');
      } else console.log(res);

      console.log($focused);
    });
  });

  $('.todo .title').click(onClickTitle);

  $('.sortable').sortable({
    forcePlaceholderSize: true
  }).bind('sortupdate', setTodoOrder);
});<commit_msg>fixed typo<commit_after>
onClickTitle = function(e) {
  var title = $(this).html();
  var $todo = $(this).parent('.todo');
  $todo.data('title', title);
  $(this).remove();
  $todo.append('<input class="title-input" type="text"/>');

  var $input = $todo.children('.title-input');
  $input.keydown(onKeydownTitle)
        .val(title)
        .focus();

  // Move cursor to end of input
  var tmpStr = $input.val();
  $input.val('');
  $input.val(tmpStr);
};

reloadTodo = function(id) {
  $todo = $('#'+id);
  getTodo(id, function(res, success) {
    if(!success) console.log(res);
    $todo.replaceWith(res);
  })
}

showUndo = function(message, action, undoAction) {
  $('.notice').html(message + ' Undo ').fadeIn(0);

  setTimeout(function() { $('.notice').fadeOut(1000); }, 2000);
  window.undo_timeout = setTimeout(action, 3000);

  $('.undo').click(function(e) {
    e.preventDefault();
    $('.notice').fadeOut(0);
    clearTimeout(window.undo_timeout);
    undoAction();
  });
};

renderTitle = function($todo, title) {
  var title = title || $todo.data('title');
  $todo.data('title', '');
  $todo.children('.title-input').remove();
  $todo.append('' + title + '');
  $todo.children('.title').click(onClickTitle);
};

onKeydownTitle = function(e) {

  // Press Enter
  if(e.which === 13) {
    e.preventDefault();
    var $todo = $(this).parent('.todo');
    var title = $(this).val();
    renderTitle($todo, title);
    updateTodo($todo.attr('id'), { title: title }, function(res, success) {
      console.log('update title res: ', res);
    });
  }

  // Press Backspace when input is empty
  if(e.which === 8 && $(this).val() === '') {
    e.preventDefault();
    var $todo = $(this).parent('.todo');
    $todo.hide();
    showUndo('Task Deleted', function() {
      $todo.remove();
      deleteTodo($todo.attr('id'), function(res, success) {
        console.log(res);
      });
    }, function() {
      renderTitle($todo);
      $todo.show();
    });
  }

  if(e.which === 27) {
    renderTitle($(this).parent('.todo'));
  }
};

getTodo = function(id, callback) {
  var url = '/api/todo/' + id;
  $.get(url, callback);
};

renderTodo = function(id, callback) {
  var url = '/api/todo/' + id;
  $.get(url, { render: true }, callback);
};

renderNewTodo = function(todo, callback) {
  var data = JSON.stringify({
    todo: todo,
    render: true
  });
  $.post('/api/todo', { data: data }, callback);
};

updateTodo = function(id, todo, callback) {
  var url = '/api/todo/' + id;
  $.put(url, todo, callback);
};

deleteTodo = function(id, callback) {
  var url = '/api/todo/' + id;
  $.delete(url, callback);
};

reorderTodos = function(ids, callback) {
  $.post('/api/todo/reorder', { data: JSON.stringify(ids) }, callback);
};

setTodoOrder = function() {
  var ids = $.map($('.todo'), function(todo) { return $(todo).attr('id'); });
  reorderTodos(ids, function(res) { console.log(res); });
};

$(function() {
  $('.add-todo').keydown(function(e) {
    if(e.which !== 13) return;

    var title = $(this).val();
    var uid = getCookie('productivUid');

    renderNewTodo({ title: title, owner: uid }, function(res, success) {
      console.log('res: ', res);
      if(!success) console.log(res.message);
      else {
        $('.todos').prepend(res);
        $('.add-todo').val('');
        var $todo = $('.todos').children('.todo').first();
        $todo.children('.title').click(onClickTitle);
        setTodoOrder();
      }
    });
  });

  $('.todo .check').click(function(e) {
    e.stopPropagation();
  }).change(function(e) {
    e.preventDefault();

    var $focused = $(document.activeElement);
    console.log($focused);
    var $todo = $(this).parent('.todo');
    var isDone = this.checked;
    var id = $todo.attr('id');

    $todo.toggleClass('done');

    updateTodo(id, { isDone: isDone }, function(res, success) {
      if(!success) {
        console.log(res.message);
        isDone = !isDone;
        e.target.checked = isDone;
        isDone ? $todo.addClass('done') : $todo.removeClass('done');
      } else console.log(res);

      console.log($focused);
    });
  });

  $('.todo .title').click(onClickTitle);

  $('.sortable').sortable({
    forcePlaceholderSize: true
  }).bind('sortupdate', setTodoOrder);
});<|endoftext|>


<commit_before>var am = angular.module('am', ['ui.bootstrap']);
am.controller('amCtl', ['$scope', '$http', '$uibModal', '$log', function ($scope, $http, $uibModal, $log) {
    var AM_FORM_DATA = "amFormData";
    $scope.title = "AM REST DB Client";
    $scope.formData = {
        server: "16.165.217.186:8081",
        context: "/AssetManagerWebService/rs/",
        "ref-link": "db/amLocation/126874",
        collection: "EmplDepts",
        param: {
            limit: "10",
            offset: "1",
            filter: "",
            orderby: "",
            fields: []
        },

        user: "admin",
        password: ""
    };
    $scope.pageSize = 10;

    if (localStorage && localStorage[AM_FORM_DATA])
        $scope.formData = JSON.parse(localStorage.getItem(AM_FORM_DATA));

    $scope.query = function () {
        $scope.tableData = {};
        $http.post('/am/get', $scope.formData).success(function (data) {
            if (data instanceof Object) {
                if (data.entities instanceof Array)
                    $scope.tableData = data;
                else if (data.type == 'Buffer') {
                    $scope.tableData.count = 0;
                } else {
                    $scope.tableData.count = 1;
                    $scope.tableData.entities = [];
                    $scope.tableData.entities.push(data);
                }
            }
        });
        $scope.store();
    };

    $scope.load = function (data) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'am_modal.html',
            controller: 'amModalCtrl',
            size: "modal-lg",
            resolve: {
                data: function () {
                    return data;
                },
                form: function () {
                    return $scope.formData;
                }
            }
        });

        modalInstance.result.then(function () {
            $scope.query();
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.store = function () {
        if (localStorage)
            localStorage.setItem(AM_FORM_DATA, JSON.stringify($scope.formData));
    };

    // list order by and pagination =============================
    $scope.predicate = '';
    $scope.reverse = true;
    $scope.order = function (predicate) {
        console.log("order: " + predicate);
        $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        $scope.predicate = predicate;
    };

    $scope.jump = function (i) {
        var pos = i;
        $scope.currentPage = pos;
    };

    $scope.showValue = function (value) {
        if (value instanceof Object)
            return value[Object.keys(value)[0]];
        else
            return value;
    };

}]);

am.controller('amModalCtrl', function ($scope, $http, $uibModalInstance, data, form) {
    $scope.title = data['ref-link'];
    $scope.recordData = data;
    $scope.modifyData = {};
    $scope.ifUpdated = false;
    for (key in $scope.recordData) {
        $scope.modifyData[key] = "";
    }
    var form = clone(form);

    $scope.create = function (record) {
        var pos = data["ref-link"].lastIndexOf("/")
        form["ref-link"] = data["ref-link"].substring(0, pos);
        console.log("ref-link:" + form["ref-link"]);
        delete form["param"];
        form["collection"] = "";

        var update = {};
        for (key in record) {
            if (!JSON.stringify(record[key]).isEmpty() && key != 'ref-link' && key != 'self')
                update[key] = record[key];
        }
        form["data"] = update;
        $http.post('/am/post', form).success(function (data) {
            $scope.message = data;
            $scope.ifUpdated = true;
        });
    };

    $scope.update = function (record) {
        form["ref-link"] = data["ref-link"];
        delete form["param"];
        form["collection"] = "";

        var update = {};
        for (key in record) {
//            console.log("JSON.stringify(record[key]: " + JSON.stringify(record[key]));
            if (!JSON.stringify(record[key]).isEmpty() && key != 'ref-link' && key != 'self')
                update[key] = record[key];
        }
        form["data"] = update;
        $http.post('/am/put', form).success(function (data) {
            $scope.message = data;
            $scope.ifUpdated = true;
        });
    };

    $scope.delete = function (record) {
        form["ref-link"] = record["ref-link"];
        delete form["param"];
        form["collection"] = "";
        $http.post('/am/delete', form).success(function (data) {
            $scope.message = data;
            $scope.ifUpdated = true;
        });
    };

    $scope.fill = function () {
        for (var data in $scope.recordData) {
            if ($scope.recordData[data] instanceof Object)
                $scope.modifyData[data] = Object.keys($scope.recordData[data])[0];
            else
                $scope.modifyData[data] = $scope.recordData[data];
        }
    };

    $scope.clearMsg = function () {
        delete $scope.message;
    };

    $scope.ok = function () {
        if ($scope.ifUpdated)
            $uibModalInstance.close();
        else
            $uibModalInstance.dismiss('cancel');
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});

am.filter('startFrom', function () {
    return function (input, start) {
        if (input) {
            start = +start; //parse to int
            return input.slice(start);
        }
    }
});

am.filter('range', function () {
    return function (input, total) {
        total = Math.ceil(total);
        for (var i = 0; i < total; i++) {
            input.push(i);
        }
        return input;
    };
});

function clone(obj) {
    var o;
    if (typeof obj == "object") {
        if (obj === null) {
            o = null;
        } else {
            if (obj instanceof Array) {
                o = [];
                for (var i = 0, len = obj.length; i < len; i++) {
                    o.push(clone(obj[i]));
                }
            } else {
                o = {};
                for (var j in obj) {
                    o[j] = clone(obj[j]);
                }
            }
        }
    } else {
        o = obj;
    }
    return o;
}

String.prototype.isEmpty = function () {
    return (this.length === 0 || !this.trim());
};<commit_msg>fix json string empty bug<commit_after>var am = angular.module('am', ['ui.bootstrap']);
am.controller('amCtl', ['$scope', '$http', '$uibModal', '$log', function ($scope, $http, $uibModal, $log) {
    var AM_FORM_DATA = "amFormData";
    $scope.title = "AM REST DB Client";
    $scope.formData = {
        server: "16.165.217.186:8081",
        context: "/AssetManagerWebService/rs/",
        "ref-link": "db/amLocation/126874",
        collection: "EmplDepts",
        param: {
            limit: "10",
            offset: "1",
            filter: "",
            orderby: "",
            fields: []
        },

        user: "admin",
        password: ""
    };
    $scope.pageSize = 10;

    if (localStorage && localStorage[AM_FORM_DATA])
        $scope.formData = JSON.parse(localStorage.getItem(AM_FORM_DATA));

    $scope.query = function () {
        $scope.tableData = {};
        $http.post('/am/get', $scope.formData).success(function (data) {
            if (data instanceof Object) {
                if (data.entities instanceof Array)
                    $scope.tableData = data;
                else if (data.type == 'Buffer') {
                    $scope.tableData.count = 0;
                } else {
                    $scope.tableData.count = 1;
                    $scope.tableData.entities = [];
                    $scope.tableData.entities.push(data);
                }
            }
        });
        $scope.store();
    };

    $scope.load = function (data) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'am_modal.html',
            controller: 'amModalCtrl',
            size: "modal-lg",
            resolve: {
                data: function () {
                    return data;
                },
                form: function () {
                    return $scope.formData;
                }
            }
        });

        modalInstance.result.then(function () {
            $scope.query();
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.store = function () {
        if (localStorage)
            localStorage.setItem(AM_FORM_DATA, JSON.stringify($scope.formData));
    };

    // list order by and pagination =============================
    $scope.predicate = '';
    $scope.reverse = true;
    $scope.order = function (predicate) {
        console.log("order: " + predicate);
        $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        $scope.predicate = predicate;
    };

    $scope.jump = function (i) {
        var pos = i;
        $scope.currentPage = pos;
    };

    $scope.showValue = function (value) {
        if (value instanceof Object)
            return value[Object.keys(value)[0]];
        else
            return value;
    };

}]);

am.controller('amModalCtrl', function ($scope, $http, $uibModalInstance, data, form) {
    $scope.title = data['ref-link'];
    $scope.recordData = data;
    $scope.modifyData = {};
    $scope.ifUpdated = false;
    for (key in $scope.recordData) {
        $scope.modifyData[key] = "";
    }
    var form = clone(form);

    $scope.create = function (record) {
        var pos = data["ref-link"].lastIndexOf("/")
        form["ref-link"] = data["ref-link"].substring(0, pos);
        console.log("ref-link:" + form["ref-link"]);
        delete form["param"];
        form["collection"] = "";

        var update = {};
        for (key in record) {
            if (JSON.stringify(record[key]).length > 2 && key != 'ref-link' && key != 'self')
                update[key] = record[key];
        }
        form["data"] = update;
        $http.post('/am/post', form).success(function (data) {
            $scope.message = data;
            $scope.ifUpdated = true;
        });
    };

    $scope.update = function (record) {
        form["ref-link"] = data["ref-link"];
        delete form["param"];
        form["collection"] = "";

        var update = {};
        for (key in record) {
            if (JSON.stringify(record[key]).length > 2 && key != 'ref-link' && key != 'self')
                update[key] = record[key];
        }
        form["data"] = update;
        $http.post('/am/put', form).success(function (data) {
            $scope.message = data;
            $scope.ifUpdated = true;
        });
    };

    $scope.delete = function (record) {
        form["ref-link"] = record["ref-link"];
        delete form["param"];
        form["collection"] = "";
        $http.post('/am/delete', form).success(function (data) {
            $scope.message = data;
            $scope.ifUpdated = true;
        });
    };

    $scope.fill = function () {
        for (var data in $scope.recordData) {
            if ($scope.recordData[data] instanceof Object)
                $scope.modifyData[data] = Object.keys($scope.recordData[data])[0];
            else
                $scope.modifyData[data] = $scope.recordData[data];
        }
    };

    $scope.clearMsg = function () {
        delete $scope.message;
    };

    $scope.ok = function () {
        if ($scope.ifUpdated)
            $uibModalInstance.close();
        else
            $uibModalInstance.dismiss('cancel');
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});

am.filter('startFrom', function () {
    return function (input, start) {
        if (input) {
            start = +start; //parse to int
            return input.slice(start);
        }
    }
});

am.filter('range', function () {
    return function (input, total) {
        total = Math.ceil(total);
        for (var i = 0; i < total; i++) {
            input.push(i);
        }
        return input;
    };
});

function clone(obj) {
    var o;
    if (typeof obj == "object") {
        if (obj === null) {
            o = null;
        } else {
            if (obj instanceof Array) {
                o = [];
                for (var i = 0, len = obj.length; i < len; i++) {
                    o.push(clone(obj[i]));
                }
            } else {
                o = {};
                for (var j in obj) {
                    o[j] = clone(obj[j]);
                }
            }
        }
    } else {
        o = obj;
    }
    return o;
}

String.prototype.isEmpty = function () {
    return (this.trim().length === 0 || !this.trim());
};<|endoftext|>


<commit_before>var am = angular.module('am', ['ui.bootstrap']);
am.controller('amCtl', function ($scope, $http, $uibModal, $log, $q) {
    var AM_FORM_DATA = "amFormData";
    $scope.title = "AM REST DB Client";
    $scope.formData = {
        server: "16.165.217.186:8081",
        context: "/AssetManagerWebService/rs/",
        "ref-link": "",     // "db/amLocation/126874",
        collection: "",     // "EmplDepts",
        param: {
            limit: "100",
            offset: "0",
            filter: "",
            orderby: "",
            fields: []
        },

        user: "admin",
        password: ""
    };
    $scope.pageSize = 10;
    $scope.fields = [];
    $scope.breadcrumb = [];
    $scope.toggleFilter = function toggleSelection(field) {
        var idx = $scope.fields.indexOf(field);
        if (idx > -1) {
            $scope.fields.splice(idx, 1);
        }
        else {
            $scope.fields.push(field);
        }
//        $scope.addFields();
    };
    $scope.addFields = function () {
        $scope.formData.param.fields = $scope.fields;
        $scope.query();
    };

    if (localStorage && localStorage[AM_FORM_DATA]) {
        $scope.formData = JSON.parse(localStorage.getItem(AM_FORM_DATA));
        $scope.formData.collection = "";
        $scope.formData.param.filter = "";
        $scope.formData.param.offset = 0;
        $scope.formData.param.orderby = "";
        $scope.formData.param.fields = [];
    }

    $scope.query = function (form) {
        $scope.loading = true;
        $scope.tableData = {};

        // if param is query form, use it
        var form = form ? form : clone($scope.formData);
        $scope.tableName = form["ref-link"].split("/")[1];

        form.method = "get";
        $http.post('/am/rest', form).success(function (data) {
//            console.log("rest data: " + JSON.stringify(data));
            $scope.loading = false;
            if (data instanceof Object) {
                console.log("query data:" + JSON.stringify(data));
                if (data.entities instanceof Array)
                    $scope.tableData = data;
                else if (data.type == 'Buffer') {
                    $scope.tableData.count = 0;
                } else {
                    $scope.tableData.count = 1;
                    $scope.tableData.entities = [];
                    $scope.tableData.entities.push(data);
                }
            } else {
                $scope.message = data;
            }
        });
        $scope.store();
    };

    $scope.load = function (data) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'am_modal.html',
            controller: 'amModalCtrl',
            size: "modal-lg",
            resolve: {
                data: function () {
                    return data;
                },
                form: function () {
                    return clone($scope.formData);
                }
            }
        });

        modalInstance.result.then(function () {
            $scope.query();
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.store = function () {
        if (localStorage)
            localStorage.setItem(AM_FORM_DATA, JSON.stringify($scope.formData));
    };

    // list order by and pagination =============================
    $scope.predicate = '';
    $scope.reverse = true;
    $scope.order = function (predicate, reQuery) {
        console.log("order: " + predicate);
        $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        $scope.predicate = predicate;
//        $scope.formData.param.orderby = predicate + ($scope.reverse) ? " desc" : "";
        if (reQuery) {
            var form = clone($scope.formData);
            form.param.orderby = predicate;
            if ($scope.reverse)
                form.param.orderby = form.param.orderby + " desc";
            $scope.query(form);
        }
    }
    ;

    $scope.jump = function (i) {
        var pos = i;
        $scope.currentPage = pos;
    };

    $scope.showValue = function (value) {
        if (value instanceof Object)
            return value[Object.keys(value)[0]];
        else
            return value;
    };

    $scope.metadata = function (schema, link, callback) {
        var form = clone($scope.formData);
        var metadata = "";
        if (schema == 'all') {
            metadata = "metadata/tables";
        } else {
            metadata = "metadata/schema/" + schema;

            // click query table from tree
            if (!link && !callback) {
                $scope.formData['ref-link'] = "db/" + schema;
//                $scope.tableName = schema;
                $scope.formData.param.fields = [];
                $scope.fields = [];
                $scope.query();
            }

        }
        form['metadata'] = metadata;
        $http.post('/am/metadata', form).success(function (data) {

            if (callback instanceof Function) {
                callback(data);
            } else {
                if (data.Tables) {
                    $scope.metadata["tables"] = [];
                    for (var t in data.Tables.Table) {
                        $scope.metadata["tables"].push(data.Tables.Table[t]["$"]);
                    }

//                console.log("meta data: " + JSON.stringify($scope.metadata["tables"]));
                } else if (data.table) {
//                console.log("meta data table: " + JSON.stringify(data));
//                console.log("parent: " + JSON.stringify(parent));

                    if (link) {
                        link["table"] = data.table;

                        if (link["parent"])
                            link["table"].parent = link["parent"] + "." + link["$"]["sqlname"];
                        else
                            link["table"].parent = link["$"]["sqlname"];
//                    console.log("parent's reverse: " + parent["table"].parent);
                    }
                    else
                        $scope.metadata["table"] = data.table;
                }
            }

        });
    };

    $scope.foldChild = function (link) {
//        console.log("child: " + JSON.stringify(child));
        delete link["table"];
    };

    $scope.addBreadcrumb = function (refLink) {
        var bread = {
            label: refLink.split("/")[1] + "[" + refLink.split("/")[2] + "]",
            link: refLink
        };

        if ($scope.breadcrumb.map(function (e) {
            return e.label;
        }).indexOf(bread.label) < 0)
            $scope.breadcrumb.push(bread);
    };

    $scope.removeBreadcrumb = function (refLink) {
//        console.log("refLink: " + refLink);
        if (!refLink)
            $scope.breadcrumb = [];
        else {
            var bread = {
                label: refLink.split("/")[1] + "[" + refLink.split("/")[2] + "]",
                link: refLink
            };
            var pos = $scope.breadcrumb.map(function (e) {
                return e.label;
            }).indexOf(bread.label);

            $scope.breadcrumb.splice(pos, 1);
        }
    };

    $scope.useBreadcrumb = function (bread) {
        var form = clone($scope.formData);
        form["ref-link"] = bread.link;
        $scope.query(form);
        $scope.hiddenRelations();
    };

    $scope.showRelations = function (record, parent) {
        if (!parent) {
            $scope.relations = [];
            $scope.relations.push({
                table: record["ref-link"].split("/")[1],
                active: true,
                records: [record],
                child: null
            });
        } else {
            parent.child = [];
            parent.child.push({
                table: parent.table,
                active: true,
                records: [record],
                child: null
            });
        }

        $scope.addBreadcrumb(record["ref-link"]);

        $scope.metadata(record["ref-link"].split("/")[1], null, function (data) {
            var links = data.table.link;
            for (var i in links) {
                var form = clone($scope.formData);
                var sqlname = links[i]['$']['sqlname'];

                // check 1v1
                if (links[i]['$']['card11']) {
                    form["ref-link"] = "db/" + links[i]['$']['desttable'];
                    form.param.filter = links[i]['$']['reverse'] + ".PK=" + record["ref-link"].split('/')[2];
                } else {
                    form["ref-link"] = record["ref-link"];
                    form["collection"] = "/" + sqlname;
                }

                form.method = "get";
                if (!parent) {
                    $scope.relations.push({
                        table: sqlname,
                        records: [],
                        form: form
                    });
                } else {
                    parent.child.push({
                        table: sqlname,
                        records: [],
                        form: form
                    });
                }

            }
        });

    };

    $scope.getRecords = function (record) {
        if (record.form) {
            $http.post('/am/rest', record.form).success(function (data) {
                record.records = data.entities;
            });
        }
    };

    $scope.showRecord = function (record) {
        record.active = (record.active) ? !record.active : true;
    };

    $scope.hiddenRelations = function (record) {
//        console.log("record: " + JSON.stringify(record));
        if (!record) {
            delete $scope.relations;
            $scope.removeBreadcrumb();
        } else {
            $scope.removeBreadcrumb(record.form["ref-link"]);
            delete record.child;
        }
    };

    $scope.removeOneTable = function () {
        delete $scope.metadata["table"];
        $scope.formData.param.fields = [];
        $scope.fields = [];
        $scope.breadcrumb = [];
        $scope.hiddenRelations();
        delete $scope.tableData;
        delete $scope.tableName;
    };

    $scope.getMeta = function (ref) {
        var words = ref.split('/');
        for (var i in words) {
            if (words[i].indexOf("am") == 0)
                return 'metadata/schema/' + words[i];
        }
        return "metadata/tables";
    };

    $scope.clearMsg = function () {
        delete $scope.message;
    };

    $scope.toggleNavbar = function () {
        if ($scope.navbar) {
            $scope.navbar = !$scope.navbar;
        } else
            $scope.navbar = true;
    };

    $scope.toggleServer = function () {
        if ($scope.serverbar) {
            $scope.serverbar = !$scope.serverbar;
        } else
            $scope.serverbar = true;
    };

    $scope.metadata("all");
});

am.filter('startFrom', function () {
    return function (input, start) {
        if (input) {
            start = +start; //parse to int
            return input.slice(start);
        }
    }
});

am.filter('range', function () {
    return function (input, total) {
        total = Math.ceil(total);
        for (var i = 0; i < total; i++) {
            input.push(i);
        }
        return input;
    };
});

function clone(obj) {
    var o;
    if (typeof obj == "object") {
        if (obj === null) {
            o = null;
        } else {
            if (obj instanceof Array) {
                o = [];
                for (var i = 0, len = obj.length; i < len; i++) {
                    o.push(clone(obj[i]));
                }
            } else {
                o = {};
                for (var j in obj) {
                    o[j] = clone(obj[j]);
                }
            }
        }
    } else {
        o = obj;
    }
    return o;
}<commit_msg>fix back<commit_after>var am = angular.module('am', ['ui.bootstrap']);
am.controller('amCtl', function ($scope, $http, $uibModal, $log, $q) {
    var AM_FORM_DATA = "amFormData";
    $scope.title = "AM REST DB Client";
    $scope.formData = {
        server: "16.165.217.186:8081",
        context: "/AssetManagerWebService/rs/",
        "ref-link": "",     // "db/amLocation/126874",
        collection: "",     // "EmplDepts",
        param: {
            limit: "100",
            offset: "0",
            filter: "",
            orderby: "",
            fields: []
        },

        user: "admin",
        password: ""
    };
    $scope.pageSize = 10;
    $scope.fields = [];
    $scope.breadcrumb = [];
    $scope.toggleFilter = function toggleSelection(field) {
        var idx = $scope.fields.indexOf(field);
        if (idx > -1) {
            $scope.fields.splice(idx, 1);
        }
        else {
            $scope.fields.push(field);
        }
//        $scope.addFields();
    };
    $scope.addFields = function () {
        $scope.formData.param.fields = $scope.fields;
        $scope.query();
    };

    if (localStorage && localStorage[AM_FORM_DATA]) {
        $scope.formData = JSON.parse(localStorage.getItem(AM_FORM_DATA));
        $scope.formData.collection = "";
        $scope.formData.param.filter = "";
        $scope.formData.param.offset = 0;
        $scope.formData.param.orderby = "";
        $scope.formData.param.fields = [];
    }

    $scope.query = function (form) {
        $scope.loading = true;
        $scope.tableData = {};

        // if param is query form, use it
        var form = form ? form : clone($scope.formData);
        $scope.tableName = form["ref-link"].split("/")[1];

        form.method = "get";
        $http.post('/am/rest', form).success(function (data) {
//            console.log("rest data: " + JSON.stringify(data));
            $scope.loading = false;
            if (data instanceof Object) {
                console.log("query data:" + JSON.stringify(data));
                if (data.entities instanceof Array)
                    $scope.tableData = data;
                else if (data.type == 'Buffer') {
                    $scope.tableData.count = 0;
                } else {
                    $scope.tableData.count = 1;
                    $scope.tableData.entities = [];
                    $scope.tableData.entities.push(data);
                }
            } else {
                $scope.message = data;
            }
        });
        $scope.store();
    };

    $scope.load = function (data) {
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'am_modal.html',
            controller: 'amModalCtrl',
            size: "modal-lg",
            resolve: {
                data: function () {
                    return data;
                },
                form: function () {
                    return clone($scope.formData);
                }
            }
        });

        modalInstance.result.then(function () {
            $scope.query();
        }, function () {
            $log.info('Modal dismissed at: ' + new Date());
        });
    };

    $scope.store = function () {
        if (localStorage)
            localStorage.setItem(AM_FORM_DATA, JSON.stringify($scope.formData));
    };

    // list order by and pagination =============================
    $scope.predicate = '';
    $scope.reverse = true;
    $scope.order = function (predicate, reQuery) {
        console.log("order: " + predicate);
        $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
        $scope.predicate = predicate;
//        $scope.formData.param.orderby = predicate + ($scope.reverse) ? " desc" : "";
        if (reQuery) {
            var form = clone($scope.formData);
            form.param.orderby = predicate;
            if ($scope.reverse)
                form.param.orderby = form.param.orderby + " desc";
            $scope.query(form);
        }
    }
    ;

    $scope.jump = function (i) {
        var pos = i;
        $scope.currentPage = pos;
    };

    $scope.showValue = function (value) {
        if (value instanceof Object)
            return value[Object.keys(value)[0]];
        else
            return value;
    };

    $scope.metadata = function (schema, link, callback) {
        var form = clone($scope.formData);
        var metadata = "";
        if (schema == 'all') {
            metadata = "metadata/tables";
        } else {
            metadata = "metadata/schema/" + schema;

            // click query table from tree
            if (!link && !callback) {
                $scope.formData['ref-link'] = "db/" + schema;
//                $scope.tableName = schema;
                $scope.formData.param.fields = [];
                $scope.fields = [];
                $scope.query();
            }

        }
        form['metadata'] = metadata;
        $http.post('/am/metadata', form).success(function (data) {

            if (callback instanceof Function) {
                callback(data);
            } else {
                if (data.Tables) {
                    $scope.metadata["tables"] = [];
                    for (var t in data.Tables.Table) {
                        $scope.metadata["tables"].push(data.Tables.Table[t]["$"]);
                    }

//                console.log("meta data: " + JSON.stringify($scope.metadata["tables"]));
                } else if (data.table) {
//                console.log("meta data table: " + JSON.stringify(data));
//                console.log("parent: " + JSON.stringify(parent));

                    if (link) {
                        link["table"] = data.table;

                        if (link["parent"])
                            link["table"].parent = link["parent"] + "." + link["$"]["sqlname"];
                        else
                            link["table"].parent = link["$"]["sqlname"];
//                    console.log("parent's reverse: " + parent["table"].parent);
                    }
                    else
                        $scope.metadata["table"] = data.table;
                }
            }

        });
    };

    $scope.foldChild = function (link) {
//        console.log("child: " + JSON.stringify(child));
        delete link["table"];
    };

    $scope.addBreadcrumb = function (refLink) {
        var bread = {
            label: refLink.split("/")[1] + "[" + refLink.split("/")[2] + "]",
            link: refLink
        };

        if ($scope.breadcrumb.map(function (e) {
            return e.label;
        }).indexOf(bread.label) < 0)
            $scope.breadcrumb.push(bread);
    };

    $scope.removeBreadcrumb = function (refLink) {
//        console.log("refLink: " + refLink);
        if (!refLink)
            $scope.breadcrumb = [];
        else {
            var bread = {
                label: refLink.split("/")[1] + "[" + refLink.split("/")[2] + "]",
                link: refLink
            };
            var pos = $scope.breadcrumb.map(function (e) {
                return e.label;
            }).indexOf(bread.label);

            $scope.breadcrumb.splice(pos, 1);
        }
    };

    $scope.useBreadcrumb = function (bread) {
        var form = clone($scope.formData);
        form["ref-link"] = bread.link;
        $scope.query(form);
        $scope.hiddenRelations();
    };

    $scope.showRelations = function (record, parent) {
        if (!parent) {
            $scope.relations = [];
            $scope.relations.push({
                table: record["ref-link"].split("/")[1],
                active: true,
                records: [record],
                child: null
            });
        } else {
            parent.child = [];
            parent.child.push({
                table: parent.table,
                active: true,
                records: [record],
                child: null
            });
        }

        $scope.addBreadcrumb(record["ref-link"]);

        $scope.metadata(record["ref-link"].split("/")[1], null, function (data) {
            var links = data.table.link;
            for (var i in links) {
                var form = clone($scope.formData);
                var sqlname = links[i]['$']['sqlname'];

                // check 1v1
                if (links[i]['$']['card11']) {
                    form["ref-link"] = "db/" + links[i]['$']['desttable'];
                    form.param.filter = links[i]['$']['reverse'] + ".PK=" + record["ref-link"].split('/')[2];
                } else {
                    form["ref-link"] = record["ref-link"];
                    form["collection"] = "/" + sqlname;
                }

                form.method = "get";
                if (!parent) {
                    $scope.relations.push({
                        table: sqlname,
                        records: [],
                        form: form
                    });
                } else {
                    parent.child.push({
                        table: sqlname,
                        records: [],
                        form: form
                    });
                }

            }
        });

    };

    $scope.getRecords = function (record) {
        if (record.form) {
            $http.post('/am/rest', record.form).success(function (data) {
                record.records = data.entities;
            });
        }
    };

    $scope.showRecord = function (record) {
        record.active = (record.active) ? !record.active : true;
    };

    $scope.hiddenRelations = function (record) {
//        console.log("record: " + JSON.stringify(record));
        if (!record) {
            delete $scope.relations;
            $scope.removeBreadcrumb();
        } else {
            $scope.removeBreadcrumb("db/" + record.table + "/dummy");
            delete record.child;
        }
    };

    $scope.removeOneTable = function () {
        delete $scope.metadata["table"];
        $scope.formData.param.fields = [];
        $scope.fields = [];
        $scope.breadcrumb = [];
        $scope.hiddenRelations();
        delete $scope.tableData;
        delete $scope.tableName;
    };

    $scope.getMeta = function (ref) {
        var words = ref.split('/');
        for (var i in words) {
            if (words[i].indexOf("am") == 0)
                return 'metadata/schema/' + words[i];
        }
        return "metadata/tables";
    };

    $scope.clearMsg = function () {
        delete $scope.message;
    };

    $scope.toggleNavbar = function () {
        if ($scope.navbar) {
            $scope.navbar = !$scope.navbar;
        } else
            $scope.navbar = true;
    };

    $scope.toggleServer = function () {
        if ($scope.serverbar) {
            $scope.serverbar = !$scope.serverbar;
        } else
            $scope.serverbar = true;
    };

    $scope.metadata("all");
});

am.filter('startFrom', function () {
    return function (input, start) {
        if (input) {
            start = +start; //parse to int
            return input.slice(start);
        }
    }
});

am.filter('range', function () {
    return function (input, total) {
        total = Math.ceil(total);
        for (var i = 0; i < total; i++) {
            input.push(i);
        }
        return input;
    };
});

function clone(obj) {
    var o;
    if (typeof obj == "object") {
        if (obj === null) {
            o = null;
        } else {
            if (obj instanceof Array) {
                o = [];
                for (var i = 0, len = obj.length; i < len; i++) {
                    o.push(clone(obj[i]));
                }
            } else {
                o = {};
                for (var j in obj) {
                    o[j] = clone(obj[j]);
                }
            }
        }
    } else {
        o = obj;
    }
    return o;
}<|endoftext|>


<commit_before>/* global MyRadioAPIKey */
function updateShow() {

  console.log("Starting to update now and next.");

  var request = new XMLHttpRequest()
  request.open(
    'GET',
    '//ury.org.uk/api/v2/timeslot/currentandnext/?api_key=' + MyRadioAPIKey,
    true,
  )

  request.onload = function () {
    if (this.status >= 200 && this.status < 400) {
      success(JSON.parse(this.response))
    } else {
      fail(this.response)
    }
  }
  request.send()

  //Schedule when the next update will happen.
  scheduleUpdate()
}

function scheduleUpdate() {
  // Call the function 15 seconds past every half hour (to line up with live stream)
  let nextCall = new Date()

  if (nextCall.getMinutes() >= 30) {
    nextCall.setHours(nextCall.getHours() + 1)
    nextCall.setMinutes(0)
  } else {
    nextCall.setMinutes(30)
  }
  nextCall.setSeconds(15)

  let difference = nextCall - new Date()
  setTimeout(updateShow, difference)
}

function calcTime(timestamp) {
  var date = new Date(timestamp * 1000)
  // Hours part from the timestamp
  var hours = '0' + date.getHours()
  // Minutes part from the timestamp
  var minutes = '0' + date.getMinutes()
  // Use substr to remove the extra 0 if 2 digit hour/min
  return hours.substr(-2) + ':' + minutes.substr(-2)
}

function makeContent(show) {
  if (typeof show.title !== 'undefined') {
    // If we're off air
    if (show.end_time === 'The End of Time') {
      return (
        '
We\'re off air right now.
' +
        '
Check back next term.
'
      )
    }
    // Use "Now" as start time if it's missing
    let startTimeString = calcTime(show.start_time)
    if (typeof show.start_time === 'undefined') {
      startTimeString = 'Now'
    }
    // Default case (regular show)
    return (
      '
' +
      show.title +
      '
' +
      '
' +
      startTimeString +
      ' - ' +
      calcTime(show.end_time) +
      '
'
    )
  } else {
    return 'Looks like there is nothing on here.'
  }
}

function fail(data) {
  console.log("Failed to update now and next.", data)
}

function success(data) {
  console.log("Successfully retrieved for now and next.")
  // Current show
  if (typeof data.payload.current === 'undefined') {
    // There is no current show; Something is probably very wrong...
    $('.current-and-next-now').replaceWith(
      '
' +
        '
Now
' +
        '
There\'s nothing on right now.
',
    )
    $('#studiomessage *').attr('disabled', true)
  } else if (typeof data.payload.current.url !== 'undefined') {
    $('.current-and-next-now').replaceWith(
      '' +
        '
Now
' +
        makeContent(data.payload.current) +
        '',
    )
    $('#studiomessage *').attr('disabled', false)
  } else {
    $('.current-and-next-now').replaceWith(
      '
' +
        '
Now
' +
        makeContent(data.payload.current) +
        '',
    )
    $('#studiomessage *').attr('disabled', true)
  }

  // Next show
  if (typeof data.payload.next === 'undefined') {
    // There is no next show (e.g. we're off air)
    $('.current-and-next-next').replaceWith(
      '
' +
        '
Next
' +
        '
There\'s nothing up next yet.
' +
        '',
    )
  } else if (typeof data.payload.next.url !== 'undefined') {
    $('.current-and-next-next').replaceWith(
      '' +
        '
Next
' +
        makeContent(data.payload.next) +
        '',
    )
  } else {
    $('.current-and-next-next').replaceWith(
      '
' +
        '
Next
' +
        makeContent(data.payload.next) +
        '',
    )
  }

  $('.current-and-next-img img').attr(
    'src',
    '//ury.org.uk' + data.payload.current.photo,
  )
}

$(document).ready(function () {
  // Call on startup too, this will schedule the next update.
  updateShow()
})
<commit_msg>Fix console logs.<commit_after>/* global MyRadioAPIKey */
function updateShow() {

  console.log("Starting to update now and next.");

  var request = new XMLHttpRequest()
  request.open(
    'GET',
    '//ury.org.uk/api/v2/timeslot/currentandnext/?api_key=' + MyRadioAPIKey,
    true,
  )

  request.onload = function () {
    if (this.status >= 200 && this.status < 400) {
      success(JSON.parse(this.response))
    } else {
      fail(this.response)
    }
  }
  request.send()

  //Schedule when the next update will happen.
  scheduleUpdate()
}

function scheduleUpdate() {
  // Call the function 15 seconds past every half hour (to line up with live stream)
  let nextCall = new Date()

  if (nextCall.getMinutes() >= 30) {
    nextCall.setHours(nextCall.getHours() + 1)
    nextCall.setMinutes(0)
  } else {
    nextCall.setMinutes(30)
  }
  nextCall.setSeconds(15)

  let difference = nextCall - new Date()
  setTimeout(updateShow, difference)
}

function calcTime(timestamp) {
  var date = new Date(timestamp * 1000)
  // Hours part from the timestamp
  var hours = '0' + date.getHours()
  // Minutes part from the timestamp
  var minutes = '0' + date.getMinutes()
  // Use substr to remove the extra 0 if 2 digit hour/min
  return hours.substr(-2) + ':' + minutes.substr(-2)
}

function makeContent(show) {
  if (typeof show.title !== 'undefined') {
    // If we're off air
    if (show.end_time === 'The End of Time') {
      return (
        '
We\'re off air right now.
' +
        '
Check back next term.
'
      )
    }
    // Use "Now" as start time if it's missing
    let startTimeString = calcTime(show.start_time)
    if (typeof show.start_time === 'undefined') {
      startTimeString = 'Now'
    }
    // Default case (regular show)
    return (
      '
' +
      show.title +
      '
' +
      '
' +
      startTimeString +
      ' - ' +
      calcTime(show.end_time) +
      '
'
    )
  } else {
    return 'Looks like there is nothing on here.'
  }
}

function fail(data) {
  console.log("Failed to update now and next.", data)
}

function success(data) {
  console.log("Successfully retrieved now and next.")
  // Current show
  if (typeof data.payload.current === 'undefined') {
    // There is no current show; Something is probably very wrong...
    $('.current-and-next-now').replaceWith(
      '
' +
        '
Now
' +
        '
There\'s nothing on right now.
',
    )
    $('#studiomessage *').attr('disabled', true)
  } else if (typeof data.payload.current.url !== 'undefined') {
    $('.current-and-next-now').replaceWith(
      '' +
        '
Now
' +
        makeContent(data.payload.current) +
        '',
    )
    $('#studiomessage *').attr('disabled', false)
  } else {
    $('.current-and-next-now').replaceWith(
      '
' +
        '
Now
' +
        makeContent(data.payload.current) +
        '',
    )
    $('#studiomessage *').attr('disabled', true)
  }

  // Next show
  if (typeof data.payload.next === 'undefined') {
    // There is no next show (e.g. we're off air)
    $('.current-and-next-next').replaceWith(
      '
' +
        '
Next
' +
        '
There\'s nothing up next yet.
' +
        '',
    )
  } else if (typeof data.payload.next.url !== 'undefined') {
    $('.current-and-next-next').replaceWith(
      '' +
        '
Next
' +
        makeContent(data.payload.next) +
        '',
    )
  } else {
    $('.current-and-next-next').replaceWith(
      '
' +
        '
Next
' +
        makeContent(data.payload.next) +
        '',
    )
  }

  $('.current-and-next-img img').attr(
    'src',
    '//ury.org.uk' + data.payload.current.photo,
  )

  console.log("Finished rendering now and next.")
}

$(document).ready(function () {
  // Call on startup too, this will schedule the next update.
  updateShow()
})
<|endoftext|>