var restBaseUrl = "http://cloudapi.labjack.com";
var username = "";
var prependChannelName = true;

var UPDATE_MILLISECONDS = 900000;
var channelNameList = [];

function initCD(myusername, autoUpdate, callbackFunction) {
    username = myusername;
    $(".channel").each(function() {
        var thisChannelName = $(this).text();
        $(this).attr("cdChannelName", thisChannelName);
        channelNameList.push(thisChannelName);
    });
    updateChannelValues(callbackFunction);
    if (autoUpdate == true) {
        setInterval(function(){ 
            updateChannelValues(callbackFunction);
        }, UPDATE_MILLISECONDS);
    }
}

function updateChannelValues(callbackFunction) {
    for (var i in channelNameList) {
        if ("" != restBaseUrl) {
            $.getJSON(restBaseUrl + "/" + username + "/channels/" + channelNameList[i] +  ".json?callback=?",
                function(item) {
                    var readingAndUnits = "No recent reading";
                    var utcTime = "";
                    if (undefined != item.latestReading) {
                        readingAndUnits = item.latestReading.stringValue;
                        utcTime = item.latestReading.updated_at;
                    }
                    if (item.units != "" && item.units != null) {
                        readingAndUnits += " (" + item.units + ")";
                    }
                    if ("undefined" != typeof(gadgets) && "undefined" != typeof(gadgets.window)) {
                        gadgets.window.setTitle(item.name);
                    } 
                    if (prependChannelName) {
                        readingAndUnits = item.name + ": " + readingAndUnits;
                    }
                    $(".channel[cdChannelName='" + item.nickname + "']").text(readingAndUnits).addClass("prettyDate").attr("title", utcTime).data("utcTime", utcTime);
                    if ("undefined" != typeof(gadgets) && "undefined" != typeof(gadgets.window))
                        gadgets.window.adjustHeight();
                    if (null != callbackFunction) {
                        callbackFunction(item);
                    }
                }
            );
        }
    }
}