/* http://fgnass.github.com/spin.js/ */
$.fn.spin = function(opts) {
this.each(function() {
var $this = $(this),
data = $this.data();
if (data.spinner) {
data.spinner.stop();
delete data.spinner;
}
if (opts !== false) {
data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
}
});
return this;
};
$.fn.disabled = function (disabled) {
if (disabled)
this.attr('disabled', 'disabled');
else
this.removeAttr('disabled');
return this;
};
var Timer = function (interval, cb) {
var handle = null;
this.enable = function () {
if (handle) return;
handle = window.setInterval(cb, interval);
};
this.disable = function () {
if (!handle) return;
window.clearInterval(handle);
handle = null;
};
return this;
};
function html (tag, params, html) {
return $("<" + tag + " />", $.extend({html: html}, params));
};
function hosts_realtime (params) {
var t = params.t;
var refreshTimer = Timer(2 * 1000, refresh);
var animate = false; // true;
function render_host (host) {
var columns = [
html("td", {},
html("a", { href: params.host.replace('0', host.id) }, "#" )
),
];
$.each(params.columns, function (i, name) {
column = html("td", { class: name }, host[name]);
if (name == 'state')
column.addClass(host['state_class']);
columns.push(column);
});
return html("tr", {id: host.id}, columns);
}
// XXX: refresh > interval?
function refresh () {
console.log("refresh: " + t);
var refresh = $('#refresh').disabled(true);
var spinner = $('#wrapper').spin();
var url = params.url;
var query = $.param($.extend(params.filters, {t: t }), true); // using traditional encoding for multi-values
$.getJSON(url, query, function (data) {
var t1 = data.t;
var hosts = data.hosts;
console.log("refresh: " + t + " -> " + t1 + ": " + hosts.length);
$.each(hosts, function (i, host) {
var item = $('#' + host.id);
if (item.length) {
if (animate) item.slideUp();
} else {
item = render_host(host)
if (animate) item.hide();
}
// move to top
item.prependTo($('#hosts tbody'));
if (animate)
item.slideDown();
else
item.effect("highlight", {}, 'slow');
});
// update
t = t1;
}).error(function () {
alert("Error :(");
// disable auto-refresh
refreshTimer.disable();
}).complete(function () {
spinner.spin(false);
refresh.disabled(false);
});
}
return function () {
// init
if (animate)
$("#hosts").css('display', 'block');
$("#refresh").click(function () {
// in case diabled on error
refreshTimer.enable();
refresh();
$("#pause").disabled(false);
});
$("#pause").click(function () {
console.log("pause");
refreshTimer.disable();
$("#pause").disabled(true);
});
// start auto-refresh
refreshTimer.enable();
}
}