/*
 * jQuery plugin which inserts a 'latest orders' ticker 
 *
 * $('#ticker').ticker();
 */
(function($){


/* override these in .ticker({...}) */
var options = {
    repeat: 30000, // pause between checks (ms) 
    blinkerRepeat: 1500 // (ms)
};

var lastTimestamp;
var oldText;

// placeholder for the target node
var $ticker;

/* blinker is reattached to text every time it is changed */
var blinker = $('<span>_</span>');
var blinkerBlink = function() {
    blinker.toggle();
    setTimeout(blinkerBlink, options.blinkerRepeat);    
};
blinkerBlink();

/* make a list of tickets out of response */
var ticketList = function(response) {
    var tickets = [];
    var ticket = '';
    for(pName in response.products) {
        ticket = [response.products[pName].n, pName].join(' ');
        if('' !== response.products[pName].landing_page) {
            ticket = ['<a href="',response.products[pName].landing_page,'">',ticket,'</a>'].join('');
        }
        tickets.push(ticket);
    }
    return tickets.slice(0,3).join(', ');
};

/* update target with new information */
var updateTicker = function(response) {

    // join first three elements to country and ago
    var newText = 'Latest order ('+response.ago+' ago) from <span class="country">'+ response.country+
        '</span>:<div class="names">'+ ticketList(response) + ' </div>'; 

    if(newText === oldText) { return; }
    oldText = newText;

    if(lastTimestamp !== response.time) {
        // animate if change of product
        lastTimestamp = response.time;
        $ticker.fadeTo(500, 0.5, function() {
            $ticker.html(newText).find('.names').append(blinker);
            $ticker.fadeTo(500, 1);
        });
    } else {
        $ticker.html(newText).find('.names').append(blinker);
    }

};


/* check service for changes */
var fetchLatest = function() {
    $.getJSON(
        '/services.php', 
        {c:'ticker',action:'latest'}, 
        function(resp,status) {
            if(resp) { updateTicker(resp); } 
            if(options.repeat) { setTimeout(fetchLatest, options.repeat); }
        }
    );
};


/* plugin */
$.fn.ticker = function(opt) {
    $.extend(options, opt);
    return this.each(function(){ 
        $ticker = $(this);
        fetchLatest(); 
    });
};

}(jQuery));


