var failures = 0;
var timeouts = [1, 5, 10, 60, 300];
var curerror = null;

function got_update(data, status, xhr) {
    failures = 0;
    clear_error();
    if(data != "") {
	$("#status").replaceWith(data);
    }
    setTimeout(queue_update, 2500);
}

function clear_error() {
    if(curerror !== null) {
	curerror.remove();
	curerror = null;
    }
}

function got_error(xhr, status, err) {
    clear_error();
    var err = $("<p>(Currently not updating live)</p>");
    $("#status").append(err);
    curerror = err;
    var to = failures++;
    if(to >= timeouts.length)
	to = timeouts.length - 1;
    setTimeout(queue_update, timeouts[to] * 1000);
}

function queue_update() {
    var url = "https://www.havenandhearth.com/portal/index/status";
    var seq = $("#status").attr("sequence")
    if(seq)
	url += "?seq=" + seq;
    $.ajax({
	url: url,
	cache: false,
	dataType: "text",
	success: got_update,
	error: got_error
    });
}

$(document).ready(queue_update)
