// the URL for our data refresh, must return JSON
var __dataURL = "/realtime/rt_queue_query.php";

// this is a global to hold our image cache, ie,
// a map of image URLs to the images themselves
var __imageCache;

// the jquery object of the display
var __display;

// the sign we are going to display
var __sign = "SV_south";

// this is our refresh timer
var __timer;

// date of last refresh
var __lastRefresh;

// current image counter
var __currentImage;

// our timer interval
var __timerInterval;

// are we "live"?
var __live = false;

// time delta sync from server
var __sync = 0;

// the slideshow elements
var __slideshowChildren = null;

function setSign(sign) {
    if (typeof __slideshow != "undefined") {
        __slideshow.stop();
    }
    if (!__slideshowChildren) {
        $("#sign script").remove(); // get rid of script elements which have already executed
        __slideshowChildren = $("#sign").children();
    }
    __slideshowChildren.hide();
    if ($("#rtDisp").length == 0) {
        $("#sign").append('<div id="rtDisp" name="rtDisp" width="416" height="224"></div>');
    }
    __display = $("#rtDisp");
    __sign = sign;

    __display.show();
    refreshImages();
}

function showSlideshow() {
    if (!__display) {
        return;
    }

    window.clearTimeout(__timer);
    __display.hide();
    __display = null;

    __slideshowChildren.show();
    __slideshow.startit();
}

function refreshImages() {
    $("#status").html("refreshing queue...");

    // don't use adjustedDate() here b/c we want the server to
    // tell us how far off we are.
    now = new Date();

    $.get(__dataURL + "?format=json&display=" + __sign + "&timestamp=" + now.getTime(), 
        function(textData, textStatus) {
            // clear timer first
            $("#status").html("got JSON response: "+textData);
            window.clearTimeout(__timer);
            // reset current image counter
            __currentImage = -1;
            __imageCache = new Array();

            // data = JSON.parse(textData);
            data = eval("(" + textData + ")");

            // get time delta sync
            __sync = data.sync;

            $.each(data.images, function(i, item) {
                dispTime = new Date();
                dispTime.setTime(item[1]);
                __imageCache.push(new SignImage(item[0], dispTime, item[2]));
                // alert(item[0] + " " + dispTime);
            });
            // say we're "live"
            __live = true;

            // finally, update the display
            $("#status").html("queue refreshed.");
            handleDisplay();

            __lastRefresh = new Date();
        },
        "text"
    );
}

function adjustedDate() {
    now = new Date();
    // adjust time based on server time diff
    now.setTime(now.getTime() + __sync);

    return now;
}

function updateStatus() {
    d = adjustedDate();
    queue = "";
    for(i = 0; i < __imageCache.length; i++) {
        e = __imageCache[i];
        bold = (i==__currentImage)?"<b>":"";
        unbold = (i==__currentImage)?"</b>":"";
        queue += bold +
            "ts: " + e.getDisplayTime().getTime() + " = " + e.url + unbold + "<br/>";
    }

    $("#status").html("live: " + (__live?"yes":"no") + "<br/>"
        + " queue: " + (__imageCache.length) + "<br/>"
        + " index: " + __currentImage + "<br/>"
        + " wait time: " + __timerInterval + "<br/>"
        + " time: " + d + " (" + d.getTime() + ")<br/>"
        + " ms: " + d.getMilliseconds() + "<br/>"
        + " sync delta: " + __sync + "<br/>"
        + " last refresh: " + __lastRefresh
        + " <p>" + queue + "</p>"
    );
}

function handleDisplay() {
    // ok, let's get our next image and display it
    if (__live && __imageCache.length > 0) {
        now = adjustedDate();
        if (__currentImage == -1) {
            // ok we have new images, we need to find out which
            // one in the list to display
            lastIndex = 0;
            for(i = 0; i < __imageCache.length; i++) {
                if (__imageCache[i].getDisplayTime() > now) {
                    break;
                }
                lastIndex = i;
            }

            if (lastIndex != -1) {
                __currentImage = lastIndex;
            }
        } else {
            // we're still going, see if we can change our
            // image.
            if (__currentImage + 1 >= __imageCache.length) {
                error();
            } else {
                __currentImage++;
            }
        }
    } else {
        // just rotate images one by one
        __currentImage++;
        if (__currentImage == __imageCache.length) {
            __currentImage = 0;
        }
    }


    // calculate when we should be called next
    __imageCache[__currentImage].Display();
    // get a more accurate "now" again
    __timerInterval = 5000; // default
    now = adjustedDate();
    if (__live) {
        if (__currentImage + 1 >= __imageCache.length) {
            error();
        } else {
            __timerInterval = __imageCache[__currentImage+1].getDisplayTime().getTime() - now.getTime();
        }
    }

    if (__timerInterval < 0) {
        error();
        // yeah milliseconds matter -- we spent too much time computing. try again
        //__timerInterval = 10; // ms
        //__currentImage = -1;
    }

    // init timer
    __timer = window.setTimeout("handleDisplay()", __timerInterval);

    // if our last refresh happend 30 s ago, and this is a long
    // timer interval, refresh
    //if (__timerInterval >= 3000 && (now.getTime() - __lastRefresh.getTime()) > 30000) {
    if (__imageCache.length > 1 && ((__timerInterval >= 3000 && __currentImage >= __imageCache.length - 8) || __currentImage >= __imageCache.length - 4)) {
        refreshImages();
    }

    updateStatus();
}

function error() {
    //alert("entering non-live mode");
    __currentImage = 0;
    __live = false;
}

// this is the "image" implementation
function SignImage(url, displayTime, hotlink) {
    this.url = url;
    this.displayTime = displayTime;
    this.image = new Image();
    this.image.src = url;
    this.hotlink = hotlink;
}

SignImage.prototype.Display = function() {
    // change the __display to show us
    /* set the default URL */
    var url = '<img src="/realtime/images/3.jpg" id="realtimeDisplay" width="416" height="224"/>';
    if(this.hotlink != "<empty>")
    {/* append hotlink if exists */
        url = '<a href="' + this.hotlink + '" target="_blank"><img src="' + this.url + '" id="realtimeDisplay" width="416" height="224"/></a>';
    }
    else
    {/* set the image */
        url = '<img src="' + this.url + '" id="realtimeDisplay" width="416" height="224"/>';
    }
    __display.html(url);
}

SignImage.prototype.getDisplayTime = function() {
    return this.displayTime;
}
