/**
* Let the time tick in deal views
*
* @author Martin Rothenberger <martin.rothenberger@dailydeal.de>
* @author Dirk Gustke <dirk.gustke@dailydeal.de>
* @author Jonathan Gilbert <jonathan.gilbert@dailydeal.de>
* @param timestamp
* @return
*/
var targetTimestamp = 0;
var countdownIntervalId = 0;
var defaultPollSoldInterval = 20;
var incrementPollInterval = 20;
var maxPollInterval = 300;
var pollSoldInterval = 20;
var firstCall = true;
var dd_counter;
var remainingTime = 1;
var lastUpdate = 0;

var calibrateTime = function (remainingTime) {
    var localTimestamp = Math.round(new Date().getTime() / 1000);

    // cache the target time to update each second
    if (remainingTime === null) {
        if (targetTimestamp === 0) {
            return;
        }
        remainingTime = targetTimestamp - localTimestamp;
    } else {
        targetTimestamp = localTimestamp + parseInt(remainingTime, 10);
    }

    var seconds = Number(remainingTime % 60);
    var minutes = Number(((remainingTime - seconds) % (3600)) / 60);
    var hours = Number((remainingTime - minutes * 60 - seconds) / 3600);

    seconds = (seconds < 1) ? 0 : seconds;
    minutes = (minutes < 1) ? 0 : minutes;
    hours = (hours < 1) ? 0 : hours;

    seconds = (seconds < 10) ? "0" + seconds : seconds;
    minutes = (minutes < 10) ? "0" + minutes : minutes;

    if ($('#counter_days').length > 0) {
        var days = Math.floor(Number((hours / 24)));
        hours = hours - (days * 24);
        days = (days < 10) ? "0" + days : days;
        $('#counter_days').html(days);
    }
    hours = (hours < 10) ? "0" + hours : hours;

    $('#counter_hours').html(hours);
    $('#counter_minutes').html(minutes);
    $('#counter_seconds').html(seconds);
};

var do_dd_countdown = function () {
    calibrateTime(null);

    // every x seconds, get new values
    var date = new Date();
    var interval = Math.min(defaultPollSoldInterval, incrementPollInterval, pollSoldInterval) * 1000;
    if ((date.getTime() - lastUpdate) > interval) {
        lastUpdate = date.getTime();
        var oldCnt = parseInt($('.dealsalesonp strong').text(), 10);
        var path = '/fast-ajax/getDealsSold/i/' + $('#refer-data').attr('dealId') + '/o/' + oldCnt;
        $.getJSON(path, function (data) {
            if (data.error === 0) {
                calibrateTime(data.remainingTime);
    
                if (data.remainingTime <= 0) { // explode it!
                    window.clearInterval(countdownIntervalId);
                    if (!firstCall) {
                        // only needed if time runs out while page loaded
                        jQuery.getScript(
                            'http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.js',
                            function () {
                                $('#kaufen').effect("explode");
                                window.setTimeout(function () {
                                    $('#buynow').hide();
                                    /* Remove #buynow action from onclick (title and image) */
                                    $('#deal div.dealbild').unbind('click');
                                    $('#deal div.dealbild').css('cursor', 'default');
                                    $('h2.dealhead').unbind('click');
                                    $('h2.dealhead').css('cursor', 'default');
                                    $('#misseddetail').fadeIn('slow');
                                }, 1000);
                            }
                        );
                    }
                    $('#giftButton').hide();
                    $('.timebox').addClass('timebox_v').removeClass('timebox');
                    $('#menu li:nth-child(1) a').removeClass('current');
                    $('#menu li:nth-child(3) a').addClass('current');
                    $('#dealnamePrefix').remove();
                } else {
                    // the value for the current count, is stored differently at the max-quantity-counter
                    if (dd_counter !== null && dd_counter.isLimitedShown) {
                        oldCnt = dd_counter.soldItems;
                    }

                    countUpTo(data.soldItems);

                    // checks if a maximum quantity is provided for the deal. if so, the counter will
                    // switch to a different one.
                    if (dd_counter !== null) {
                        dd_counter.show(data.maximumQuantity > 0 ? dd_counter.limited : dd_counter.origin);
                        dd_counter.setCounterValue(data.soldItems, data.maximumQuantity);
                    }
                }
            }
            firstCall = false;
        });
    }
};


