/* 
 * Alter a delivery message based on a cutoff time and a time zone
 * offset for the cutoff time. 
 */
function alterDeliveryMsg(msgId, delivCutoff, delivCutoffTzOffset, msgContainerId, blinkOutMillis, msgs) {
    var localDelivCutoff = getLocalDelivCutoff(delivCutoff, delivCutoffTzOffset);
    var now = new Date();

    var deliveryMsg;
    var millisToGo = localDelivCutoff.getTime() - now.getTime();
    var nowDay = now.getDay();
    if (millisToGo > 0) {
        // Before the cutoff. other vs Sun
        deliveryMsg = (nowDay != 0) ? msgs[0] : msgs[2];
    } else {
        // After the cutoff. other vs Sat
        deliveryMsg = (nowDay != 6) ? msgs[2] : msgs[1];
    }

    // Set the page element to the delivery message.
    $("#"+msgId).text(deliveryMsg);

    if (millisToGo >= 0 || -millisToGo >= blinkOutMillis || nowDay == 0 || nowDay == 6) {
        // Show because it's before cutoff or after blink-out period or
        // neither Sat or Sun.
        $("#"+msgContainerId).show();
    } else {
        $("#"+msgContainerId).hide();
        millisToGo += blinkOutMillis;
    }

    // Repeat execution in an hour or at the next cutoff time, whichever
    // is earlier.
    if (millisToGo < 0) {
        // Get the millis to the next cutoff.
        millisToGo = 86400000 + millisToGo;
    }
    millisToGo = (millisToGo <= 3600000) ? millisToGo : 3600000;
    setTimeout(function(){ alterDeliveryMsg(msgId, delivCutoff, delivCutoffTzOffset, msgContainerId, blinkOutMillis, msgs ) }, millisToGo);
}

/*
 * Returns the delivery cutoff time in local time.
 */
function getLocalDelivCutoff(delivCutoff, delivCutoffTzOffset) {
    var localCutoff = new Date();

    var cutoffMin = delivCutoff%100;
    var cutoffHr = (delivCutoff-cutoffMin)/100;

    var adjust = delivCutoffTzOffset - localCutoff.getTimezoneOffset();
    var adjustMin = adjust%60;
    var adjustHr = (adjust-adjustMin)/60;

    localCutoff.setHours(cutoffHr + adjustHr);
    localCutoff.setMinutes(cutoffMin + adjustMin);
    localCutoff.setSeconds(0);
    localCutoff.setMilliseconds(0);
    
    return localCutoff;
}
